import { HttpClient } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { catchError, map, Observable, of } from 'rxjs'; import { LoginResponse, RegisterResponse } from './responses/auth'; import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthService { private readonly API_BASE: string = "http://localhost:5000" private readonly SESSION_COOKIE: string = "session"; private readonly USERNAME_FIELD: string = "username"; private readonly PASSWORD_FIELD: string = "password"; private readonly REPEAT_PASSWORD_FIELD: string = "repeatPassword"; constructor(private http: HttpClient) { } public Login(username: string, password: string): Observable { let url = `${this.API_BASE}/auth/login`; let formData = new FormData(); formData.append(this.USERNAME_FIELD, username); formData.append(this.PASSWORD_FIELD, password); return this.http.post(url, formData, { withCredentials: true }) } public Register(username: string, password: string, repeatPassword: string): Observable { let url = `${this.API_BASE}/auth/register`; let formData = new FormData(); formData.append(this.USERNAME_FIELD, username); formData.append(this.PASSWORD_FIELD, password); formData.append(this.REPEAT_PASSWORD_FIELD, repeatPassword); return this.http.post(url, formData, { withCredentials: true }) } public Logout(): Observable { let url = `${this.API_BASE}/auth/logout`; return this.http.get(url, { withCredentials: true }).pipe( map(() => true), catchError(() => of(false)) ); } public Bump(): Observable { let url = `${this.API_BASE}/auth/bump` return this.http.get(url, { withCredentials: true }).pipe( map(() => true), catchError(() => of(false)) ); } public IsLoggedIn(): boolean { let cookies = document.cookie.split(';'); let found = false; cookies.forEach(cookie => { cookie = cookie.trim(); found = found || cookie.startsWith(this.SESSION_COOKIE + "=") && cookie.split('=', 2)[1] != ''; }); return found; } } export const IsLoggedInCanActivate: CanActivateFn = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ) => { if (inject(AuthService).IsLoggedIn()) { return true; } else { inject(Router).navigateByUrl("auth/login"); return false; } }