Created
April 19, 2020 13:34
-
-
Save coderkan/4c0726f49eed04ee38d18587e89cd7e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AuthGuard implements CanActivate, CanActivateChild, CanDeactivate<unknown>, CanLoad { | |
constructor(private authService: AuthService, private router: Router) { } | |
canActivate( | |
next: ActivatedRouteSnapshot, | |
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { | |
let url: string = state.url; | |
return this.checkUserLogin(next, url); | |
} | |
canActivateChild( | |
next: ActivatedRouteSnapshot, | |
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { | |
return this.canActivate(next, state); | |
} | |
canDeactivate( | |
component: unknown, | |
currentRoute: ActivatedRouteSnapshot, | |
currentState: RouterStateSnapshot, | |
nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { | |
return true; | |
} | |
canLoad( | |
route: Route, | |
segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean { | |
return true; | |
} | |
checkUserLogin(route: ActivatedRouteSnapshot, url: any): boolean { | |
if (this.authService.isLoggedIn()) { | |
const userRole = this.authService.getRole(); | |
if (route.data.role && route.data.role.indexOf(userRole) === -1) { | |
this.router.navigate(['/home']); | |
return false; | |
} | |
return true; | |
} | |
this.router.navigate(['/home']); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment