parent
c7f748d6c3
commit
b86a2d83aa
@ -0,0 +1,15 @@
|
|||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { CanActivateFn, Router } from '@angular/router';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
|
||||||
|
export const authGuard: CanActivateFn = (route, state) => {
|
||||||
|
const authService = inject(AuthService);
|
||||||
|
const router = inject(Router);
|
||||||
|
|
||||||
|
if (authService.isLoggedIn()) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
router.navigate(['/home']);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
@ -0,0 +1,14 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-login',
|
||||||
|
template: ``,
|
||||||
|
})
|
||||||
|
export class LoginComponent {
|
||||||
|
constructor(private authService: AuthService, private router: Router) {
|
||||||
|
this.authService.login();
|
||||||
|
this.router.navigate(['/ingredients']);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-logout',
|
||||||
|
template: ``,
|
||||||
|
})
|
||||||
|
export class LogoutComponent {
|
||||||
|
constructor(private authService: AuthService, private router: Router) {
|
||||||
|
this.authService.logout();
|
||||||
|
this.router.navigate(['/home']);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { BehaviorSubject, Observable } from 'rxjs';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class AuthService {
|
||||||
|
private readonly adminKey = 'isAdmin';
|
||||||
|
private loggedInSubject: BehaviorSubject<boolean> =
|
||||||
|
new BehaviorSubject<boolean>(this.isLoggedIn());
|
||||||
|
|
||||||
|
get loggedIn$(): Observable<boolean> {
|
||||||
|
return this.loggedInSubject.asObservable();
|
||||||
|
}
|
||||||
|
|
||||||
|
login() {
|
||||||
|
localStorage.setItem(this.adminKey, 'true');
|
||||||
|
this.loggedInSubject.next(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
logout() {
|
||||||
|
localStorage.removeItem(this.adminKey);
|
||||||
|
this.loggedInSubject.next(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
isLoggedIn(): boolean {
|
||||||
|
return localStorage.getItem(this.adminKey) === 'true';
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue