[[oktatas:web:angular|< Angular]]
====== Angular - Útvonalak védelme ======
* **Szerző:** Sallai András
* Copyright (c) 2024, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]]
* Web: https://szit.hu
===== Fő komponens =====
===== AuthService =====
Az AuthService osztályban szükségünk lesz egy isLoggedIn() metódusra.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
isLoggedIn() {
return true;
}
}
===== AuthGuard =====
Az egyes útvonalak védelméről a guard nevű eszközzel tudunk gondoskodni.
A shared nevű könyvtárban fogom létrehozni (nem kötelező itt létrehozni):
ng generate guard shared/auth
Rövidítéssel:
ng g g shared/auth
Létrehozáskor rákérdez milyen típusokat szeretnénk:
>(*) CanActivate
( ) CanActivateChild
( ) CanDeactivate
( ) CanLoad
A szóközzel jelölhetek ki, a le és fel billentyűvel választhatok, az Enter billentyűre továbblép.
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
if (!authService.isLoggedIn()) {
return false;
}
return true;
};
===== Komponens =====
Legyen egy védett komponens Valami névű.
ng g c valami
===== Routing =====
import { Routes } from '@angular/router';
import { ValamiComponent } from './valami/valami.component';
import { authGuard } from './shared/auth.guard';
export const routes: Routes = [
{
path: 'valami',
component: ValamiComponent,
canActivate: [authGuard]
},
];
===== Teszt =====
A böngészőbe írjuk be:
http://localhost:4200/valami
Próbáljuk meg true és false értékkel is az isLoggedIn() függvényben.
//...
isLoggedIn() {
return true;
}
===== Az AuthService javítása =====
Javítsuk az isLoggedIn() függvényt:
isLoggedIn() {
return !!localStorage.getItem('login_token');
}
===== Teljes kód =====
Teljes kód:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
login(user: string, pass: string): boolean {
if(user === 'admin' && pass === 'admin') {
const authToken = 'aaa'
localStorage.setItem('login_token', authToken);
return true;
}else {
return false;
}
}
logout() {
localStorage.removeItem('login_token');
}
isLoggedIn() {
return !!localStorage.getItem('login_token');
}
}