-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontroller.js
78 lines (67 loc) · 2.15 KB
/
controller.js
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
70
71
72
73
74
75
76
77
78
const axios = require('axios')
const find = require('lodash.find')
const yapi = require('yapi.js');
const baseController = require('controllers/base.js');
class oauth2Controller extends baseController {
constructor(ctx) {
super(ctx);
}
/**
* oauth2回调
* @param {*} ctx
*/
async oauth2Callback(ctx) {
// 获取code和state
const oauthcode = ctx.request.query.code;
const oauthstate = ctx.request.query.state;
if (!oauthcode) {
return (ctx.body = yapi.commons.resReturn(null, 400, 'code不能为空'));
}
// if (!oauthstate) {
// return (ctx.body = yapi.commons.resReturn(null, 400, 'state不能为空'));
// }
// 获取oauth2配置信息
const opts = loadOpts();
if (!opts) {
return (ctx.body = yapi.commons.resReturn(null, 400, 'oauth2未配置,请配置后重新启动服务'));
}
const { authMethod = 'get', authServer, tokenPath, clientId, clientSecret, redirectUri, authArgs } = opts.options;
try {
const tokenResult = await axios.request({
method: authMethod,
baseURL: authServer,
url: tokenPath,
params: Object.assign({
grant_type: 'authorization_code',
client_id: clientId,
client_secret: clientSecret,
code: oauthcode,
oauthstate: oauthstate,
redirect_uri: encodeURIComponent(redirectUri)
}, authArgs)
});
if (tokenResult.status === 200) {
ctx.redirect('/api/user/login_by_token?token=' + tokenResult.data.access_token);
} else {
console.error('oauth2Callback.status.error', tokenResult)
ctx.body = yapi.commons.resReturn(null, tokenResult.status, tokenResult.statusText);
}
} catch (err) {
console.error('oauth2Callback.error', err)
if (err.response) {
ctx.body = yapi.commons.resReturn(null, 400, err.response.message);
} else {
ctx.body = yapi.commons.resReturn(null, 400, err.message);
}
}
}
}
/**
* 加载oauth2配置文件
*/
function loadOpts() {
return find(yapi.WEBCONFIG.plugins, (plugin) => {
return plugin.name === 'auth2';
})
}
module.exports = oauth2Controller;