Skip to content

Instantly share code, notes, and snippets.

@hongbo-miao
Forked from fxck/config.js
Created May 25, 2016 23:41
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 hongbo-miao/12df3b57b8861425918746eff39d3503 to your computer and use it in GitHub Desktop.
Save hongbo-miao/12df3b57b8861425918746eff39d3503 to your computer and use it in GitHub Desktop.
ng2-permission vs. @ngrx/router
/**
* PLUNKER VERSION (based on systemjs.config.js in angular.io)
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
* Override at the last minute with global.filterSystemConfig (as plunkers do)
*/
(function(global) {
var ngVer = '@2.0.0-rc.1'; // lock in the angular package version; do not let it float to current!
//map tells the System loader where to look for things
var map = {
'app': 'src', // 'dist',
'rxjs': 'https://npmcdn.com/rxjs@5.0.0-beta.6',
'angular2-in-memory-web-api': 'https://npmcdn.com/angular2-in-memory-web-api',
'@ngrx/router': 'https://npmcdn.com/@ngrx/router',
'@ngrx/core': 'https://npmcdn.com/@ngrx/core',
'path-to-regexp': 'https://npmcdn.com/path-to-regexp',
'isarray': 'https://npmcdn.com/isarray',
'query-string': 'https://npmcdn.com/query-string',
'strict-uri-encode': 'https://npmcdn.com/strict-uri-encode'
};
//packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'app.ts', defaultExtension: 'ts' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
'@ngrx/router': { main: 'index.js', defaultExtension: 'js' },
'@ngrx/core': { main: 'index.js', defaultExtension: 'js' }
};
var packageNames = [
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router-deprecated',
'@angular/testing',
'@angular/upgrade',
];
// add map entries for angular packages in the form '@angular/common': 'https://npmcdn.com/@angular/common@0.0.0-3'
packageNames.forEach(function(pkgName) {
map[pkgName] = 'https://npmcdn.com/' + pkgName + ngVer;
});
// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
transpiler: 'typescript',
typescriptOptions: {
emitDecoratorMetadata: true
},
map: map,
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
<!DOCTYPE html>
<html>
<head>
<title>angular2 playground</title>
<link rel="stylesheet" href="styles.css" />
<script src="https://npmcdn.com/zone.js@0.6.12"></script>
<script src="https://npmcdn.com/reflect-metadata@0.1.3"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.27/system.js"></script>
<script src="https://npmcdn.com/typescript@1.8.10/lib/typescript.js"></script>
<script src="config.js"></script>
<script>
System.import('app')
.catch(console.error.bind(console));
</script>
<base href="https://gist.host/">
</head>
<body>
<my-app>
Loading...
</my-app>
</body>
</html>
//our root app component
import { Component, provide } from '@angular/core';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { Http, HTTP_PROVIDERS } from '@angular/http';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { Observable } from 'rxjs/Observable';
import { provideRouter, Routes, Router } from '@ngrx/router';
import { Ng2Permission } from './ng2-permissions';
import { routes } from './routes';
import { User } from './user';
import { UserService } from './user.service';
@Component({
selector: 'my-app',
template : `
<h1>ng2-permission example</h1>
<ul class="c-menu">
<li><a linkTo="/" linkActive="is-active">Home</a></li>
<li><a linkTo="/protected" linkActive="is-active">Protected</a></li>
</ul>
<user
[data]="user$ | async"
(onLogin)="user.logIn()"
(onLogout)="user.logOut()">
</user>
<route-view></route-view>
`,
directives: [ User ],
providers: [ UserService ]
})
export class App {
public user$;
constructor(
public permission: Ng2Permission,
public user: UserService) {
this.user$ = user.getUser();
// defined user role
permission.define('user', () => {
return this.user.isAuthenticated();
});
}
}
bootstrap(App, [
...HTTP_PROVIDERS,
provideRouter(routes),
provide(LocationStrategy, { useClass: HashLocationStrategy }),
Ng2Permission
]).catch(err => console.error(err));
import { Component } from '@angular/core';
import { Ng2Permission } from './ng2-permissions';
@Component({
selector: 'index',
template : `
<p>Hello world!</p>
<div *ngIf="permission.authorize({ only: ['user'] }) | async" >
<p>You can see this cat only because you are logged in</p>
<img src="http://www.helpinghomelesscats.com/images/cat1.jpg" />
</div>
`
})
export class Index {
constructor(public permission: Ng2Permission) { }
}
import {
Directive,
Injectable,
Injector
} from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/merge';
import 'rxjs/add/operator/combineLatest';
import 'rxjs/add/observable/combineLatest';
import { Guard, Router, TraversalCandidate } from '@ngrx/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class Ng2Permission {
private _store: Object = {};
constructor() {}
public define(name: string, validation) {
this._store[name] = validation;
}
public 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(`NgPermission: No defined validation for ${res}`);
}
});
return Observable
.combineLatest(...mergeObsrArr)
.map((res: Array<boolean>) => {
let r = res.some(x => x === true);
if (type === 'only') {
return !!r;
}
if (type === 'except') {
return !r;
}
});
}
}
@Injectable()
export class PermGuard implements Guard {
constructor(private _permission: Ng2Permission, private _router: Router) { }
protectRoute(candidate: TraversalCandidate) {
return this._permission
.authorize(candidate.route.options.permission.rule)
.take(1)
.map(res => {
if (res) {
return true;
} else {
this._router.replace(candidate.route.options.permission.redirectTo);
return false;
}
});
}
}
export const createRule = (rule, redirectTo) => {
return {
rule,
redirectTo
};
};
}
import { Component } from '@angular/core';
@Component({
selector: 'protected',
template : `<p>Hello protected world!</p>`
})
export class Protected {
}
import { provideRouter, Routes } from '@ngrx/router';
import { Index } from './index';
import { Protected } from './protected';
import { PermGuard, createRule } from './ng2-permissions';
export const routes: Routes = [
{
path: '/',
component: Index
},
{
path: '/protected',
component: Protected,
guards: [ PermGuard ],
options: {
permission: createRule({ only: ['user'] }, '/')
}
}
];
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
// just mock states
const INITIAL = {
name: undefined,
isAuthenticated: false
};
const AUTH = {
name: 'foo',
isAuthenticated: true
};
@Injectable()
export class UserService {
private _user$ = new BehaviorSubject<Object>(INITIAL);
public getUser() {
return this._user$;
}
public isAuthenticated() {
return this.getUser().map(res => res.isAuthenticated);
}
public logIn() {
this._user$.next(Object.assign({}, AUTH));
}
public logOut() {
this._user$.next(Object.assign({}, INITIAL));
}
}
import {
Component,
Input,
Output,
EventEmitter
ChangeDetectionStrategy
} from '@angular/core';
@Component({
selector: 'user',
template : `
<div *ngIf="data.isAuthenticated">Logged in as <strong>{{ data.name }}</strong></div>
<button *ngIf="!data.isAuthenticated" (click)="onLogin.next()">Login</button>
<button *ngIf="data.isAuthenticated" (click)="onLogout.next()">Logout</button>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class User {
@Input()
public data;
@Output()
public onLogin = new EventEmitter(false);
@Output()
public onLogout = new EventEmitter(false);
}
* {
font-family: Arial, Helvetica, sans-serif;
}
.c-menu a {
color: black;
}
.c-menu a:hover {
text-decoration: none;
}
.c-menu .is-active {
color: green;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment