76 lines
1.9 KiB
TypeScript
76 lines
1.9 KiB
TypeScript
|
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;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static async CreateUser(currentUserId:number, username:string, password:string) {
|
||
|
try {
|
||
|
const existingCheck = await UserRepo.SelectByUsername(username);
|
||
|
if (existingCheck) {
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
const user = new User();
|
||
|
user.UserType = UserType.User;
|
||
|
user.Username = username;
|
||
|
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;
|
||
|
}
|
||
|
}
|
||
|
}
|