|
1 |
| -const router = require('koa-router')() |
| 1 | +const router = require("koa-router")(); |
| 2 | +const crypto = require("crypto"); |
2 | 3 |
|
3 |
| -router.prefix('/users') |
| 4 | +const secret = process.env.secret; |
4 | 5 |
|
5 |
| -router.get('/', function (ctx, next) { |
6 |
| - ctx.body = 'this is a users response!' |
7 |
| -}) |
| 6 | +router.prefix("/api/v1/user"); |
8 | 7 |
|
9 |
| -router.get('/bar', function (ctx, next) { |
10 |
| - ctx.body = 'this is a users/bar response' |
11 |
| -}) |
| 8 | +function encrypt(str) { |
| 9 | + const cipher = crypto.createCipher("aes192", secret); |
| 10 | + let enc = cipher.update(str, "utf8", "hex"); //编码方式从utf-8转为hex; |
| 11 | + enc += cipher.final("hex"); //编码方式从转为hex; |
| 12 | + return enc; |
| 13 | +} |
12 | 14 |
|
13 |
| -module.exports = router |
| 15 | +function decrypt(str) { |
| 16 | + const decipher = crypto.createDecipher("aes192", secret); |
| 17 | + let dec = decipher.update(str, "hex", "utf8"); //编码方式从hex转为utf-8; |
| 18 | + dec += decipher.final("utf8"); //编码方式从utf-8; |
| 19 | + return dec; |
| 20 | +} |
| 21 | + |
| 22 | +router.get("/", async (ctx) => { |
| 23 | + const token = ctx.cookies.get("token"); |
| 24 | + |
| 25 | + if (token) { |
| 26 | + const duser = decrypt(token); |
| 27 | + if (db.find((q) => q.login === duser.login)) return duser; |
| 28 | + } |
| 29 | + const code = ctx.query.code; |
| 30 | + const { access_token } = await fetch( |
| 31 | + `https://github.com/login/oauth/access_token?code=${code}&client_id=${clientId}&client_secret=${clientSecret}`, |
| 32 | + { |
| 33 | + method: "POST", |
| 34 | + headers: { |
| 35 | + Accept: "application/json", |
| 36 | + }, |
| 37 | + } |
| 38 | + ).then((res) => res.json()); |
| 39 | + |
| 40 | + const user = await fetch("https://api.github.com/user", { |
| 41 | + headers: { |
| 42 | + Accept: "application/json", |
| 43 | + Authorization: `token ${access_token}`, |
| 44 | + }, |
| 45 | + }).then((res) => res.json()); |
| 46 | + if (user.login) { |
| 47 | + loginedUsers.add(user.login); |
| 48 | + } |
| 49 | + if (db.find((q) => q.login === user.login)) { |
| 50 | + ctx.cookies.set("token", encrypt(JSON.stringify(user))); |
| 51 | + ctx.body = { |
| 52 | + ...user, |
| 53 | + pay: true, |
| 54 | + }; |
| 55 | + } else { |
| 56 | + ctx.body = { |
| 57 | + ...user, |
| 58 | + pay: false, |
| 59 | + }; |
| 60 | + } |
| 61 | +}); |
| 62 | + |
| 63 | +module.exports = router; |
0 commit comments