|
|
|
@ -5,6 +5,7 @@ import * as bcrypt from "bcrypt"; |
|
|
|
|
import { JwtService } from "@nestjs/jwt"; |
|
|
|
|
import { ConfigService } from "@nestjs/config"; |
|
|
|
|
import { CreateAdminDto } from "./dto/create-Admin.dto"; |
|
|
|
|
import { LoginAdminDto } from "./dto/login-Admin.dto"; |
|
|
|
|
@Injectable() |
|
|
|
|
export class AdminService { |
|
|
|
|
constructor( |
|
|
|
@ -12,6 +13,7 @@ export class AdminService { |
|
|
|
|
private readonly jwtService: JwtService, |
|
|
|
|
private readonly configService: ConfigService, |
|
|
|
|
) {} |
|
|
|
|
//register method
|
|
|
|
|
async register(createAdminDto:CreateAdminDto): Promise<Admin> { |
|
|
|
|
try { |
|
|
|
|
const existingAdmin = await this.adminModel.findOne({ where: { email:createAdminDto.email } }); |
|
|
|
@ -32,17 +34,20 @@ export class AdminService { |
|
|
|
|
throw new HttpException("An error occurred during registration.", HttpStatus.INTERNAL_SERVER_ERROR); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
async login(email: string, password: string): Promise<{ token: string }> { |
|
|
|
|
//login method
|
|
|
|
|
async login(loginAdminDto: LoginAdminDto): Promise<{ token: string }> { |
|
|
|
|
try { |
|
|
|
|
const admin = await this.adminModel.findOne({ where: { email } }); |
|
|
|
|
const admin = await this.adminModel.findOne({ where: { email: loginAdminDto.email } }); |
|
|
|
|
|
|
|
|
|
if (!admin) { |
|
|
|
|
throw new HttpException("Invalid email or password", HttpStatus.UNAUTHORIZED); |
|
|
|
|
} |
|
|
|
|
const isValidPassword = await bcrypt.compare(password, admin.password); |
|
|
|
|
|
|
|
|
|
const isValidPassword = await bcrypt.compare(loginAdminDto.password, admin.password); |
|
|
|
|
if (!isValidPassword) { |
|
|
|
|
throw new HttpException("Invalid email or password", HttpStatus.UNAUTHORIZED); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
const token = this.jwtService.sign( |
|
|
|
|
{ id: admin.id, role: admin.role }, |
|
|
|
|
{ |
|
|
|
@ -50,10 +55,12 @@ export class AdminService { |
|
|
|
|
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h", |
|
|
|
|
}, |
|
|
|
|
); |
|
|
|
|
|
|
|
|
|
return { token }; |
|
|
|
|
} catch (error) { |
|
|
|
|
console.log(error); |
|
|
|
|
throw new HttpException("An error occurred during login.", HttpStatus.INTERNAL_SERVER_ERROR); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
} |
|
|
|
|