Skip to content

Commit

Permalink
fix(lib, auth): oAuth errors management 馃悰
Browse files Browse the repository at this point in the history
  • Loading branch information
PierreBrisorgueil committed Nov 25, 2020
1 parent bc944dc commit f809a76
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 25 deletions.
8 changes: 7 additions & 1 deletion lib/helpers/errors.js
Expand Up @@ -73,10 +73,16 @@ const getMessageFromErrors = (err) => {
if (err.errors instanceof Array) {
err.errors.map((error) => {
if (error.message) {
output = error.message;
output += `${error.message} `;
}
return null;
});
} else if (err.errors instanceof Object) {
Object.keys(err.errors).forEach((key) => {
if (err.errors[key].message) {
output += `${err.errors[key].message} `;
}
});
} else {
output = err.message;
}
Expand Down
37 changes: 26 additions & 11 deletions lib/middlewares/model.js
Expand Up @@ -7,6 +7,13 @@ const path = require('path');
const config = require(path.resolve('./config'));
const responses = require(path.resolve('./lib/helpers/responses'));

module.exports.cleanError = (string) => string.replace(/conditions\[(.*?)\]/g, '')
.replace(/checks\[(.*?)\]/g, '')
.replace(/"/g, ' ')
.replace(/\./g, ' ')
.replace(/ {2}/g, ' ')
.trim();

/**
* get Joi result
*/
Expand All @@ -28,6 +35,23 @@ module.exports.getResultFromJoi = (body, schema, options) => schema.validate(bod
return data;
});

/**
* check error and return if needed
*/
module.exports.checkError = (result, res) => {
if (result && result.error) {
if (result.error.original && (result.error.original.password || result.error.original.firstname)) result.error.original = _.pick(result.error.original, config.whitelists.users.default);
let description = '';
result.error.details.forEach((err) => {
const message = this.cleanError(err.message);
description += (`${message.charAt(0).toUpperCase() + message.slice(1).toLowerCase()}. `);
});

if (result.error._original && (result.error._original.password || result.error._original.firstname)) result.error._original = _.pick(result.error._original, config.whitelists.users.default);
return responses.error(res, 422, 'Schema validation error', description)(result.error);
}
};

/**
* Check model is Valid with Joi schema
*/
Expand All @@ -40,17 +64,8 @@ module.exports.isValid = (schema) => (req, res, next) => {
}
// Validate req.body using the schema and validation options
const result = this.getResultFromJoi(req.body, schema, options);
// if error
if (result && result.error) {
if (result.error.original && (result.error.original.password || result.error.original.firstname)) result.error.original = _.pick(result.error.original, config.whitelists.users.default);
let description = '';
result.error.details.forEach((err) => {
description += (`${err.message.charAt(0).toUpperCase() + err.message.slice(1).toLowerCase()}. `);
});

if (result.error._original && (result.error._original.password || result.error._original.firstname)) result.error._original = _.pick(result.error._original, config.whitelists.users.default);
return responses.error(res, 422, 'Schema validation error', description)(result.error);
}
// check error
this.checkError(result, res);
// else return req.body with the data after Joi validation
req.body = result.value;
return next();
Expand Down
21 changes: 9 additions & 12 deletions modules/auth/controllers/auth/auth.authentication.controller.js
Expand Up @@ -129,7 +129,7 @@ exports.oauthCallback = async (req, res, next) => {
providerData: {},
};
user.providerData[req.body.key] = req.body.value;
user = await this.checkOAuthUserProfile(user, req.body.key, strategy);
user = await this.checkOAuthUserProfile(user, req.body.key, strategy, res);
const token = jwt.sign({ userId: user.id }, config.jwt.secret, {
expiresIn: config.jwt.expiresIn,
});
Expand Down Expand Up @@ -178,7 +178,7 @@ exports.oauthCallback = async (req, res, next) => {
* @param {Object} providerUserProfile
* @param {Function} done - done
*/
exports.checkOAuthUserProfile = async (profil, key, provider) => {
exports.checkOAuthUserProfile = async (profil, key, provider, res) => {
// check if user exist
try {
const query = {};
Expand All @@ -187,7 +187,7 @@ exports.checkOAuthUserProfile = async (profil, key, provider) => {
const search = await UserService.search(query);
if (search.length === 1) return search[0];
} catch (err) {
throw new AppError('checkOAuthUserProfile', {
throw new AppError('oAuth, find user failed', {
code: 'SERVICE_ERROR',
details: err,
});
Expand All @@ -207,17 +207,14 @@ exports.checkOAuthUserProfile = async (profil, key, provider) => {
UsersSchema.User,
_.clone(config.joi.validationOptions),
);
if (result && result.error) {
throw new AppError('checkOAuthUserProfile schema validation', {
code: 'SERVICE_ERROR',
details: result.error,
});
}
// check error
model.checkError(result, res);
// else return req.body with the data after Joi validation
return await UserService.create(result.value);
} catch (err) {
throw new AppError('checkOAuthUserProfile', {
code: 'SERVICE_ERROR',
details: err,
throw new AppError('oAuth', {
code: 'CONTROLLER_ERROR',
details: err.details || err,
});
}
};
2 changes: 1 addition & 1 deletion modules/auth/routes/auth.routes.js
Expand Up @@ -25,5 +25,5 @@ module.exports = (app) => {
// Setting the oauth routes
app.route('/api/auth/:strategy').get(auth.oauthCall);
app.route('/api/auth/:strategy/callback').get(auth.oauthCallback);
app.route('/api/auth/:strategy/callback').post(model.isValid(usersSchema.User), auth.oauthCallback); // specific for apple call back
app.route('/api/auth/:strategy/callback').post(auth.oauthCallback); // specific for apple call back
};

0 comments on commit f809a76

Please sign in to comment.