38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
import { UserRepository } from "../repositories/UserRepository";
|
|
import { encrypt } from "../utils/encryptionUtils";
|
|
import { ValidationError, UnauthorizedError } from "../errors/httpErrors";
|
|
import { UserDto } from "../dtos/UserDto";
|
|
import { UserDtoEntityMapper } from "../mappers/UserDtoEntityMapper";
|
|
|
|
export class AuthController {
|
|
constructor(
|
|
private userRepository: UserRepository,
|
|
private mapper: UserDtoEntityMapper
|
|
) {}
|
|
|
|
async login(userName: string, password: string): Promise<{ token: string; user: UserDto }> {
|
|
if (!userName || !password) {
|
|
throw new ValidationError("Username and password are required");
|
|
}
|
|
|
|
// Find user by userName
|
|
const user = await this.userRepository.findByUserName(userName);
|
|
// Compare password
|
|
const passwordMatches = encrypt.comparepassword(user.password, password);
|
|
if (!passwordMatches || !user ) {
|
|
throw new UnauthorizedError("Invalid username or password");
|
|
}
|
|
|
|
// Create JWT
|
|
const token = encrypt.generateToken({
|
|
id: user.id,
|
|
userName: user.userName,
|
|
role: user.role,
|
|
});
|
|
|
|
return {
|
|
token,
|
|
user: this.mapper.toDto(user),
|
|
};
|
|
}
|
|
}
|