-
Notifications
You must be signed in to change notification settings - Fork 13
/
controller.js
84 lines (80 loc) · 2.42 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
79
80
81
82
83
84
const baseController = require('controllers/base.js');
const yapi = require('yapi.js');
const http = require('http');
class oauth2Controller extends baseController {
constructor(ctx) {
super(ctx);
}
/**
* oauth2回调
* @param {*} ctx
*/
async oauth2Callback(ctx) {
try {
// 获取code和state
let oauthcode = ctx.request.query.code;
if (!oauthcode) {
return (ctx.body = yapi.commons.resReturn(null, 400, 'code不能为空'));
}
let oauthstate = ctx.request.query.state;
if (!oauthstate) {
return (ctx.body = yapi.commons.resReturn(null, 400, 'state不能为空'));
}
let ops = yapi.WEBCONFIG.plugins[0].options;
// 通过code获取token
let tokenpath = ops.tokenPath + '?client_id=' + ops.appId + '&client_secret='
+ ops.appSecret + '&code=' + oauthcode + "&grant_type=authorization_code&redirect_uri=" + encodeURIComponent(ops.redirectUri);
let tokenResult = await this.requestInfo(ops, tokenpath, 'POST').then(function(res) {
let jsonRes = JSON.parse(res);
ctx.redirect('/api/user/login_by_token?token=' + jsonRes.access_token);
}).catch(function(rej) {
return {
status_code: rej.statuscode,
message: rej.statusMessage
};
});
return ctx.body = yapi.commons.resReturn(tokenResult, 401, "授权失败");
} catch (err) {
ctx.body = yapi.commons.resReturn(null, 400, err.message);
}
}
/**
* 请求封装
* @param {*} host
* @param {*} port
* @param {*} path
*/
requestInfo(ops, path, method) {
return new Promise((resolve, reject) => {
let req = '';
let http_client = http.request(
{
host: ops.hostname,
method: method,
path: path
},
function(res) {
res.on('error', function(err) {
reject(err);
});
res.setEncoding('utf8');
if (res.statusCode != 200) {
reject({statuscode: res.statusCode, statusMessage: res.statusMessage});
} else {
res.on('data', function(chunk) {
req += chunk;
});
res.on('end', function() {
resolve(req);
});
}
}
);
http_client.on('error', (e) => {
reject({message: 'request error'});
});
http_client.end();
});
}
}
module.exports = oauth2Controller;