feat: add user createOne and refactor code

This commit is contained in:
2026-02-23 09:19:34 +03:30
parent 72a001a150
commit 63b4567166
13 changed files with 192 additions and 110 deletions
+5 -76
View File
@@ -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);
}
}