feat(services): refactor register and login functions in UserService

- Removed extraneous comments and updated function parameters to use interface types in `register` and `login` methods.
- Renamed `RegisterService` and `LoginService` to `register` and `login` respectively.
- This update enhances readability and maintains the consistency in code by leveraging TypeScript's type-checking feature.

Signed-off-by: Mathis <yidhra@tuta.io>
This commit is contained in:
Mathis H (Avnyr) 2024-04-25 16:57:21 +02:00
parent debb30b896
commit 789d62ea62
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

View File

@ -1,10 +1,10 @@
import {Logger} from "tslog"; import {Logger} from "tslog";
import Argon2id from "@node-rs/argon2";
import MySqlService from "@services/mysql.service"; import MySqlService from "@services/mysql.service";
import CredentialService from "@services/credential.service"; import CredentialService from "@services/credential.service";
import JwtService from "@services/jwt.service"; import JwtService from "@services/jwt.service";
import MysqlService from "@services/mysql.service"; import MysqlService from "@services/mysql.service";
import type {IReqRegister} from "@interfaces/requests/IReqRegister";
import {IReqLogin} from "@interfaces/requests/IReqLogin";
const logger = new Logger({ name: "UserService" }); const logger = new Logger({ name: "UserService" });
@ -29,41 +29,22 @@ async function getUserFromIdService(id: string | undefined) {
return dbUser; return dbUser;
} }
/** async function register(ReqData: IReqRegister) {
* Registers a new user by creating a UserService object, generating a JWT token, and inserting the user into the database. if (ReqData.password.length < 6) {
* logger.info(`REGISTER :> Invalid password (${ReqData.username})`)
* @param {Object} sanitizedData - The sanitized user data.
* @param {string} sanitizedData.username - The username of the new user.
* @param {string} sanitizedData.displayName - The display namcoe of the new user.
* @param {string} sanitizedData.firstName
* @param {string} sanitizedData.lastName
* @param {string} sanitizedData.password - The password of the new user.
* @param {boolean} sanitizedData.gdpr - Indicates whether the new user has accepted GDPR.
*
* @returns {Object} - An object containing the registered user's data and JWT token.
* @returns {string} error - The error name, if any. "none" if registration was successful.
* @returns {string|null} jwt - The JWT token for the registered user. Null if registration was not successful.
* @returns {Object|null} user - The registered user's data. Null if registration was not successful.
* @returns {string|null} user.id - The ID of the registered user. Null if registration was not successful.
* @returns {string|null} user.username - The username of the registered user. Null if registration was not successful.
* @returns {string|null} user.displayName - The display name of the registered user. Null if registration was not successful.
*/
async function RegisterService(sanitizedData) {
if (sanitizedData.password.length < 6) {
logger.info(`REGISTER :> Invalid password (${sanitizedData.username})`)
return { error: "invalidPassword" }; return { error: "invalidPassword" };
} }
const passwordHash = await CredentialService.hash(sanitizedData.password) const passwordHash = await CredentialService.hash(ReqData.password)
// Does the new user has accepted GDPR ? // Does the new user has accepted GDPR ?
if (sanitizedData.gdpr !== true) { if (ReqData.gdpr !== true) {
logger.info(`REGISTER :> GDPR not validated (${sanitizedData.username})`) logger.info(`REGISTER :> GDPR not validated (${ReqData.username})`)
return { error: "gdprNotApproved" } return { error: "gdprNotApproved" }
} }
// Check if exist and return // Check if exist and return
const dbUserIfExist = await getUserFromUsername(sanitizedData.username) const dbUserIfExist = await getUserFromUsername(ReqData.username)
if (dbUserIfExist) { if (dbUserIfExist) {
logger.info(`REGISTER :> User exist (${dbUserIfExist.username})\n ID:${dbUserIfExist.id}`) logger.info(`REGISTER :> User exist (${dbUserIfExist.username})\n ID:${dbUserIfExist.id}`)
return { error: "exist" } return { error: "exist" }
@ -73,9 +54,9 @@ async function RegisterService(sanitizedData) {
// New UserService (class) // New UserService (class)
const NewUser = new User(sanitizedData.username, sanitizedData.displayName, passwordHash, currentDate); const NewUser = new User(ReqData.username, ReqData.displayName, passwordHash, currentDate);
NewUser.setFirstName(sanitizedData.firstName); NewUser.setFirstName(ReqData.firstName);
NewUser.setLastName(sanitizedData.lastName); NewUser.setLastName(ReqData.lastName);
// JWT // JWT
@ -102,35 +83,22 @@ async function RegisterService(sanitizedData) {
return userData return userData
} }
/** async function login(ReqData: IReqLogin) {
* Performs the login process by verifying the provided credentials.
* @param {Object} sanitizedData - The sanitized user login data.
* @param {string} sanitizedData.username - The username provided by the user.
* @param {string} sanitizedData.password - The password provided by the user.
* @returns {Object} - The login result object.
* @returns {string} result.error - The error code if there is an error during the login process.
* @returns {string} result.jwt - The JSON Web Token (JWT) generated upon successful login.
* @returns {Object} result.user - The user information.
* @returns {number} result.user.id - The ID of the user.
* @returns {string} result.user.username - The username of the user.
* @returns {string} result.user.displayName - The display name of the user.
*/
async function LoginService(sanitizedData: { username: string; password: string; }) {
//const passwordHash = await getHashFromPassword(sanitizedData.password); //const passwordHash = await getHashFromPassword(sanitizedData.password);
const dbUser = await MysqlService.User.getByUsername(DbHandler, sanitizedData.username); const dbUser = await MysqlService.User.getByUsername(DbHandler, ReqData.username);
if (!dbUser) { if (!dbUser) {
console.log(`LoginService :> User does not exist (${sanitizedData.username})`); console.log(`LoginService :> User does not exist (${ReqData.username})`);
return { error: "userNotFound" }; return { error: "userNotFound" };
} }
if (sanitizedData.password.length < 6) { if (ReqData.password.length < 6) {
console.log('X') console.log('X')
console.log(`LoginService :> Invalid password (${sanitizedData.username})`); console.log(`LoginService :> Invalid password (${ReqData.username})`);
return { error: "invalidPassword" }; return { error: "invalidPassword" };
} }
const isPasswordValid = await CredentialService.compare(sanitizedData.password, dbUser.hash) const isPasswordValid = await CredentialService.compare(ReqData.password, dbUser.hash)
if (!isPasswordValid) { if (!isPasswordValid) {
console.log(isPasswordValid) console.log(isPasswordValid)
console.log(`LoginService :> Invalid password (${sanitizedData.username})`); console.log(`LoginService :> Invalid password (${ReqData.username})`);
return { error: "invalidPassword" }; return { error: "invalidPassword" };
} }
// biome-ignore lint/style/useConst: <explanation> // biome-ignore lint/style/useConst: <explanation>
@ -219,8 +187,8 @@ async function deleteUserService(targetId) {
} }
const UserService = { const UserService = {
register: RegisterService, register: register,
login: LoginService, login: login,
getAll: getAllUsersService, getAll: getAllUsersService,
getFromId: getUserFromIdService, getFromId: getUserFromIdService,
edit: editUserService, edit: editUserService,