/**
* @module method/validate
*/
const getUserMeta = require('./get');
const setFailCount = require('./setFailCount');
const {has} = require('lodash');
/**
* Validate a user’s password
*
* @requires method/get
*
* @param {object} user - User object
* @param {string} user.uid - Firebase User ID, e.g. hk_wx5555556.
* @param {string} user.passwordHash - Hashed password.
*
* @return {(object|boolean)} User object with Firebase UID if successfully validated, otherwise returns false.
*/
const password = (user) => {
return getUserMeta(user).then((userMeta) => {
// Throw error if user is not a legacy user and has more than 5 fails
if (!has(userMeta, 'security') && has(userMeta, 'failCount') && userMeta.failCount >= 5) {
throw new Error('User has exceded five fail counts');
}
// check if password hash matches
if (userMeta.passwordHash === user.passwordHash) {
return {
uid: user.uid
};
} else {
// update fail count
return setFailCount(user, true).then(() => {
// return false on success
return false;
}).catch((error) => {
throw error;
});
}
}).catch((error) => {
throw error;
});
};
module.exports = password;