feat: add user createOne and refactor code
This commit is contained in:
@@ -1,88 +1,17 @@
|
||||
import { UsersService } from '@/modules/users/providers/users.service';
|
||||
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { LoginDTO } from '../dtos/login.dto';
|
||||
import { OtpService } from '@/modules/otp/providers/otp.service';
|
||||
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import jwtConfig from '@/config/jwt.config';
|
||||
import { LoginProvider } from './login.provider';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
/**
|
||||
* Inject Users Service
|
||||
* Inject Login Provider
|
||||
*/
|
||||
private readonly usersService: UsersService,
|
||||
|
||||
/**
|
||||
* Inject OTP Service
|
||||
*/
|
||||
private readonly otpService: OtpService,
|
||||
|
||||
/**
|
||||
* Inject Hashing Provider
|
||||
*/
|
||||
private readonly hashingProvider: HashingProvider,
|
||||
|
||||
/**
|
||||
* Inject Jwt Service
|
||||
*/
|
||||
private readonly jwtService: JwtService,
|
||||
|
||||
/**
|
||||
* Inject Jwt Config
|
||||
*/
|
||||
@Inject(jwtConfig.KEY)
|
||||
private readonly jwtConfiguration: ConfigType<typeof jwtConfig>,
|
||||
private readonly loginProvider: LoginProvider,
|
||||
) {}
|
||||
|
||||
public async logIn(loginDto: LoginDTO) {
|
||||
const { phone, password } = loginDto;
|
||||
const user = await this.usersService.findOneByPhone(phone);
|
||||
|
||||
if (!user) {
|
||||
// TODO: Send OTP
|
||||
const otpCode = await this.otpService.createOTP(phone);
|
||||
|
||||
return {
|
||||
newUser: true,
|
||||
message: `Otp sent to ${phone}`,
|
||||
// Just for development
|
||||
code: otpCode,
|
||||
};
|
||||
}
|
||||
|
||||
if (!password) {
|
||||
return {
|
||||
newUser: false,
|
||||
message: 'Please send password',
|
||||
};
|
||||
}
|
||||
|
||||
const isPasswordCorrect = await this.hashingProvider.compare(
|
||||
password,
|
||||
user.password || '',
|
||||
);
|
||||
|
||||
if (isPasswordCorrect) {
|
||||
const tokenPayload = {
|
||||
sub: user.id,
|
||||
phone: user.phone,
|
||||
};
|
||||
|
||||
const accessToken = await this.jwtService.signAsync(tokenPayload);
|
||||
|
||||
const refreshToken = await this.jwtService.signAsync(tokenPayload, {
|
||||
secret: this.jwtConfiguration.refresh.secret,
|
||||
expiresIn: this.jwtConfiguration.refresh.expiresIn,
|
||||
});
|
||||
|
||||
return { access: accessToken, refresh: refreshToken };
|
||||
}
|
||||
|
||||
throw new UnauthorizedException(
|
||||
'Entered phone number or password is wrong.',
|
||||
);
|
||||
return await this.loginProvider.logIn(loginDto);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user