2020-12-03 21:29:01 +01:00
|
|
|
const auth = require('basic-auth');
|
2017-11-16 16:45:01 +01:00
|
|
|
const User = require('../user');
|
|
|
|
const AuthenticationRequired = require('../authentication-required');
|
|
|
|
|
2019-03-03 11:41:56 +01:00
|
|
|
function unsecureAuthentication(basePath = '', app) {
|
|
|
|
app.post(`${basePath}/api/admin/login`, (req, res) => {
|
2017-11-16 16:45:01 +01:00
|
|
|
const user = req.body;
|
|
|
|
req.session.user = new User({ email: user.email });
|
2018-11-22 20:47:06 +01:00
|
|
|
res.status(200)
|
2017-11-16 16:45:01 +01:00
|
|
|
.json(req.session.user)
|
|
|
|
.end();
|
|
|
|
});
|
|
|
|
|
2019-03-03 11:41:56 +01:00
|
|
|
app.use(`${basePath}/api/admin/`, (req, res, next) => {
|
2017-11-16 16:45:01 +01:00
|
|
|
if (req.session.user && req.session.user.email) {
|
|
|
|
req.user = req.session.user;
|
2020-12-03 21:29:01 +01:00
|
|
|
} else if (req.header('authorization')) {
|
|
|
|
const user = auth(req);
|
|
|
|
if (user && user.name) {
|
|
|
|
req.user = new User({ username: user.name });
|
|
|
|
}
|
2017-11-16 16:45:01 +01:00
|
|
|
}
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
2019-03-03 11:41:56 +01:00
|
|
|
app.use(`${basePath}/api/admin/`, (req, res, next) => {
|
2017-11-16 16:45:01 +01:00
|
|
|
if (req.user) {
|
2020-04-14 22:29:11 +02:00
|
|
|
return next();
|
2017-11-16 16:45:01 +01:00
|
|
|
}
|
2020-04-14 22:29:11 +02:00
|
|
|
return res
|
|
|
|
.status('401')
|
|
|
|
.json(
|
|
|
|
new AuthenticationRequired({
|
|
|
|
path: `${basePath}/api/admin/login`,
|
|
|
|
type: 'unsecure',
|
|
|
|
message:
|
2021-02-04 12:21:08 +01:00
|
|
|
'You have to identify yourself in order to use Unleash.',
|
2020-04-14 22:29:11 +02:00
|
|
|
}),
|
|
|
|
)
|
|
|
|
.end();
|
2017-11-16 16:45:01 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = unsecureAuthentication;
|