add auth and user handling
This commit is contained in:
parent
db057ce342
commit
1fce467571
19 changed files with 356 additions and 32 deletions
38
src/controllers/AuthController.ts
Normal file
38
src/controllers/AuthController.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
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),
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue