You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.3 KiB
89 lines
2.3 KiB
|
|
const jwt = require('jsonwebtoken')
|
|
const camelcase = require('camelcase')
|
|
const CFG = require('../../config')
|
|
const TOL = require('../../tools/common')
|
|
const ObjectId = require('mongodb').ObjectId
|
|
|
|
const MSG = {
|
|
USER: {
|
|
NOT_ALLOWED: 'User:NotAllowed'
|
|
}
|
|
}
|
|
|
|
/**
|
|
* For each received request, check the jwt token and user rights
|
|
*
|
|
* @param {HttpRequest} req Http request from client
|
|
* @param {HttpResponse} res Http context to answer to client
|
|
* @param {Function} next Callback to continue the Express pipe
|
|
*/
|
|
module.exports = function (pCtx) {
|
|
return (req, res, next) => {
|
|
if (req.method === 'OPTIONS') return next()
|
|
// Find token in the request. Can be set in:
|
|
// - header
|
|
// - token field : {token}
|
|
// - Authorization field : "Bearer {token}"
|
|
// - query
|
|
// - token field
|
|
let lToken
|
|
if (req.headers.token) {
|
|
lToken = req.headers.token
|
|
} else if (req.query.token) {
|
|
lToken = req.query.token
|
|
} else if (req.headers.authorization) {
|
|
let match = req.headers.authorization.match(/Bearer ?(.*)/)
|
|
if (match) {
|
|
lToken = match[1]
|
|
}
|
|
} else {
|
|
// To be removed when client is ready to use full auth API
|
|
if (!CFG.jwt.enable) {
|
|
return pCtx.db.collection('users')
|
|
.find({username: 'admin'})
|
|
.limit(1)
|
|
.next(function (pErr, pUser) {
|
|
// console.log(pUser)
|
|
req.user = pUser
|
|
next()
|
|
})
|
|
} else {
|
|
return res.done(401, 'jwtAccess:Missing')
|
|
}
|
|
}
|
|
|
|
// Decrypt received token
|
|
jwt.verify(lToken, CFG.jwt.jwtAccess.secret, function (pErr, pToken) {
|
|
if (pErr) {
|
|
return res.done(401, new Error(`jwtAccess:${camelcase(pErr.message, {pascalCase: true})}`))
|
|
}
|
|
|
|
res.token = pToken
|
|
|
|
let payloadState = TOL.jwt.checkPayload(req, res.token.data)
|
|
if (payloadState) {
|
|
return res.done(401, 'jwtAccess:CorruptedPayload:' + payloadState)
|
|
}
|
|
|
|
req.user = res.token.data.user
|
|
try { req.user._id = ObjectId(req.user.id) } catch (e) {}
|
|
delete req.user.pass
|
|
|
|
next()
|
|
})
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Projects user fields to be public compliant
|
|
* @param {Object} pUser Public-ified user
|
|
*/
|
|
function JOB_getPublicUser (pUser) {
|
|
return {
|
|
id: pUser.id,
|
|
user: pUser.user,
|
|
role: pUser.role,
|
|
name: pUser.name
|
|
}
|
|
}
|