-
Notifications
You must be signed in to change notification settings - Fork 0
/
apitoken.js
75 lines (71 loc) · 2.14 KB
/
apitoken.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
// Add a new function to player sandbox space
// Some Super Secret Secret (32 character hex string)
const secretFile = `${__dirname}/secret.bin`
const fs = require('fs')
try {
fs.accessSync(secretFile)
} catch(e) {
fs.writeFileSync(secretFile, require('crypto').randomBytes(16))
}
const secret = fs.readFileSync(secretFile); // Buffer.from('DEADBEEF000000000000000000000000', 'hex')
const jwt = require('./lib/jwt')
module.exports = function (config) {
if (config.engine) {
config.engine.onPlayerSandbox = function (sandbox) {
sandbox.getAPIToken = function () {
let key = generateToken(sandbox.module.user)
sandbox.console.log('API KEY:', key)
}
}
}
if (config.backend) {
const path = require('path')
const basicAuth = require('basic-auth')
const authlib = require(path.join(path.dirname(require.main.filename), '../lib/authlib'))
config.backend.router.post('/auth/signin', (req, res) => {
let { email, password } = req.body
try {
if (email != 'token') throw new Error('invalid email')
let data = verifyToken(req.body.password)
authlib.genToken(data.user)
.then(token => {
res.json({ ok: 1, token})
})
} catch(e) {
console.error(e)
res.status(401).json({ error: 'unauthorized' })
}
})
let preConfig = config.backend.onExpressPreConfig
config.backend.onExpressPreConfig = function (app) {
app.post('/user/code', (req, res, next) => {
let { name, pass } = basicAuth(req)
try {
if (name != 'token') return next()
let data = verifyToken(pass)
authlib.genToken(data.user)
.then(token => {
req.headers['x-token'] = token
next()
})
} catch(e) {
next()
}
})
return preConfig(app)
}
}
}
function sha128 (val) {
return require('crypto').createHash('sha128').update(val).digest()
}
function generateToken (userid) {
let data = {
iat: Date.now(),
user: userid
}
return jwt.encode(data, secret)
}
function verifyToken (token) {
return jwt.decode(token, secret)
}