const Repository = require('../repository/repository'); const passwordService = require('./passwordService'); const userRepository = new Repository('users'); class UserService { /** * Get a user from database by its login. * @param {String} login User login. * @param {Function} onSuccess Callback function to execute if a user exists with this login. * @param {Function} onError Callback function to execute if not any user exists with this login. */ getUser(login, onSuccess, onError) { userRepository.find({login: login}, results => onSuccess(results[0]), onError); } /** * Checks if credentials matches to an existing user, that have this password. * @param {String} login User login. * @param {String} password User password, in plain text. * @param {Function} onSuccess Callback function to execute if a user exists with this login. * @param {Function} onError Callback function to execute if not any user exists with this login. */ checkCredentials(login, password, onSuccess, onError) { this.getUser( login, dbUser => { if (!!dbUser && passwordService.areSamePasswords(password, dbUser.password)) { onSuccess(); } else { onError(); } }, // If login is incorrect, the "getUser" function will return "undefined". // So if "user" is "undefined", this proofs that login is incorrect onError ); } } const singleton = new UserService(); module.exports = singleton;