2021-09-16 14:36:54 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const { getService } = require('../utils');
|
|
|
|
|
|
|
|
/** @type {import('.').AuthenticateFunction} */
|
2022-08-08 23:33:39 +02:00
|
|
|
const authenticate = async (ctx) => {
|
2021-09-16 14:36:54 +02:00
|
|
|
const { authorization } = ctx.request.header;
|
|
|
|
|
|
|
|
if (!authorization) {
|
|
|
|
return { authenticated: false };
|
|
|
|
}
|
|
|
|
|
|
|
|
const parts = authorization.split(/\s+/);
|
|
|
|
|
|
|
|
if (parts[0].toLowerCase() !== 'bearer' || parts.length !== 2) {
|
|
|
|
return { authenticated: false };
|
|
|
|
}
|
|
|
|
|
|
|
|
const token = parts[1];
|
|
|
|
const { payload, isValid } = getService('token').decodeJwtToken(token);
|
|
|
|
|
|
|
|
if (!isValid) {
|
|
|
|
return { authenticated: false };
|
|
|
|
}
|
|
|
|
|
|
|
|
const user = await strapi
|
|
|
|
.query('admin::user')
|
|
|
|
.findOne({ where: { id: payload.id }, populate: ['roles'] });
|
|
|
|
|
|
|
|
if (!user || !(user.isActive === true)) {
|
|
|
|
return { authenticated: false };
|
|
|
|
}
|
|
|
|
|
|
|
|
const userAbility = await getService('permission').engine.generateUserAbility(user);
|
|
|
|
|
2022-07-29 10:17:06 +02:00
|
|
|
// TODO: use the ability from ctx.state.auth instead of
|
|
|
|
// ctx.state.userAbility, and remove the assign below
|
2021-09-16 14:36:54 +02:00
|
|
|
ctx.state.userAbility = userAbility;
|
|
|
|
ctx.state.user = user;
|
|
|
|
|
2022-07-29 10:17:06 +02:00
|
|
|
return {
|
|
|
|
authenticated: true,
|
|
|
|
credentials: user,
|
|
|
|
ability: userAbility,
|
|
|
|
};
|
2021-09-16 14:36:54 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
/** @type {import('.').AuthStrategy} */
|
|
|
|
module.exports = {
|
|
|
|
name: 'admin',
|
|
|
|
authenticate,
|
|
|
|
};
|