-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
69 lines (60 loc) · 2.05 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Created by karl on 16/07/15.
*/
/// <reference path='typings/tsd.d.ts' />
'use strict';
import express = require('express');
function compareRole(role:string, compare:string | string[], reverse?: boolean):boolean {
if(Array.isArray(compare)) {
return reverse ? compare.indexOf(role) === -1 : compare.indexOf(role) !== -1;
}
return reverse ? compare !== role : compare === role;
}
export function isLoggedIn(role?: string | string[], reverse?: boolean): express.RequestHandler {
if(role && typeof role !== 'string' && !Array.isArray(role)) {
throw new TypeError('Role has to be string or string[]');
}
return function checkLoggedIn(req:express.Request, res:express.Response, next: Function) {
if(!req.info || !req.info.isLoggedIn) {
res.fail('Unauthorized', 401);
return;
}
if(role && !compareRole(req.info.role, role, reverse)) {
res.fail('Forbidden', 403);
return;
}
next();
}
}
export function hasRole(role: string | string[], reverse?: boolean): express.RequestHandler {
if(typeof role !== 'string' && !Array.isArray(role)) {
throw new TypeError('Role has to be string or string[]');
}
return function checkRole(req:express.Request, res:express.Response, next: Function) {
if(!req.info) {
res.fail('Unauthorized', 401);
return;
}
if(!compareRole(req.info.role, role, reverse)) {
res.fail('Forbidden', 403);
return;
}
next();
}
}
export function isLoggedOut(): express.RequestHandler {
return function checkLoggedOut(req:express.Request, res:express.Response, next: Function) {
if(!req.info) {
res.fail('Unauthorized', 401);
return;
}
if(req.info.role !== 'guest' || req.info.isLoggedIn) {
res.fail('Forbidden', 403);
return;
}
next();
}
}
import RBAC = require('./lib/rbac');
export var setRbac = RBAC.setRbac;
export var rbac = RBAC.rbac;