Add renew token

Signed-off-by: Alexandre Bodin <bodin.alex@gmail.com>
This commit is contained in:
Alexandre Bodin 2020-05-12 13:21:26 +02:00
parent ceb11379fc
commit 298dcac271
3 changed files with 57 additions and 20 deletions

View File

@ -59,6 +59,11 @@
"path": "/login", "path": "/login",
"handler": "authentication.login" "handler": "authentication.login"
}, },
{
"method": "POST",
"path": "/renew-token",
"handler": "authentication.renewToken"
},
{ {
"method": "POST", "method": "POST",
"path": "/auth/local/register", "path": "/auth/local/register",

View File

@ -3,17 +3,20 @@
const passport = require('koa-passport'); const passport = require('koa-passport');
const compose = require('koa-compose'); const compose = require('koa-compose');
const login = compose([ module.exports = {
login: compose([
(ctx, next) => { (ctx, next) => {
return passport.authenticate('local', { session: false }, (err, user, info) => { return passport.authenticate('local', { session: false }, (err, user, info) => {
if (err) { if (err) {
ctx.body = { error: 'Internal server error' }; return ctx.badImplementation();
} else if (!user) { }
ctx.body = { error: info.error };
} else { if (!user) {
return ctx.badRequest(info.error);
}
ctx.state.user = user; ctx.state.user = user;
return next(); return next();
}
})(ctx, next); })(ctx, next);
}, },
ctx => { ctx => {
@ -26,8 +29,25 @@ const login = compose([
}, },
}; };
}, },
]); ]),
module.exports = { renewToken(ctx) {
login, const { token } = ctx.request.body;
if (token === undefined) {
return ctx.badRequest('Token is required.');
}
const { isValid, payload } = strapi.admin.services.auth.decodeToken(token);
if (!isValid) {
return ctx.badRequest('Invalid token.');
}
ctx.body = {
data: {
token: strapi.admin.services.auth.createJwtToken(payload.id),
},
};
},
}; };

View File

@ -8,7 +8,7 @@ const sanitizeUser = user => {
return _.omit(user, ['password', 'resetPasswordToken']); return _.omit(user, ['password', 'resetPasswordToken']);
}; };
const defaultOptions = { expiresIn: '30d' }; const defaultOptions = { expiresIn: '1s' };
const getJWTOptions = () => { const getJWTOptions = () => {
const { options, secret } = strapi.config.get('server.admin.jwt', {}); const { options, secret } = strapi.config.get('server.admin.jwt', {});
@ -78,6 +78,17 @@ const checkCredentials = async ({ email, password }) => {
return [null, user]; return [null, user];
}; };
const decodeToken = token => {
const { secret } = getJWTOptions();
try {
const payload = jwt.verify(token, secret);
return { payload, isValid: true };
} catch (err) {
return { payloda: null, isValid: false };
}
};
module.exports = { module.exports = {
checkCredentials, checkCredentials,
createJwtToken, createJwtToken,
@ -85,4 +96,5 @@ module.exports = {
validatePassword, validatePassword,
hashPassword, hashPassword,
getJWTOptions, getJWTOptions,
decodeToken,
}; };