gancio/server/api/auth.js

56 lines
1.1 KiB
JavaScript
Raw Normal View History

2021-03-05 14:17:10 +01:00
const log = require('../log')
2020-01-27 00:47:03 +01:00
const oauth = require('./oauth')
2020-01-30 23:43:58 +01:00
const get = require('lodash/get')
2019-04-03 00:25:12 +02:00
const Auth = {
2019-10-30 14:58:40 +01:00
2020-01-30 12:39:32 +01:00
fillUser (req, res, next) {
2020-01-30 23:43:58 +01:00
const token = get(req.cookies, 'auth._token.local', null)
const authorization = get(req.headers, 'authorization', null)
if (!authorization && token) {
req.headers.authorization = token
}
if (!authorization && !token) {
return next()
}
2020-01-30 12:39:32 +01:00
oauth.oauthServer.authenticate()(req, res, () => {
2022-02-26 21:27:40 +01:00
res.locals.user = get(res, 'locals.oauth.token.user', null)
2020-01-30 12:39:32 +01:00
next()
})
},
2022-07-18 10:05:59 +02:00
isAuth (_req, res, next) {
2022-02-26 21:27:40 +01:00
if (res.locals.user) {
2020-01-30 23:43:58 +01:00
next()
} else {
res.sendStatus(403)
2020-01-30 23:43:58 +01:00
}
},
2019-09-11 19:12:24 +02:00
isAdmin (req, res, next) {
2022-03-10 13:12:37 +01:00
if (res.locals.user && res.locals.user.is_admin) {
2020-01-30 23:43:58 +01:00
next()
} else {
res.sendStatus(403)
2020-01-30 23:43:58 +01:00
}
2020-01-27 00:47:03 +01:00
},
2020-01-30 23:43:58 +01:00
// TODO
2020-01-27 00:47:03 +01:00
hasPerm (scope) {
return (req, res, next) => {
2021-03-05 14:17:10 +01:00
log.debug(scope, req.path)
2021-05-19 16:38:22 +02:00
oauth.oauthServer.authenticate({ scope })(req, res, err => {
if (err) {
next()
} else {
next(Error(err))
}
2020-01-27 00:47:03 +01:00
})
2019-06-06 23:54:32 +02:00
}
2019-09-11 19:12:24 +02:00
}
2019-04-03 00:25:12 +02:00
}
module.exports = Auth