2020-05-11 17:09:48 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const passport = require('koa-passport');
|
|
|
|
const { Strategy: LocalStrategy } = require('passport-local');
|
|
|
|
|
|
|
|
const createLocalStrategy = strapi => {
|
|
|
|
return new LocalStrategy(
|
|
|
|
{
|
|
|
|
usernameField: 'email',
|
|
|
|
passwordField: 'password',
|
|
|
|
session: false,
|
|
|
|
},
|
|
|
|
function(email, password, done) {
|
|
|
|
return strapi.admin.services.auth
|
|
|
|
.checkCredentials({ email, password })
|
|
|
|
.then(([error, user, message]) => done(error, user, message))
|
2020-05-13 11:46:52 +02:00
|
|
|
.catch(error => done(error));
|
2020-05-11 17:09:48 +02:00
|
|
|
}
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = strapi => ({
|
|
|
|
initialize() {
|
|
|
|
passport.use(createLocalStrategy(strapi));
|
|
|
|
|
|
|
|
strapi.app.use(passport.initialize());
|
2020-05-12 14:57:24 +02:00
|
|
|
|
|
|
|
strapi.app.use(async (ctx, next) => {
|
|
|
|
if (
|
|
|
|
ctx.request.header.authorization &&
|
|
|
|
ctx.request.header.authorization.split(' ')[0] === 'Bearer'
|
|
|
|
) {
|
|
|
|
const token = ctx.request.header.authorization.split(' ')[1];
|
|
|
|
|
2020-05-13 11:46:52 +02:00
|
|
|
const { payload, isValid } = strapi.admin.services.token.decodeToken(token);
|
2020-05-12 14:57:24 +02:00
|
|
|
|
|
|
|
if (isValid) {
|
|
|
|
// request is made by an admin
|
2020-05-12 20:46:48 +02:00
|
|
|
const admin = await strapi.query('user', 'admin').findOne({ id: payload.id }, []);
|
2020-05-12 14:57:24 +02:00
|
|
|
|
2020-05-12 20:46:48 +02:00
|
|
|
if (!admin || !(admin.isActive === true)) {
|
2020-05-12 14:57:24 +02:00
|
|
|
return ctx.forbidden('Invalid credentials');
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.state.admin = admin;
|
|
|
|
ctx.state.user = admin;
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return next();
|
|
|
|
});
|
2020-05-11 17:09:48 +02:00
|
|
|
},
|
|
|
|
});
|