misc fixes, add ability to attach local auth to social user

This commit is contained in:
Matteo Pagliazzi
2015-11-23 12:47:15 +01:00
parent 3459b51cef
commit a26f713e18
5 changed files with 85 additions and 60 deletions

View File

@@ -4,7 +4,7 @@
"missingEmail": "Missing email.", "missingEmail": "Missing email.",
"missingUsername": "Missing username.", "missingUsername": "Missing username.",
"missingPassword": "Missing password.", "missingPassword": "Missing password.",
"invalidEmail": "Invalid email address.", "notAnEmail": "Invalid email address.",
"emailTaken": "Email already taken.", "emailTaken": "Email already taken.",
"usernameTaken": "Username already taken.", "usernameTaken": "Username already taken.",
"passwordConfirmationMatch": "Password confirmation doesn't match password.", "passwordConfirmationMatch": "Password confirmation doesn't match password.",
@@ -12,5 +12,7 @@
"invalidCredentials": "User not found with given auth credentials.", "invalidCredentials": "User not found with given auth credentials.",
"accountSuspended": "Account has been suspended, please contact leslie@habitica.com with your UUID \"<%= userId %>\" for assistance.", "accountSuspended": "Account has been suspended, please contact leslie@habitica.com with your UUID \"<%= userId %>\" for assistance.",
"onlyFbSupported": "Only Facebook supported currently.", "onlyFbSupported": "Only Facebook supported currently.",
"cantDetachFb": "Account lacks another authentication method, can't detach Facebook." "cantDetachFb": "Account lacks another authentication method, can't detach Facebook.",
"onlySocialAttachLocal": "Local auth can only be added to a social account.",
"invalidReqParams": "Invalid request parameters."
} }

View File

@@ -39,9 +39,9 @@ describe('POST /user/auth/local/register', () => {
password, password,
confirmPassword: confirmPassword, confirmPassword: confirmPassword,
})).to.eventually.be.rejected.and.eql({ })).to.eventually.be.rejected.and.eql({
code: 401, code: 400,
error: 'NotAuthorized', error: 'BadRequest',
message: t('passwordConfirmationMatch'), message: t('invalidReqParams'),
}); });
}); });
@@ -56,9 +56,9 @@ describe('POST /user/auth/local/register', () => {
password, password,
confirmPassword, confirmPassword,
})).to.eventually.be.rejected.and.eql({ })).to.eventually.be.rejected.and.eql({
code: 401, code: 400,
error: 'NotAuthorized', error: 'BadRequest',
message: t('missingUsername'), message: t('invalidReqParams'),
}); });
}); });
@@ -72,9 +72,9 @@ describe('POST /user/auth/local/register', () => {
password, password,
confirmPassword: password, confirmPassword: password,
})).to.eventually.be.rejected.and.eql({ })).to.eventually.be.rejected.and.eql({
code: 401, code: 400,
error: 'NotAuthorized', error: 'BadRequest',
message: t('missingEmail'), message: t('invalidReqParams'),
}); });
}); });
@@ -90,9 +90,9 @@ describe('POST /user/auth/local/register', () => {
password, password,
confirmPassword: password, confirmPassword: password,
})).to.eventually.be.rejected.and.eql({ })).to.eventually.be.rejected.and.eql({
code: 401, code: 400,
error: 'NotAuthorized', error: 'BadRequest',
message: t('invalidEmail'), message: t('invalidReqParams'),
}); });
}); });
@@ -107,9 +107,9 @@ describe('POST /user/auth/local/register', () => {
email: email, email: email,
confirmPassword: confirmPassword, confirmPassword: confirmPassword,
})).to.eventually.be.rejected.and.eql({ })).to.eventually.be.rejected.and.eql({
code: 401, code: 400,
error: 'NotAuthorized', error: 'BadRequest',
message: t('missingPassword'), message: t('invalidReqParams'),
}); });
}); });
}); });

View File

