Skip to content

Commit

Permalink
feat(users): rework tokens ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
PierreBrisorgueil committed May 24, 2019
1 parent 03a5466 commit 88a8191
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 33 deletions.
1 change: 1 addition & 0 deletions config/defaults/development.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ module.exports = {
},
jwt: {
secret: 'test',
expiresIn: 7 * 24 * 60 * 60, // sec
},
mailer: {
from: 'WAOS_NODE_mailer_from',
Expand Down
41 changes: 21 additions & 20 deletions modules/users/controllers/users/users.authentication.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ const noReturnUrls = [
exports.signup = async (req, res) => {
try {
const user = await UserService.create(req.body);
const token = jwt.sign({ userId: user.id }, config.jwt.secret);
const token = jwt.sign({ userId: user.id }, config.jwt.secret, { expiresIn: config.jwt.expiresIn });
return res.status(200)
.cookie('TOKEN', token, { httpOnly: true })
.json({ user, tokenExpiresIn: Date.now() + (3600 * 24 * 1000) });
.json({ user, tokenExpiresIn: Date.now() + (config.jwt.expiresIn * 1000) });
} catch (err) {
responses.error(res, 422, errors.getMessage(err))(err);
}
Expand All @@ -43,35 +43,36 @@ exports.signup = async (req, res) => {
*/
exports.signin = async (req, res) => {
const user = req.user;
const token = jwt.sign({ userId: user.id }, configuration.jwt.secret);
const token = jwt.sign({ userId: user.id }, configuration.jwt.secret, { expiresIn: config.jwt.expiresIn });
return res.status(200)
.cookie('TOKEN', token, { httpOnly: true })
.json({ user, tokenExpiresIn: Date.now() + (3600 * 24 * 1000) });
.json({ user, tokenExpiresIn: Date.now() + (config.jwt.expiresIn * 1000) });
};

/**
* @desc Endpoint to generate a token
* @desc Endpoint to get a new token if old is ok
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
exports.token = async (req, res) => {
try {
// Authenticate the user based on credentials
// @TODO be consistent with whether the login field for user identification
// is a username or an email
const user = await UserService.authenticate(req.body.email, req.body.password);
// Create the token and send
// @TODO properly create the token with all of its metadata
const payload = {
id: user.id,
let user = null;
if (req.user) {
user = {
id: req.user.id,
provider: escape(req.user.provider),
username: escape(req.user.username),
roles: req.user.roles,
profileImageURL: req.user.profileImageURL,
email: escape(req.user.email),
lastName: escape(req.user.lastName),
firstName: escape(req.user.firstName),
additionalProvidersData: req.user.additionalProvidersData,
};
// @TODO properly sign the token, not with a shared secret (use pubkey instead),
// and specify proper expiration, issuer, algorithm, etc.
const token = jwt.sign(payload, config.jwt.secret);
return res.status(200).cookies('TOKEN', token);
} catch (err) {
responses.error(res, 422, errors.getMessage(err))(err);
}
const token = jwt.sign({ userId: user.id }, configuration.jwt.secret, { expiresIn: config.jwt.expiresIn });
return res.status(200)
.cookie('TOKEN', token, { httpOnly: true })
.json({ user, tokenExpiresIn: Date.now() + (config.jwt.expiresIn * 1000) });
};

/**
Expand Down
10 changes: 5 additions & 5 deletions modules/users/controllers/users/users.profile.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ exports.changeProfilePicture = async (req, res) => {
exports.me = (req, res) => {
// Sanitize the user - short term solution. Copied from core.controller.js
// TODO create proper passport mock: See https://gist.github.com/mweibel/5219403
let safeUserObject = null;
let user = null;
if (req.user) {
safeUserObject = {
user = {
id: req.user.id,
provider: escape(req.user.provider),
username: escape(req.user.username),
Expand All @@ -72,7 +72,7 @@ exports.me = (req, res) => {
additionalProvidersData: req.user.additionalProvidersData,
};
}
return responses.success(res, 'user get')(safeUserObject);
return responses.success(res, 'user get')(user);
};

/**
Expand All @@ -89,9 +89,9 @@ exports.addOAuthProviderUserProfile = async (req, res) => {
}
if (!user) return responses.error(res, 404, 'No Oauth found')();

const token = jwt.sign({ userId: user.id }, config.jwt.secret);
const token = jwt.sign({ userId: user.id }, config.jwt.secret, { expiresIn: config.jwt.expiresIn });

res.status(200)
.cookie('TOKEN', token, { httpOnly: true })
.json({ user, tokenExpiresIn: Date.now() + (3600 * 24 * 1000) });
.json({ user, tokenExpiresIn: Date.now() + (config.jwt.expiresIn * 1000) });
};
10 changes: 2 additions & 8 deletions modules/users/routes/auth.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,8 @@ module.exports = (app) => {
app.route('/api/auth/signup').post(model.isValid(usersSchema.User), users.signup);
app.route('/api/auth/signin').post(passport.authenticate('local'), users.signin);

// Jwt token
app.route('/api/auth/token').post(model.isValid(usersSchema.User), users.token);
// Jwt protected route example:
// app.route('/api/auth/secretPlace').get(passport.authenticate('jwt'), (req, res) => {
// console.log(req.user)
// console.log(req.isAuthenticated())
// res.status(200).send()
// })
// Jwt reset token
app.route('/api/auth/token').get(passport.authenticate('jwt'), users.token);

// Setting the oauth routes
app.route('/api/auth/:strategy').get(users.oauthCall);
Expand Down

0 comments on commit 88a8191

Please sign in to comment.