typescript Angular 2应用程序角色访问装饰器,包装内置CanAccess功能。当用户角色不是ap时,防止视图转换
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript Angular 2应用程序角色访问装饰器,包装内置CanAccess功能。当用户角色不是ap时,防止视图转换相关的知识,希望对你有一定的参考价值。
import { Injector } from 'angular2/core';
import { CanActivate, ComponentInstruction } from 'angular2/router';
import { Authentication } from '../services/authentication';
import { Storage } from '../services/storage';
import { CurrentUser } from '../interfaces/common';
export const Roles = (...rolesAllowed : Array<string>) => {
return CanActivate((next: ComponentInstruction, prev: ComponentInstruction) => {
//this would not work if user info was not being kept in session storage
//as of now it doesn't seem possible to access same-instance application services through non-components
const injector = Injector.resolveAndCreate([Authentication, Storage]);
const authentication : Authentication = injector.get(Authentication);
const userRoles : Array<string> = authentication.userRoles;
return isAllowedAccess(rolesAllowed, userRoles);
});
};
const isAllowedAccess = (rolesAllowed: Array<string>, currentRoles: Array<string>) => {
const intersectedRoles = currentRoles.reduce((acc, curr) => {
return [
...acc,
...rolesAllowed.filter(role => role.trim().toUpperCase() === curr.trim().toUpperCase())
]
}, []);
return intersectedRoles.length > 0;
};
import { Component } from 'angular2/core';
import { Roles } from '../decorators/roles';
@Component({
selector: 'home',
template: `<h1>{{title}}</h1>`
})
@Roles('ADMIN')
export default class Home{
title : string = "Home View!";
}
import { Injectable } from 'angular2/core';
import { Storage } from './storage';
import { CurrentUser } from '../interfaces/common';
@Injectable()
export class Authentication{
private _storageService : Storage;
private _userKey : string = "CURRENT_USER";
constructor(storageService : Storage){
this._storageService = storageService;
}
authenticate(name : string, password: string){
return new Promise((resolve, reject) => {
setTimeout(() => {
this.currentUser = {
name,
roles : ['ADMIN']
};
resolve(true);
}, 100);
});
}
logOut(){
this._storageService.removeStorage(this._userKey);
}
get userRoles() : Array<string> {
const user = this._storageService.getStorage(this._userKey);
return user ? user.roles : [];
}
get currentUser() : CurrentUser {
return this._storageService.getStorage(this._userKey);
}
set currentUser(user : CurrentUser){
this._storageService.setStorage(this._userKey, user);
}
}
以上是关于typescript Angular 2应用程序角色访问装饰器,包装内置CanAccess功能。当用户角色不是ap时,防止视图转换的主要内容,如果未能解决你的问题,请参考以下文章
Angular 2 Typescript 编译错误
带有 Ionic 2 Angular 2 和 TypeScript 的 OpenPGP
使用 SignalR 的 Angular 2 TypeScript
Angular 2\TypeScript 中 export 关键字的确切含义是啥?
Typescript 2 + Angular googlemaps 打字稿定义
使用 Visual Studio Code 调试和运行 Angular 2 Typescript?