@@ -12,7 +12,7 @@ import { sendTxn as sendTxnEmail } from '../../libs/api-v3/email';
let api = {}; let api = {};
/** /**
* @api {post} /user/auth/local/register Register a new user with email, username and password or add local authentication to a social user * @api {post} /user/auth/local/register Register a new user with email, username and password or attach local auth to a social user
* @apiVersion 3.0.0 * @apiVersion 3.0.0
* @apiName UserRegisterLocal * @apiName UserRegisterLocal
* @apiGroup User * @apiGroup User
@@ -22,21 +22,32 @@ let api = {};
* @apiParam {String} password Password for the new user account * @apiParam {String} password Password for the new user account
* @apiParam {String} confirmPassword Password confirmation * @apiParam {String} confirmPassword Password confirmation
* *
* @apiSuccess {Object} user The user object * @apiSuccess {Object} user The user object, if we just attached local auth to a social user then only user.auth.local
*/ */
api.registerLocal = { api.registerLocal = {
method: 'POST', method: 'POST',
middlewares: [authWithHeaders(true)],
url: '/user/auth/local/register', url: '/user/auth/local/register',
handler (req, res, next) { handler (req, res, next) {
let { email, username, password, confirmPassword } = req.body; let fbUser = res.locals.user; // If adding local auth to social user
// Validate required params req.checkBody({
if (!username) return next(new NotAuthorized(res.t('missingUsername'))); email: {
if (!email) return next(new NotAuthorized(res.t('missingEmail'))); notEmpty: {errorMessage: res.t('missingEmail')},
if (!validator.isEmail(email)) return next(new NotAuthorized(res.t('invalidEmail'))); isEmail: {errorMessage: res.t('notAnEmail')},
if (!password) return next(new NotAuthorized(res.t('missingPassword'))); },
if (password !== confirmPassword) return next(new NotAuthorized(res.t('passwordConfirmationMatch'))); username: {notEmpty: {errorMessage: res.t('missingUsername')}},
password: {
notEmpty: {errorMessage: res.t('missingPassword')},
equals: {options: [req.body.confirmPassword], errorMessage: res.t('passwordConfirmationMatch')},
},
});
let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors);
let { email, username, password } = req.body;
// Get the lowercase version of username to check that we do not have duplicates // Get the lowercase version of username to check that we do not have duplicates
// So we can search for it in the database and then reject the choosen username if 1 or more results are found // So we can search for it in the database and then reject the choosen username if 1 or more results are found
email = email.toLowerCase(); email = email.toLowerCase();
@@ -57,7 +68,7 @@ api.registerLocal = {
let salt = passwordUtils.makeSalt(); let salt = passwordUtils.makeSalt();
let hashed_password = passwordUtils.encrypt(password, salt); // eslint-disable-line camelcase let hashed_password = passwordUtils.encrypt(password, salt); // eslint-disable-line camelcase
let newUser = new User({ let newUser = {
auth: { auth: {
local: { local: {
username, username,
@@ -70,11 +81,17 @@ api.registerLocal = {
preferences: { preferences: {
language: req.language, language: req.language,
}, },
}); };
if (fbUser) {
if (!fbUser.auth.facebook.id) throw new NotAuthorized(res.t('onlySocialAttachLocal'));
fbUser.auth.local = newUser;
return fbUser.save();
} else {
newUser = new User(newUser);
newUser.registeredThrough = req.headers['x-client']; // TODO is this saved somewhere? newUser.registeredThrough = req.headers['x-client']; // TODO is this saved somewhere?
return newUser.save(); return newUser.save();
}
}) })
.then((savedUser) => { .then((savedUser) => {
res.status(201).json(savedUser); res.status(201).json(savedUser);
@@ -84,12 +101,14 @@ api.registerLocal = {
.remove({email: savedUser.auth.local.email}) .remove({email: savedUser.auth.local.email})
.then(() => sendTxnEmail(savedUser, 'welcome')); .then(() => sendTxnEmail(savedUser, 'welcome'));
if (!savedUser.auth.facebook.id) {
res.analytics.track('register', { res.analytics.track('register', {
category: 'acquisition', category: 'acquisition',
type: 'local', type: 'local',
gaLabel: 'local', gaLabel: 'local',
uuid: savedUser._id, uuid: savedUser._id,
}); });
}
}) })
.catch(next); .catch(next);
}, },
@@ -225,7 +244,7 @@ api.loginSocial = {
api.deleteSocial = { api.deleteSocial = {
method: 'DELETE', method: 'DELETE',
url: '/user/auth/social/:network', url: '/user/auth/social/:network',
middlewares: [authWithHeaders], middlewares: [authWithHeaders()],
handler (req, res, next) { handler (req, res, next) {
let user = res.locals.user; let user = res.locals.user;
let network = req.params.network; let network = req.params.network;

View File

@@ -8,11 +8,14 @@ import {
} from '../../models/user'; } from '../../models/user';
// Authenticate a request through the x-api-user and x-api key header // Authenticate a request through the x-api-user and x-api key header
export function authWithHeaders (req, res, next) { // If optional is true, don't error on missing authentication
export function authWithHeaders (optional = false) {
return function authWithHeadersHandler (req, res, next) {
let userId = req.header['x-api-user']; let userId = req.header['x-api-user'];
let apiToken = req.header['x-api-key']; let apiToken = req.header['x-api-key'];
if (!userId || !apiToken) { if (!userId || !apiToken) {
if (optional) return next();
return next(new BadRequest(res.t('missingAuthHeaders'))); return next(new BadRequest(res.t('missingAuthHeaders')));
} }
@@ -31,6 +34,7 @@ export function authWithHeaders (req, res, next) {
next(); next();
}) })
.catch(next); .catch(next);
}
} }
// Authenticate a request through a valid session // Authenticate a request through a valid session

View File

@@ -36,7 +36,7 @@ export default function errorHandler (err, req, res, next) {
// Handle errors by express-validator // Handle errors by express-validator
if (Array.isArray(err) && err[0].param && err[0].msg) { if (Array.isArray(err) && err[0].param && err[0].msg) {
responseErr = new BadRequest('Invalid request parameters.'); responseErr = new BadRequest(res.t('invalidReqParams'));
responseErr.errors = err; // TODO format responseErr.errors = err; // TODO format
} }