EUS/services/UserService.ts

77 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-01-03 03:11:00 +00:00
import { Console } from "hsconsole";
import UserRepo from "../repos/UserRepo";
import PasswordUtility from "../utilities/PasswordUtility";
import UserType from "../enums/UserType";
import User from "../entities/User";
export default abstract class UserService {
public static async AuthenticateUser(username:string, password:string) {
try {
const user = await UserRepo.SelectByUsername(username);
if (!user) {
return null;
}
if (await PasswordUtility.ValidatePassword(user.PasswordHash, user.PasswordSalt, password)) {
return user;
}
return null;
} catch (e) {
Console.printError(`EUS server service error:\n${e}`);
throw e;
}
}
public static async GetUser(id:number) {
try {
return await UserRepo.SelectById(id);
} catch (e) {
Console.printError(`EUS server service error:\n${e}`);
throw e;
}
}
public static async GetAll() {
try {
return await UserRepo.SelectAll();
} catch (e) {
Console.printError(`EUS server service error:\n${e}`);
throw e;
}
}
public static async GetUserByUsername(username:string) {
try {
return await UserRepo.SelectByUsername(username);
} catch (e) {
Console.printError(`EUS server service error:\n${e}`);
throw e;
}
}
2025-01-05 14:22:18 +00:00
public static async CreateUser(currentUserId: number, username: string, email: string, password: string) {
2025-01-03 03:11:00 +00:00
try {
const existingCheck = await UserRepo.SelectByUsername(username);
if (existingCheck) {
return null;
}
const user = new User();
user.UserType = UserType.User;
user.Username = username;
2025-01-05 14:22:18 +00:00
user.EmailAddress = email;
2025-01-03 03:11:00 +00:00
user.PasswordSalt = PasswordUtility.GenerateSalt();
user.PasswordHash = await PasswordUtility.HashPassword(user.PasswordSalt, password);
user.CreatedByUserId = currentUserId;
user.CreatedDatetime = new Date();
await UserRepo.InsertUpdate(user);
return user;
} catch (e) {
Console.printError(`EUS server service error:\n${e}`);
throw e;
}
}
}