Initial commit for the Angular part. We are nowhere yet.
This commit is contained in:
41
bookie/src/app/auth/auth-guard.service.ts
Normal file
41
bookie/src/app/auth/auth-guard.service.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {AuthService} from './auth.service';
|
||||
import {Observable} from 'rxjs/internal/Observable';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {ToasterService} from '../core/toaster.service';
|
||||
import {User} from '../user/user';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthGuard implements CanActivate {
|
||||
|
||||
constructor(private auth: AuthService, private router: Router, private toaster: ToasterService) {
|
||||
}
|
||||
|
||||
static checkUser(permission: string, user: User, router: Router, state: RouterStateSnapshot, toaster: ToasterService): boolean {
|
||||
if (!user.isAuthenticated) {
|
||||
router.navigate(['login'], {queryParams: {returnUrl: state.url}});
|
||||
toaster.show('Danger', 'User is not authenticated');
|
||||
return false;
|
||||
}
|
||||
const hasPermission = permission === undefined || user.perms.indexOf(permission) !== -1;
|
||||
if (!hasPermission) {
|
||||
toaster.show('Danger', 'You do not have the permission to access this area.');
|
||||
}
|
||||
return hasPermission;
|
||||
}
|
||||
|
||||
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
|
||||
if (this.auth.user === undefined) {
|
||||
return this.auth.userObservable
|
||||
.pipe(
|
||||
map<User, boolean>((value: User) => AuthGuard.checkUser(
|
||||
route.data['permission'], value, this.router, state, this.toaster
|
||||
))
|
||||
);
|
||||
}
|
||||
return AuthGuard.checkUser(route.data['permission'], this.auth.user, this.router, state, this.toaster);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user