62 lines
1.7 KiB
TypeScript
62 lines
1.7 KiB
TypeScript
import { NotFoundException, UnauthorizedException } from 'next-api-decorators';
|
|
import { CreateUserRequest } from 'src/pages/api/users/request';
|
|
import { UserRepository } from 'src/backend/infrastructure/database/user/user.repository';
|
|
import { hashString } from 'src/utils/hash';
|
|
import { encode, validate } from 'src/utils/jwt';
|
|
import { UserEntity } from 'src/backend/infrastructure/database/user/user.entity';
|
|
import { LoginRequest } from '@/src/pages/api/auth/request';
|
|
|
|
export class UserService {
|
|
public static readonly service: UserService = new UserService();
|
|
static getService(): UserService {
|
|
return UserService.service;
|
|
}
|
|
|
|
async login(loginRequest: LoginRequest) {
|
|
const user = await UserRepository.getRepository().findOne({
|
|
where: { email: loginRequest.email },
|
|
});
|
|
if (!user) {
|
|
throw new NotFoundException('User not found');
|
|
}
|
|
if (user.password !== hashString(loginRequest.password)) {
|
|
throw new UnauthorizedException('Incorrect Credentials');
|
|
}
|
|
|
|
return {
|
|
token: encode({ id: user.id, email: user.email }),
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
},
|
|
};
|
|
}
|
|
|
|
async me(token: string) {
|
|
const userData = validate(token) as UserEntity;
|
|
const user = await UserRepository.getRepository().findOne({
|
|
where: { id: userData.id },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
username: true,
|
|
phone: true,
|
|
lastSignInAt: true,
|
|
},
|
|
});
|
|
|
|
return user;
|
|
}
|
|
|
|
async create(user: CreateUserRequest) {
|
|
const u = new UserEntity({
|
|
email: user.email,
|
|
username: user.username,
|
|
password: hashString(user.password),
|
|
phone: user.phoneNumber,
|
|
});
|
|
|
|
return UserRepository.getRepository().save(u);
|
|
}
|
|
}
|