File: /var/dev/nowruzgan/rest/api/controllers/user/auth-cb.js
var jwt = require('jsonwebtoken');
var uuid = require('uuid');
module.exports = {
friendlyName: 'AuthCB',
inputs: {
access_token: {
type: 'string',
required: true
},
id_token: {
type: 'string',
required: true
},
state: {
type: 'string',
required: false
}
},
exits: {
dbError: { statusCode: 500 },
success: {responseType: 'redirect'},
},
fn: async function (inputs, exits) {
let action = 'user.auth-callback';
sails.log.info({session: null, action, message: `Auth callback.`});
let callback = sails.config.custom.auth0.callback;
let userInfo;
try {
userInfo = jwt.decode(inputs.id_token);
}catch(e) {
return exits.error({error: 500, errorMessage: 'Authentication problem.'});
}
let user = await User.findOne({sub: userInfo.sub}).populate('roles')
.intercept(sails.log.interceptError(null, action, `on finding user with sub: ${userInfo.sub}`, 'dbError'));
if(!user){
user = await User.create({
sub: userInfo.sub,
firstName: userInfo.given_name,
lastName: userInfo.family_name,
}).fetch()
.intercept(sails.log.interceptError(null, action, `on creating user for ${userInfo.sub}`, 'dbError'));
sails.log.info({session: null, action, message: `User ${userInfo.sub} <${userInfo.given_name}-${userInfo.family_name}> created`});
}
let token = uuid();
let sessionData = {
publicUser: User.getPublic(user),
user: user,
token: token,
iat: userInfo.iat,
exp: userInfo.exp,
timestamp: (new Date()).valueOf()
};
await sails.helpers.cache.with({action: 'set', key: `${token}:session`, value: sessionData});
exits.success(callback.replace('__TOKEN__', token));
}
};