feat: add simple login logic
This commit is contained in:
+9
-5
@@ -6,17 +6,14 @@ import environmentValidation from './config/environment.validation';
|
|||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import databaseConfig from './config/database.config';
|
import databaseConfig from './config/database.config';
|
||||||
import { HeaderResolver, I18nJsonLoader, I18nModule } from 'nestjs-i18n';
|
import { HeaderResolver, I18nJsonLoader, I18nModule } from 'nestjs-i18n';
|
||||||
|
import { AuthModule } from './modules/auth/auth.module';
|
||||||
|
import { OtpModule } from './modules/otp/otp.module';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
const ENV = process.env.NODE_ENV;
|
const ENV = process.env.NODE_ENV;
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
/**
|
|
||||||
* Local Modules
|
|
||||||
*/
|
|
||||||
UsersModule,
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Third-party Modules
|
* Third-party Modules
|
||||||
*/
|
*/
|
||||||
@@ -55,6 +52,13 @@ const ENV = process.env.NODE_ENV;
|
|||||||
synchronize: configService.get<boolean>('database.synchronize'),
|
synchronize: configService.get<boolean>('database.synchronize'),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Local Modules
|
||||||
|
*/
|
||||||
|
UsersModule,
|
||||||
|
AuthModule,
|
||||||
|
OtpModule,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"fields": {
|
||||||
|
"phone": "Phone",
|
||||||
|
"password": "Password"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"fields": {
|
||||||
|
"phone": "شماره موبایل",
|
||||||
|
"password": "رمز عبور"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,5 +2,6 @@
|
|||||||
"requiredField": "{field} اجباری است.",
|
"requiredField": "{field} اجباری است.",
|
||||||
"minLengthField": "{field} باید حداقل شامل {min} کاراکتر باشد.",
|
"minLengthField": "{field} باید حداقل شامل {min} کاراکتر باشد.",
|
||||||
"maxLengthField": "{field} باید حداکثر شامل {max} کاراکتر باشد.",
|
"maxLengthField": "{field} باید حداکثر شامل {max} کاراکتر باشد.",
|
||||||
"wrongField": "{field} معتبر نیست."
|
"wrongField": "{field} معتبر نیست.",
|
||||||
|
"wrongFieldFormat": "فرمت {field} معتبر نیست."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { Body, Controller, HttpCode, Post } from '@nestjs/common';
|
||||||
|
import { LoginDTO } from './dtos/login.dto';
|
||||||
|
import { AuthService } from './providers/auth.service';
|
||||||
|
|
||||||
|
@Controller('users')
|
||||||
|
export class AuthController {
|
||||||
|
constructor(
|
||||||
|
/**
|
||||||
|
* Inject Auth Service
|
||||||
|
*/
|
||||||
|
private readonly authService: AuthService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Post('login')
|
||||||
|
@HttpCode(200)
|
||||||
|
public async logIn(@Body() loginDto: LoginDTO) {
|
||||||
|
return await this.authService.logIn(loginDto);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AuthController } from './auth.controller';
|
||||||
|
import { AuthService } from './providers/auth.service';
|
||||||
|
import { UsersModule } from '../users/users.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [UsersModule],
|
||||||
|
controllers: [AuthController],
|
||||||
|
providers: [AuthService],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import Utils from '@/common/utils';
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Transform } from 'class-transformer';
|
||||||
|
import { IsNotEmpty, IsOptional, IsString, Matches } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as t } from 'nestjs-i18n';
|
||||||
|
|
||||||
|
export class LoginDTO {
|
||||||
|
@ApiProperty({
|
||||||
|
type: 'string',
|
||||||
|
description: `User's Phone Number`,
|
||||||
|
example: '09121111111',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({
|
||||||
|
message: t('validation.requiredField', {
|
||||||
|
field: '$t(auth.fields.phone)',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
@Matches(/^(?:09|9)[0-9]{9}$/, {
|
||||||
|
message: t('validation.wrongField', {
|
||||||
|
field: '$t(auth.fields.phone)',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
@Transform(({ value }) => Utils.StringUtils.normalizePhone(value as string))
|
||||||
|
phone: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: 'string',
|
||||||
|
description: 'Password for User Account',
|
||||||
|
example: 'Password1@',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({
|
||||||
|
message: t('validation.wrongFieldFormat', {
|
||||||
|
field: '$t(auth.fields.password)',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
password?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
POST http://localhost:3000/users/login
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"phone": "09333026363",
|
||||||
|
"password": "rad1.3.5"
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { UsersService } from '@/modules/users/providers/users.service';
|
||||||
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { LoginDTO } from '../dtos/login.dto';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
constructor(
|
||||||
|
/**
|
||||||
|
* Inject Users Service
|
||||||
|
*/
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async logIn(loginDto: LoginDTO) {
|
||||||
|
const { phone, password } = loginDto;
|
||||||
|
const user = await this.usersService.findOneByPhone(phone);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
// TODO: Send OTP
|
||||||
|
|
||||||
|
return {
|
||||||
|
newUser: true,
|
||||||
|
message: `Otp sent to ${phone}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!password) {
|
||||||
|
return {
|
||||||
|
newUser: false,
|
||||||
|
message: 'Please send password',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Hash password and compare
|
||||||
|
if (password === user.password) {
|
||||||
|
// TODO: Create JWT
|
||||||
|
|
||||||
|
return { access: 'ACCESS_TOKEN', refresh: 'REFRESH_TOKEN' };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new UnauthorizedException(
|
||||||
|
'Entered phone number or password is wrong.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import {
|
||||||
|
BeforeInsert,
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity()
|
||||||
|
@Index(['phone', 'used'])
|
||||||
|
export class OTP {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Index()
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
length: 11,
|
||||||
|
nullable: false,
|
||||||
|
})
|
||||||
|
phone: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
length: 5,
|
||||||
|
nullable: false,
|
||||||
|
})
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@Index()
|
||||||
|
@Column({ type: 'timestamptz' })
|
||||||
|
expiredAt: Date;
|
||||||
|
|
||||||
|
@Column({ type: 'boolean', default: false })
|
||||||
|
used: boolean;
|
||||||
|
|
||||||
|
@BeforeInsert()
|
||||||
|
setExpiry() {
|
||||||
|
this.expiredAt = new Date(Date.now() + 2 * 60 * 1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { OtpService } from './providers/otp.service';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { OTP } from './otp.entity';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([OTP])],
|
||||||
|
providers: [OtpService],
|
||||||
|
})
|
||||||
|
export class OtpModule {}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { OTP } from '../otp.entity';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class OtpService {
|
||||||
|
constructor(
|
||||||
|
/**
|
||||||
|
* Inject OTP Repository
|
||||||
|
*/
|
||||||
|
@InjectRepository(OTP)
|
||||||
|
private readonly otpRepository: Repository<OTP>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate OTP 5-digit code
|
||||||
|
*/
|
||||||
|
private generateOTPCode(): string {
|
||||||
|
return Math.floor(10_000 + Math.random() * 90_000).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create new OTP record
|
||||||
|
*/
|
||||||
|
public async createOTP(phone: string): Promise<string> {
|
||||||
|
// OTP request Rate limit
|
||||||
|
const lastOTP = await this.otpRepository.findOne({
|
||||||
|
where: { phone },
|
||||||
|
order: { createdAt: 'DESC' },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (lastOTP && Date.now() - lastOTP.createdAt.getTime() < 60_000) {
|
||||||
|
// throw new TooMany();
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -104,7 +104,7 @@ export class CreateUserDTO {
|
|||||||
@MaxLength(96, {
|
@MaxLength(96, {
|
||||||
message: t('validation.maxLengthField', {
|
message: t('validation.maxLengthField', {
|
||||||
field: '$t(users.fields.password)',
|
field: '$t(users.fields.password)',
|
||||||
min: 96,
|
max: 96,
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
@Matches(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).{8,}$/, {
|
@Matches(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).{8,}$/, {
|
||||||
|
|||||||
@@ -14,6 +14,17 @@ export class UsersService {
|
|||||||
private readonly userRepository: Repository<User>,
|
private readonly userRepository: Repository<User>,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
public async findOneByPhone(phone: string) {
|
||||||
|
try {
|
||||||
|
return await this.userRepository.findOneBy({ phone });
|
||||||
|
} catch (err) {
|
||||||
|
throw new RequestTimeoutException(
|
||||||
|
'Unable to process your request at the moment. Please try again later.',
|
||||||
|
{ cause: err, description: 'Error connecting to the database' },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async createOne(createUserDto: CreateUserDTO) {
|
public async createOne(createUserDto: CreateUserDTO) {
|
||||||
const newUser = this.userRepository.create(createUserDto);
|
const newUser = this.userRepository.create(createUserDto);
|
||||||
|
|
||||||
|
|||||||
@@ -14,16 +14,16 @@ export class User {
|
|||||||
@Column({
|
@Column({
|
||||||
type: 'varchar',
|
type: 'varchar',
|
||||||
length: 96,
|
length: 96,
|
||||||
nullable: false,
|
nullable: true,
|
||||||
})
|
})
|
||||||
firstName: string;
|
firstName?: string;
|
||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
type: 'varchar',
|
type: 'varchar',
|
||||||
length: 96,
|
length: 96,
|
||||||
nullable: false,
|
nullable: true,
|
||||||
})
|
})
|
||||||
lastName: string;
|
lastName?: string;
|
||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
type: 'varchar',
|
type: 'varchar',
|
||||||
@@ -36,9 +36,9 @@ export class User {
|
|||||||
@Column({
|
@Column({
|
||||||
type: 'varchar',
|
type: 'varchar',
|
||||||
length: 96,
|
length: 96,
|
||||||
nullable: false,
|
nullable: true,
|
||||||
})
|
})
|
||||||
password: string;
|
password?: string;
|
||||||
|
|
||||||
@CreateDateColumn()
|
@CreateDateColumn()
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
|
|||||||
@@ -8,5 +8,6 @@ import { User } from './user.entity';
|
|||||||
imports: [TypeOrmModule.forFeature([User])],
|
imports: [TypeOrmModule.forFeature([User])],
|
||||||
controllers: [UsersController],
|
controllers: [UsersController],
|
||||||
providers: [UsersService],
|
providers: [UsersService],
|
||||||
|
exports: [UsersService],
|
||||||
})
|
})
|
||||||
export class UsersModule {}
|
export class UsersModule {}
|
||||||
|
|||||||
Reference in New Issue
Block a user