Skip to content

Instantly share code, notes, and snippets.

@umutyerebakmaz
Last active October 5, 2020 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umutyerebakmaz/19ef122d8bb97f6364418b34b645df25 to your computer and use it in GitHub Desktop.
Save umutyerebakmaz/19ef122d8bb97f6364418b34b645df25 to your computer and use it in GitHub Desktop.
Angular 10 brings authorization feature to routes according to specified authorizations. It is a simple example that supports multiple roles.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthorizedUserRouteGuard } from '@guards/authorized-user-route.guard';
import { AuthRouteGuard } from '@guards/auth-route.guard';
const routes: Routes = [
{
path: 'admin/depos',
loadChildren: () => import('@app/modules/admin/depos/depos.module').then(m => m.DeposModule),
canActivate: [AuthRouteGuard],
data: {
roles: ['Member', 'Admin'],
routeName: 'admin/depos'
}
},
{
path: 'admin/depos/create',
loadChildren: () => import('@app/modules/admin/depo-create/depo-create.module').then(m => m.DepoCreateModule),
canActivate: [AuthRouteGuard],
data: {
roles: ['Admin'],
routeName: 'admin/depos/create'
}
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { MeGQL, Role } from '@generated-types';
import { MatSnackBar, MatSnackBarRef, SimpleSnackBar } from '@angular/material/snack-bar';
interface FindRoleFn {
routeRoles: string[];
userRoles: string[];
}
@Injectable({
providedIn: 'root'
})
export class AuthRouteGuard implements CanActivate {
constructor(
private meGQL: MeGQL,
private snackBar: MatSnackBar
) { }
findRole({ routeRoles, userRoles }: FindRoleFn): boolean {
return userRoles.some((val) => {
return routeRoles.indexOf(val) >= 0;
});
}
async canActivate(router: ActivatedRouteSnapshot): Promise<boolean> {
const result = await this.meGQL.fetch({}, {
fetchPolicy: 'cache-first'
}).toPromise();
if (result.data.me) {
if (router.data.roles) {
const routeRoles = router.data.roles;
const userRoles = result.data.me.roles.map(role => role.title);
return this.findRole({ routeRoles, userRoles });
}
return true;
}
if (!result.data.me) {
this.openSnackBar('YOU ARE NOT LOGGED!');
return false;
}
}
openSnackBar(text: string): MatSnackBarRef<SimpleSnackBar> {
return this.snackBar.open(text, '', { horizontalPosition: 'center', verticalPosition: 'bottom', duration: 3000 });
}
}
@umutyerebakmaz
Copy link
Author

Angular 10 brings authorization feature to routes according to specified authorizations. It is a simple example that supports multiple roles.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment