feat: add jwt auth guard and profile endpoint

This commit is contained in:
2026-02-28 08:14:04 +03:30
parent 8212ede785
commit 06f659101d
21 changed files with 371 additions and 31 deletions
+3
View File
@@ -2,6 +2,7 @@ import { Body, Controller, HttpCode, Post } from '@nestjs/common';
import { LoginDTO } from './dtos/login.dto';
import { AuthService } from './providers/auth.service';
import { VerifyOtpDTO } from './dtos/verify-otp.dto';
import { Public } from './decorators/public.decorator';
@Controller('users')
export class AuthController {
@@ -12,12 +13,14 @@ export class AuthController {
private readonly authService: AuthService,
) {}
@Public()
@Post('login')
@HttpCode(200)
public async logIn(@Body() loginDto: LoginDTO) {
return await this.authService.logIn(loginDto);
}
@Public()
@Post('verify-otp')
@HttpCode(200)
public async verifyOTP(@Body() verifyOtpDto: VerifyOtpDTO) {
+8
View File
@@ -9,6 +9,9 @@ import { ConfigService } from '@nestjs/config';
import { LoginProvider } from './providers/login.provider';
import { GenerateTokenProvider } from './providers/generate-token.provider';
import { VerifyOTPProvider } from './providers/verify-otp.provider';
import { JwtStrategy } from './strategies/jwt.strategy';
import { APP_GUARD } from '@nestjs/core';
import { GlobalAuthGuard } from './guards/global-auth.guard';
@Module({
imports: [
@@ -33,6 +36,11 @@ import { VerifyOTPProvider } from './providers/verify-otp.provider';
GenerateTokenProvider,
LoginProvider,
VerifyOTPProvider,
JwtStrategy,
{
provide: APP_GUARD,
useClass: GlobalAuthGuard,
},
],
})
export class AuthModule {}
+1
View File
@@ -0,0 +1 @@
export const IS_PUBLIC_KEY = 'isPublic';
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';
import { IS_PUBLIC_KEY } from '../constants';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
@@ -0,0 +1,32 @@
import { IS_PUBLIC_KEY } from '../constants';
import { JwtAuthGuard } from './jwt-auth.guard';
import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
@Injectable()
export class GlobalAuthGuard extends JwtAuthGuard {
constructor(
/**
* Inject Reflector
*/
private readonly reflector: Reflector,
) {
super();
}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
return super.canActivate(context);
}
}
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
@@ -2,6 +2,5 @@ POST http://localhost:3000/users/login
Content-Type: application/json
{
"phone": "09126093033",
"password": "rad1.3.5"
"phone": "09121111111"
}
@@ -2,6 +2,6 @@ POST http://localhost:3000/users/verify-otp
Content-Type: application/json
{
"phone": "09126093033",
"otp": "57903"
"phone": "09121111111",
"otp": "83793"
}
@@ -0,0 +1,42 @@
import jwtConfig from '@/config/jwt.config';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AccessTokenPayload } from '../interfaces/jwt.interface';
import { User } from '@/modules/users/user.entity';
import { UsersService } from '@/modules/users/providers/users.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
/**
* Inject Jwt Config
*/
@Inject(jwtConfig.KEY)
private readonly jwtConfiguration: ConfigType<typeof jwtConfig>,
/**
* Inject Users Service
*/
private readonly usersService: UsersService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConfiguration.access.secret || '*********',
issuer: jwtConfiguration.issuer,
audience: jwtConfiguration.audience,
});
}
async validate(payload: AccessTokenPayload): Promise<User> {
const user = await this.usersService.findOneByPhone(payload.phone);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
@@ -0,0 +1,94 @@
import { MatchField } from '@/common/decorators/match-field.decorator';
import { ApiProperty } from '@nestjs/swagger';
import {
IsOptional,
IsString,
Matches,
MaxLength,
MinLength,
ValidateIf,
} from 'class-validator';
import { i18nValidationMessage as t } from 'nestjs-i18n';
export class UpdateProfileDTO {
@ApiProperty({
type: 'string',
description: `User's Firstname`,
example: 'Radmehr',
required: false,
})
@IsString()
@IsOptional()
@MinLength(3, {
message: t('validation.minLengthField', {
field: '$t(users.fields.firstName)',
min: 3,
}),
})
@MaxLength(96, {
message: t('validation.maxLengthField', {
field: '$t(users.fields.firstName)',
max: 96,
}),
})
firstName?: string;
@ApiProperty({
type: 'string',
description: `User's Lastname`,
example: 'Tarnas',
required: false,
})
@IsString()
@IsOptional()
@MinLength(3, {
message: t('validation.minLengthField', {
field: '$t(users.fields.lastName)',
min: 3,
}),
})
@MaxLength(96, {
message: t('validation.maxLengthField', {
field: '$t(users.fields.lastName)',
min: 3,
}),
})
lastName?: string;
@ApiProperty({
type: 'string',
description: 'Password for User Account',
example: 'Password1@',
required: false,
})
@IsString()
@IsOptional()
@MinLength(8, {
message: t('validation.minLengthField', {
field: '$t(users.fields.password)',
min: 8,
}),
})
@MaxLength(96, {
message: t('validation.maxLengthField', {
field: '$t(users.fields.password)',
max: 96,
}),
})
@Matches(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).{8,}$/, {
message: t('users.errors.passwordPattern'),
})
password?: string;
@ApiProperty({
type: 'string',
description: 'Confirm Password of User Account (Should match Password)',
example: 'Password1@',
required: false,
})
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
@ValidateIf((o) => o.password !== undefined)
@IsOptional()
@MatchField('password')
confirmPassword?: string;
}
@@ -1,3 +1,2 @@
GET http://localhost:3000/users
GET http://localhost:3000/users/2
GET http://localhost:3000/users/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjQsInBob25lIjoiMDkxMjYxMTcwMTgiLCJpYXQiOjE3NzIxMjc1MTgsImV4cCI6MTc3MjEzMTExOCwiYXVkIjoibG9jYWxob3N0IiwiaXNzIjoibG9jYWxob3N0In0.oaxzSd0DDakCDMiW129Ou3MJh0oT0zJTFerZEjnQ7Ug
@@ -0,0 +1,10 @@
PATCH http://localhost:3000/users/profile
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjUsInBob25lIjoiMDkxMjExMTExMTEiLCJpYXQiOjE3NzIxNzQwMzUsImV4cCI6MTc3MjE3NzYzNSwiYXVkIjoibG9jYWxob3N0IiwiaXNzIjoibG9jYWxob3N0In0.bux4kC-J9AV8HJpo41t8-iRGDJwVOVb0yMK9cAs4ELA
{
"firstName": "Radmehr",
"lastName": "Tarnas",
"password": "Password1@",
"confirmPassword": "ldsfjlsdf"
}
@@ -1,10 +0,0 @@
POST http://localhost:3000/users
Content-Type: application/json
lang: fa
{
"firstName": "Ra",
"lastName": "Tnas",
"phone": "9333026363",
"password": "ra"
}
@@ -38,4 +38,13 @@ export class UsersService {
return newUser;
}
public getProfile(user: User) {
return {
phone: user.phone,
firstName: user.firstName,
lastName: user.lastName,
dateJoined: user.createdAt,
};
}
}
+15 -14
View File
@@ -1,5 +1,8 @@
import { Controller } from '@nestjs/common';
import { Body, Controller, Get, Patch } from '@nestjs/common';
import { UsersService } from './providers/users.service';
import { ActiveUser } from '@/common/decorators/active-user.decorator';
import { User } from './user.entity';
import { UpdateProfileDTO } from './dto/update-profile.dto';
@Controller('users')
export class UsersController {
@@ -10,18 +13,16 @@ export class UsersController {
private readonly usersService: UsersService,
) {}
// @Get()
// public getAllUsers() {
// return ['user1', 'user2'];
// }
@Get('profile')
public getUserProfile(@ActiveUser() user: User) {
return this.usersService.getProfile(user);
}
// @Get(':id')
// public getUserById(@Param('id', ParseIntPipe) id: number) {
// return `user ${id}`;
// }
// @Post()
// public async createUser(@Body() createUserDto: CreateUserDTO) {
// return await this.usersService.createOne(createUserDto);
// }
@Patch('profile')
public updateUserProfile(
@ActiveUser() user: User,
@Body() updateProfileDto: UpdateProfileDTO,
) {
return updateProfileDto;
}
}