Files
cloud-cap-samples/gdpr/srv/auth.js
2022-02-03 17:57:35 +01:00

43 lines
1.2 KiB
JavaScript

/*
* workaround to avoid approuter et al. setup
*
* DO NOT USE FOR PRODUCTION!
* - no token validation
* - no xsappname check
*/
const jwt = require('jsonwebtoken')
const tenant = process.env.VCAP_SERVICES
? JSON.parse(process.env.VCAP_SERVICES).xsuaa[0].credentials.tenantid
: 'anonymous'
module.exports = (req, res, next) => {
// decode JWT coming from Personal Data Manager
const bearer = req.headers.authorization && req.headers.authorization.split('Bearer ')[1]
if (bearer) {
const { client_id: id, zid: tenant, scope: roles } = jwt.decode(bearer)
req.user = {
id,
tenant,
is: role => roles.some(r => r.endsWith(`.${role}`))
}
return next()
}
// mock user that has every role EXCEPT PersonalDataManagerUser
const basic = req.headers.authorization && req.headers.authorization.split('Basic ')[1]
if (basic) {
const [id] = Buffer.from(basic, 'base64').toString('utf-8').split(':')
req.user = {
id,
tenant,
// is: role => role !== 'PersonalDataManagerUser'
is: role => true
}
return next()
}
// no bearer & no basic -> 401
res.set('WWW-Authenticate', 'Basic realm="Users"').status(401).end()
}