src/utils/AuthenticationUtils.js
/**
* AuthenticationUtils
* Provides functions used for authentication of therapist
*/
import {getIdFromUsername, isValidPassword} from '../database/TherapistsDAO';
/**
* Process the login and set the variables to the correct value.
* @param {String} username - Username of the user
* @param {function} setUsername - Set the username of the user (string)
* @param {String} password - Password of the user
* @param {function} setPassword - Set the password of the user (string)
* @param {number} therapistId - Id of the therapist
* @param {function} setTherapistId - Set the id of the therapist (number)
* @param {function} setIsValidConnection - Set the validity of the connection (boolean, true for valid)
* @param {function} setShowErrorMsg - Set the code of the error message to be displayed (number)
* @param {function} setGoToJournal - Set the visibility of the journal (boolean, true to show)
* @returns {function} Set values
*/
function handleLogin(
username,
setUsername,
password,
setPassword,
therapistId,
setTherapistId,
setIsValidConnection,
setShowErrorMsg,
setGoToJournal,
) {
if (typeof username === 'undefined' || username === '') {
return setShowErrorMsg(1); // no input for username
} else if (typeof password === 'undefined' || password === '') {
return setShowErrorMsg(3); // no input for password
} else {
const id = getIdFromUsername(username);
if (id === -2) {
return setShowErrorMsg(2); // not valid username
} else {
const validConnect = isValidPassword(id, password);
if (!validConnect) {
return setShowErrorMsg(4);
} else {
return (
setTherapistId(id),
setUsername(''),
setPassword(''),
setIsValidConnection(true),
setShowErrorMsg(0),
setGoToJournal(true)
);
}
}
}
}
/**
* Set values to the given states to process log out.
* @param {function} setIsLoggedOut - Set to true to log out
* @param {function} setIsValidConnection - Set to true if the connection is valid
* @param {function} setGoToJournal - Set to true to display the journal
* @returns {Object} Logout
*/
function handleLogout(setIsLoggedOut, setIsValidConnection, setGoToJournal) {
return (
setIsLoggedOut(true), setIsValidConnection(false), setGoToJournal(false)
);
}
/**
* Check if the given id is valid
* @param {number} id - The id to be checked.
* @returns {boolean} True if the given id is valid
*/
function isValidId(id) {
return typeof id !== 'undefined' && id >= 0;
}
export {isValidId, handleLogin, handleLogout};