src/app/auth/auth.service.ts
Service for authentication which handels http requests for signup and login and holds the authentication token.
Properties |
|
Methods |
|
constructor(http: HttpClient, router: Router)
|
|||||||||
Defined in src/app/auth/auth.service.ts:34
|
|||||||||
This is for binding the
Parameters :
|
autoAuthUser |
autoAuthUser()
|
Defined in src/app/auth/auth.service.ts:120
|
Get the auth data and authenticate user automatically if there are data and the token is not expiered yet.
Returns :
void
finish the method if no information is available |
Private clearAuthDate |
clearAuthDate()
|
Defined in src/app/auth/auth.service.ts:171
|
Clear the authentication data saved in local storage by removing the items.
Returns :
void
|
createUser | ||||||||||||||||
createUser(name: string, email: string, password: string)
|
||||||||||||||||
Defined in src/app/auth/auth.service.ts:73
|
||||||||||||||||
Create a new user by sending the data to the server via http post request.
Parameters :
Returns :
void
|
Private getAuthData |
getAuthData()
|
Defined in src/app/auth/auth.service.ts:182
|
Getter for authentication data.
Returns :
{ token: any; expirationDate: any; }
return null if there is no token and/or expiration date stored in local storage and return token and expiration date if both are available |
getAuthStatusListener |
getAuthStatusListener()
|
Defined in src/app/auth/auth.service.ts:63
|
Getter for
Returns :
any
return the authStatusListener as observable |
getIsAuth |
getIsAuth()
|
Defined in src/app/auth/auth.service.ts:55
|
Getter for
Returns :
boolean
return if the user is authenticated or not |
getToken |
getToken()
|
Defined in src/app/auth/auth.service.ts:47
|
Getter for
Returns :
string
return the token of the user |
login | ||||||||||||||||
login(email: string, password: string, name)
|
||||||||||||||||
Defined in src/app/auth/auth.service.ts:91
|
||||||||||||||||
Login a user by sending the data to the server via http post request.
Parameters :
Returns :
void
|
logout |
logout()
|
Defined in src/app/auth/auth.service.ts:138
|
Logout the user by setting
Returns :
void
|
Private saveAuthData | ||||||||||||
saveAuthData(token: string, expirationDate: Date)
|
||||||||||||
Defined in src/app/auth/auth.service.ts:163
|
||||||||||||
Save authentication data in local storage
Parameters :
Returns :
void
|
Private setAuthTimer | ||||||||
setAuthTimer(duration: number)
|
||||||||
Defined in src/app/auth/auth.service.ts:153
|
||||||||
Setter for
Parameters :
Returns :
void
|
Private authStatusListener |
Default value : new Subject<boolean>()
|
Defined in src/app/auth/auth.service.ts:34
|
Listener for the status of authentication. |
Private isAuthenticated |
Default value : false
|
Defined in src/app/auth/auth.service.ts:19
|
False if the user is not authenticated, true if the user is authenticated. |
Private token |
Type : string
|
Defined in src/app/auth/auth.service.ts:24
|
Token of the current user. |
Private tokenTimer |
Type : any
|
Defined in src/app/auth/auth.service.ts:29
|
Timer until the token expires. |
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { Subject } from "rxjs";
import { environment } from "src/environments/environment";
import { AuthData } from "./auth-data.model";
/**
* Service for authentication which handels http requests for signup and login and holds the authentication token.
*/
@Injectable({ providedIn: "root" })
export class AuthService {
/**
* False if the user is not authenticated, true if the user is authenticated.
*/
private isAuthenticated = false;
/**
* Token of the current user.
*/
private token: string;
/**
* Timer until the token expires.
*/
private tokenTimer: any;
/**
* Listener for the status of authentication.
*/
private authStatusListener = new Subject<boolean>();
/**
* This is for binding the `HttpClient` and `Router` to this component.
* @param http
* @param router
*/
constructor(private http: HttpClient, private router: Router) {}
/**
* Getter for `token`.
* @returns return the token of the user
*/
getToken() {
return this.token;
}
/**
* Getter for `isAuthenticated`.
* @returns return if the user is authenticated or not
*/
getIsAuth() {
return this.isAuthenticated;
}
/**
* Getter for `AuthStatusListener`.
* @returns return the authStatusListener as observable
*/
getAuthStatusListener() {
return this.authStatusListener.asObservable();
}
/**
* Create a new user by sending the data to the server via http post request.
* @param name name the user entered as username
* @param email mail adress the user entered
* @param password password the user entered
*/
createUser(name: string, email: string, password: string){
const authData: AuthData = {name: name, email: email, password: password};
this.http
.post( environment.apiUrl + "/user/signup", authData)
.subscribe(() => {
console.log("Signup done");
this.router.navigate(['/login']);
}, error => {
this.authStatusListener.next(false);
});
}
/**
* Login a user by sending the data to the server via http post request.
* @param email mail adress the user entered
* @param password password the user entered
* @param name null in this case
*/
login(email:string, password: string, name: null){
const authData: AuthData = {name: name, email: email, password: password};
this.http.post<{token: string, expiresIn: number, userID: string, userName: string}>( environment.apiUrl + "/user/login", authData)
.subscribe(response => {
console.log(response);
const token = response.token;
this.token = token;
localStorage.setItem('currentUserID', response.userID);
if (token) {
const expiresInDuration = response.expiresIn;
this.setAuthTimer(expiresInDuration);
this.isAuthenticated = true;
this.authStatusListener.next(true);
const now = new Date();
const expirationDate = new Date(now.getTime() + expiresInDuration * 1000);
console.log(expirationDate);
this.saveAuthData(token, expirationDate);
localStorage.setItem("username", response.userName);
this.router.navigate(['/list']);
}
}, error => {
this.authStatusListener.next(false);
});
}
/**
* Get the auth data and authenticate user automatically if there are data and the token is not expiered yet.
* @returns finish the method if no information is available
*/
autoAuthUser() {
const authInformatin = this.getAuthData();
if (!authInformatin) {
return;
}
const now = new Date();
const expiresIn = authInformatin.expirationDate.getTime() - now.getTime(); // duration in ms
if (expiresIn > 0) {
this.token = authInformatin.token;
this.isAuthenticated = true;
this.setAuthTimer(expiresIn / 1000);
this.authStatusListener.next(true);
}
}
/**
* Logout the user by setting `token` to null, `isAuthenticated`to false, clear the `tokenTimer` and so on and redirect to homepage.
*/
logout() {
this.token = null;
this.isAuthenticated = false;
this.authStatusListener.next(false);
clearTimeout(this.tokenTimer);
this.clearAuthDate();
localStorage.setItem('currentUserID', "null");
localStorage.setItem("username", "null");
this.router.navigate(['/']);
}
/**
* Setter for `tokenTimer`
* @param duration duration in ms
*/
private setAuthTimer(duration: number){
console.log("Setting timer: " + duration);
this.tokenTimer = setTimeout(() => { this.logout(); }, duration * 1000);
}
/**
* Save authentication data in local storage
* @param token token of the user
* @param expirationDate expiration date of the token
*/
private saveAuthData(token: string, expirationDate: Date){
localStorage.setItem('token', token);
localStorage.setItem('expiration', expirationDate.toISOString());
}
/**
* Clear the authentication data saved in local storage by removing the items.
*/
private clearAuthDate(){
localStorage.removeItem('token');
localStorage.removeItem('expiration');
localStorage.setItem('currentUserID', "null");
localStorage.setItem("username", "null");
}
/**
* Getter for authentication data.
* @returns return null if there is no token and/or expiration date stored in local storage and return token and expiration date if both are available
*/
private getAuthData() {
const token = localStorage.getItem('token');
const expirationDate = localStorage.getItem('expiration');
if (!token || !expirationDate) {
return null;
}
return {
token: token,
expirationDate: new Date(expirationDate)
}
}
}