-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Future of this library #1
Comments
import {
Injectable,
} from '@angular/core';
import {
CanActivate,
Router,
ActivatedRouteSnapshot
} from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class Permission {
private _store: Object = {};
define(name: string, validation) {
this._store[name] = validation;
}
authorize(authObj) {
if (authObj.only && authObj.except) {
throw new Error('Authorization object cannot contain both [only] and [except]');
}
if (authObj.only) {
return this._checkAuthorization(authObj.only, 'only');
}
if (authObj.except) {
return this._checkAuthorization(authObj.except, 'except');
}
}
private _checkAuthorization(names, type) {
const mergeObsrArr: Array<Observable<boolean>> = [];
names.forEach((res) => {
if (this._store[res]) {
mergeObsrArr.push(this._store[res].call());
} else {
console.warn(`Permission: No defined validation for ${res}`);
}
});
return Observable
.combineLatest(...mergeObsrArr)
.map((res: boolean[]) => {
let r = res.some((x) => x === true);
if (type === 'only') {
return !!r;
}
if (type === 'except') {
return !r;
}
});
}
}
@Injectable()
export class PermGuard implements CanActivate {
constructor(private _permission: Permission, private _router: Router) { }
canActivate(route: ActivatedRouteSnapshot) {
return this._permission
.authorize(route.data['permission'].rule)
.take(1)
.map((res) => {
if (res) {
return true;
} else {
this._router.navigate(route.data['permission'].redirectTo);
return false;
}
});
}
}
export function createRule(
rule: { 'only': string[] } | { 'except': string[] },
redirectTo: any[]) {
return {
rule,
redirectTo
};
}; |
usage route:
app.module.ts constructor(private _permission: Permission) {
this._permission.define(ROLES.user, () => {
return this.user$.map((user) => {
return user && user.role === ROLES.user;
});
});
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @fxck,
Do you have any plans to make it compatible with Angular 4+?
The text was updated successfully, but these errors were encountered: