File

src/app/auth/auth.service.ts

Description

Service for authentication which handels http requests for signup and login and holds the authentication token.

Index

Properties
Methods

Constructor

constructor(http: HttpClient, router: Router)

This is for binding the HttpClient and Router to this component.

Parameters :
Name Type Optional
http HttpClient No
router Router No

Methods

autoAuthUser
autoAuthUser()

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()

Clear the authentication data saved in local storage by removing the items.

Returns : void
createUser
createUser(name: string, email: string, password: string)

Create a new user by sending the data to the server via http post request.

Parameters :
Name Type Optional Description
name string No

name the user entered as username

email string No

mail adress the user entered

password string No

password the user entered

Returns : void
Private getAuthData
getAuthData()

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()

Getter for AuthStatusListener.

Returns : any

return the authStatusListener as observable

getIsAuth
getIsAuth()

Getter for isAuthenticated.

Returns : boolean

return if the user is authenticated or not

getToken
getToken()

Getter for token.

Returns : string

return the token of the user

login
login(email: string, password: string, name)

Login a user by sending the data to the server via http post request.

Parameters :
Name Type Optional Description
email string No

mail adress the user entered

password string No

password the user entered

name No

null in this case

Returns : void
logout
logout()

Logout the user by setting token to null, isAuthenticatedto false, clear the tokenTimer and so on and redirect to homepage.

Returns : void
Private saveAuthData
saveAuthData(token: string, expirationDate: Date)

Save authentication data in local storage

Parameters :
Name Type Optional Description
token string No

token of the user

expirationDate Date No

expiration date of the token

Returns : void
Private setAuthTimer
setAuthTimer(duration: number)

Setter for tokenTimer

Parameters :
Name Type Optional Description
duration number No

duration in ms

Returns : void

Properties

Private authStatusListener
Default value : new Subject<boolean>()

Listener for the status of authentication.

Private isAuthenticated
Default value : false

False if the user is not authenticated, true if the user is authenticated.

Private token
Type : string

Token of the current user.

Private tokenTimer
Type : any

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)
    }
  }

}

results matching ""

    No results matching ""