-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
58 lines (45 loc) · 1.67 KB
/
index.js
File metadata and controls
58 lines (45 loc) · 1.67 KB
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
const AuthError = require('yan-error-class').AuthError;
const defaultAuthorization = function (ctx) {
return ctx && ctx['session'] && (typeof ctx['session']['user'] === 'object');
};
const defaultInvalidCallback = function () {
throw new AuthError('未登录或登录过期,请重新登录');
};
const defaultOptions = {
authorFunc: defaultAuthorization,
invalidCallback: defaultInvalidCallback,
exceptUrls: ['/login', '/logout'],
redirectUrl: '/login'
};
module.exports = function (options = {}) {
const authorFunc = getFunction(options.authorFunc) || defaultOptions.authorFunc;
const invalidCallback = getFunction(options.invalidCallback) || defaultOptions.invalidCallback;
const exceptUrls = getArray(options.exceptUrls) || defaultOptions.exceptUrls;
const apiRegxStr = getString(options.apiRegxStr);
const redirectUrl = getString(options.redirectUrl) || defaultOptions.redirectUrl;
return async function koaAuth(ctx, next) {
const isLogin = await authorFunc(ctx);
if (isLogin) {
return next();
}
if (exceptUrls.indexOf(ctx.url) !== -1) {
return next();
}
if (apiRegxStr && new RegExp(apiRegxStr).test(ctx.url)) {
return invalidCallback(ctx, next);
} else if (!ctx.accepts('html')) {
console.log('ddd');
return invalidCallback(ctx, next);
}
ctx.redirect(redirectUrl);
}
};
function getFunction(func) {
return typeof func === 'function' ? func : false;
}
function getArray(arr) {
return Array.isArray(arr) ? arr : false;
}
function getString(str) {
return typeof str === 'string' ? str : false;
}