72 lines
2.4 KiB
JavaScript
72 lines
2.4 KiB
JavaScript
'use strict';
|
|
|
|
const _ = require('lodash');
|
|
const httpStatus = require('http-status');
|
|
const passport = require('passport');
|
|
const controllerHelper = require('../../helpers/controller.helper');
|
|
const messageHelper = require('../../helpers/message.helper');
|
|
const securityHelper = require('../../helpers/security.helper');
|
|
const authService = require('./auth.service');
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
// CONSTANTS
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Module Name
|
|
const MODULE_NAME = '[auth.controller]';
|
|
|
|
// Error Messages
|
|
const NOT_FOUND = 'Videogame not found';
|
|
|
|
// Success Messages
|
|
const VG_CT_VIDEOGAME_DELETED_SUCCESSFULLY = 'Videogame deleted successfully';
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
// PUBLIC METHODS
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
async function login(req, res, next) {
|
|
try {
|
|
passport.authenticate('local', { session: false }, async (error, user, info) => {
|
|
try {
|
|
if (!user) {
|
|
return res.status(httpStatus.NOT_FOUND).json(messageHelper.buildMessage(NOT_FOUND));
|
|
}
|
|
|
|
req.login(user, { session: false }, async (error) => {
|
|
if (error) {
|
|
return controllerHelper.handleErrorResponse(MODULE_NAME, login.name, error, res);
|
|
}
|
|
|
|
//We don't want to store the sensitive information such as the
|
|
//user password in the token so we pick only the email and id
|
|
const data = {
|
|
id: user.id,
|
|
email: user.email
|
|
};
|
|
|
|
//Send back the token to the user
|
|
return res.json({
|
|
token: securityHelper.generateToken({ user: data }),
|
|
user: {
|
|
id: data.id,
|
|
email: data.email
|
|
},
|
|
});
|
|
});
|
|
} catch (error) {
|
|
return next(error);
|
|
}
|
|
})(req, res, next);
|
|
|
|
} catch (error) {
|
|
controllerHelper.handleErrorResponse(MODULE_NAME, login.name, error, res)
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = {
|
|
login,
|
|
MODULE_NAME
|
|
} |