Skip to content
Snippets Groups Projects
Select Git revision
  • 6209fe643d22b29ad01b05cdb7a099f51c70b708
  • main default protected
  • documentation
  • admin_rights_refactor
4 results

authentication.service.ts

Blame
  • Forked from an inaccessible project.
    authentication.service.ts 1.51 KiB
    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Router } from '@angular/router';
    import jwtDecode from 'jwt-decode';
    import { User } from '../Types/types';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthenticationService {
    
      constructor(
        private http: HttpClient,
        private router: Router) { }
    
    
      login(username:string, password:string): void {
    
        const body = {
          username, password
        }
    
        const headers = new Headers({
            'Content-Type': 'application/json'
          });
    
        this.http.post('http://0.0.0.0:30992/API/v1/login', body, {observe: 'response'})
        .subscribe(res => {
          if(res.ok) {
            
            localStorage.setItem("token", res.body.toString());
            this.router.navigateByUrl("/");
          }
          else {
            // sheeeeeeeesh
          }
        }); 
      }
      
      isLoggedIn(): Boolean {
        return localStorage.getItem("token") !== null;
      }
    
      logout(): void {
        localStorage.removeItem("token");
        this.router.navigateByUrl("/");
      }
    
      private getDecodedAccessToken(): User {
        try {
          return jwtDecode(localStorage.getItem("token")) as User;
        } catch(Error) {
          return null;
        }
      }
    
      isAdmin(): Boolean {
        const user = this.getDecodedAccessToken() as User;
        
        if (user === null)
          return false;
        return user.type === 'admin';
      }
    
      getUsername(): string {
        const user = this.getDecodedAccessToken() as User;
    
        if(user === null)
          return "Guest";
        return user.username;
      }
    
    }