nfp_sites/api/jwt.mjs

70 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-02-19 11:34:52 +00:00
import _ from 'lodash'
import jwt from 'jsonwebtoken'
import koaJwt from 'koa-jwt'
2019-09-14 19:03:38 +00:00
import Staff from './staff/model.mjs'
import config from './config.mjs'
2019-02-19 11:34:52 +00:00
export default class Jwt {
constructor(opts = {}) {
Object.assign(this, {
Staff: opts.Staff || Staff,
jwt: opts.jwt || jwt,
})
}
sign(value, appendSecret = '', opts) {
let secret = config.get('jwt:secret') + appendSecret
let options = _.defaults(opts, config.get('jwt:options'))
if (options.expiresIn === null) {
delete options.expiresIn
}
return this.jwt.sign(value, secret, options)
}
signDirect(value, secret) {
return this.jwt.sign(value, secret)
}
verify(token, appendSecret = '') {
let secret = config.get('jwt:secret') + appendSecret
return new Promise((resolve, reject) =>
this.jwt.verify(token, secret, (err, res) => {
if (err) return reject(err)
resolve(res)
})
)
}
decode(token) {
return this.jwt.decode(token)
}
2019-02-20 16:10:37 +00:00
createToken(email, level, opts) {
2019-02-19 11:34:52 +00:00
return this.sign({
2019-02-20 16:10:37 +00:00
email: email,
level: level,
}, email, opts)
2019-02-19 11:34:52 +00:00
}
static jwtMiddleware() {
return koaJwt({
getToken: ctx => {
if (ctx.request.header.authorization) {
return ctx.request.header.authorization.split(' ')[1]
}
if (ctx.query.token) {
return ctx.query.token
}
return null
},
2019-02-19 11:34:52 +00:00
secret: (header, payload) =>
2019-02-22 14:53:43 +00:00
`${config.get('jwt:secret')}${payload.email}`,
2019-02-19 11:34:52 +00:00
passthrough: true,
})
}
}