Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 102 additions & 10 deletions apps/api/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,126 @@
import { Body, Controller, HttpCode, HttpStatus, Post, Res } from '@nestjs/common'
import type { Response } from 'express'
import { Body, Controller, HttpCode, HttpStatus, Post, Req, Res } from '@nestjs/common'
import type { Request, Response } from 'express'

import { AuthService } from './auth.service'
import { RegisterRequestDto } from './dto/register.dto'
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger'
import {
ApiTags,
ApiOperation,
ApiOkResponse,
ApiConflictResponse,
ApiBadRequestResponse,
ApiNotFoundResponse,
ApiUnauthorizedResponse,
} from '@nestjs/swagger'
import { LoginRequestDto } from './dto/login.dto'
import { AuthResponse } from './dto/auth.dto'

@ApiTags('auth')
@ApiTags('Auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}

@ApiOperation({
summary: 'Регистрация аккаунта',
description: 'Регистрирует нового пользователя и возвращает токены',
})
@ApiOkResponse({
type: AuthResponse,
description: 'Пользователь успешно зарегистрирован',
})
@ApiConflictResponse({
description: 'Пользователь с таким email уже существует',
schema: {
example: {
statusCode: 409,
error: 'Conflict',
message: 'Пользователь с таким email уже существует',
},
},
})
@ApiBadRequestResponse({
description: 'Некорректные данные',
schema: {
example: {
statusCode: 400,
path: ['email', 'password'],
message: ['Email некорректный', 'Пароль должен быть строкой'],
},
},
})
@Post('register')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'Регистрация нового пользователя' })
@ApiResponse({ status: 201, description: 'Пользователь успешно зарегистрирован' })
@ApiResponse({ status: 400, description: 'Некорректные данные' })
async register(
@Res({ passthrough: true }) res: Response,
@Body() dto: RegisterRequestDto,
) {
return this.authService.register(res, dto)
}

@ApiOperation({
summary: 'Вход пользователя',
description: 'Выполняет аутентификацию пользователя и возвращает токены',
})
@ApiOkResponse({ type: AuthResponse, description: 'Пользователь успешно вошел' })
@ApiConflictResponse({
description: 'Пользователь с таким email уже существует',
schema: {
example: {
statusCode: 409,
error: 'Conflict',
message: 'Пользователь с таким email уже существует',
},
},
})
@ApiNotFoundResponse({
description: 'Пользователь не найден',
schema: {
example: {
statusCode: 404,
error: 'Not Found',
message: 'Пользователь не найден',
},
},
})
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Вход пользователя' })
@ApiResponse({ status: 200, description: 'Пользователь успешно вошел' })
@ApiResponse({ status: 400, description: 'Некорректные данные' })
async login(@Res({ passthrough: true }) res: Response, @Body() dto: LoginRequestDto) {
return this.authService.login(res, dto)
}

@ApiOperation({
summary: 'Обновление токена',
description: 'Обновляет access токен с помощью refresh токена',
})
@ApiOkResponse({ type: AuthResponse, description: 'Токен успешно обновлен' })
@ApiUnauthorizedResponse({
description: 'Недействительный refresh-токен',
schema: {
example: {
statusCode: 401,
error: 'Unauthorized',
message: 'Недействительный refresh-токен',
},
},
})
@ApiBadRequestResponse({
description: 'Некорректные данные',
schema: { example: { statusCode: 400, message: 'Некорректные данные' } },
})
@Post('refresh')
@HttpCode(HttpStatus.OK)
async refresh(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
return this.authService.refresh(req, res)
}

@ApiOperation({
summary: 'Выход пользователя',
description: 'Выполняет выход пользователя и удаляет токены',
})
@ApiOkResponse({ description: 'Пользователь успешно вышел' })
@Post('logout')
@HttpCode(HttpStatus.OK)
async logout(@Res({ passthrough: true }) res: Response) {
return this.authService.logout(res)
}
}
43 changes: 41 additions & 2 deletions apps/api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { hash, verify } from 'argon2'
import { ConfigService } from '@nestjs/config'
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common'
import {
ConflictException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import type { Response } from 'express'
import type { Request, Response } from 'express'

import { RegisterRequestDto } from './dto/register.dto'
import { PrismaService } from '../../prisma/prisma.service'
Expand Down Expand Up @@ -53,7 +58,7 @@
},
})

return this.auth(res, user.id)

Check warning on line 61 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`
}

async login(res: Response, dto: LoginRequestDto) {
Expand All @@ -73,15 +78,48 @@
throw new NotFoundException('Пользователь не найден')
}

const isPasswordValid = await verify(user.password, password)

Check warning on line 81 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`

if (!isPasswordValid) {
throw new NotFoundException('Пользователь не найден')
}

return this.auth(res, user.id)

Check warning on line 87 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`
}

async refresh(req: Request, res: Response) {
const refreshToken: string = req.cookies['refreshToken']

if (!refreshToken) {
throw new UnauthorizedException('Недействительный refresh-токен')
}

const payload: JwtPayload = await this.jwtService.verifyAsync(refreshToken)

if (payload) {
const user = await this.prismaService.user.findUnique({
where: {
id: payload.id,
},
select: {
id: true,
},
})

if (!user) {
throw new NotFoundException('Пользователь не найден')
}

return this.auth(res, user.id)

Check warning on line 113 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`
}
}

async logout(res: Response) {
this.setCookie(res, 'refreshToken', new Date(0))

return { message: 'Пользователь успешно вышел', success: true }
}

private auth(res: Response, userId: string) {
const { accessToken, refreshToken } = this.generateTokens(userId)

Expand All @@ -107,6 +145,7 @@

return { accessToken, refreshToken }
}

private setCookie(res: Response, value: string, expires: Date) {
res.cookie('refreshToken', value, {
httpOnly: true,
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/auth/config/jwt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@ export async function getJwtConfig(
signOptions: {
algorithm: 'HS256',
},
verifyOptions: {
algorithms: ['HS256'],
ignoreExpiration: false,
},
}
}
10 changes: 10 additions & 0 deletions apps/api/src/auth/config/swagger.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { DocumentBuilder } from '@nestjs/swagger'

export function getSwaggerConfig() {
return new DocumentBuilder()
.setTitle('Tracker Task API')
.setDescription('API для управления проектами и задачами')
.setVersion('1.0.0')
.addBearerAuth()
.build()
}
9 changes: 9 additions & 0 deletions apps/api/src/auth/dto/auth.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger'

export class AuthResponse {
@ApiProperty({
description: 'JWT access токен',
example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9....',
})
accessToken: string
}
9 changes: 8 additions & 1 deletion apps/api/src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { createZodDto } from 'nestjs-zod'
import { loginRequestSchema } from '@repo/types'
import { ApiProperty } from '@nestjs/swagger'

export class LoginRequestDto extends createZodDto(loginRequestSchema) {}
export class LoginRequestDto extends createZodDto(loginRequestSchema) {
@ApiProperty({ example: 'user@example.com', description: 'Email пользователя' })
email: string

@ApiProperty({ example: '123456', description: 'Пароль' })
password: string
}
12 changes: 11 additions & 1 deletion apps/api/src/auth/dto/register.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { createZodDto } from 'nestjs-zod'
import { registerRequestSchema } from '@repo/types'
import { ApiProperty } from '@nestjs/swagger'

// Создаём DTO класс для NestJS и Swagger из схемы
export class RegisterRequestDto extends createZodDto(registerRequestSchema) {}
export class RegisterRequestDto extends createZodDto(registerRequestSchema) {
@ApiProperty({ example: 'Иван Иванов', description: 'Имя пользователя' })
name: string

@ApiProperty({ example: 'user@example.com', description: 'Email пользователя' })
email: string

@ApiProperty({ example: '123456', description: 'Пароль' })
password: string
}
15 changes: 3 additions & 12 deletions apps/api/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,17 @@
import { NestFactory } from '@nestjs/core'

import { AppModule } from './app.module'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { cleanupOpenApiDoc } from 'nestjs-zod'

import cookieParser from 'cookie-parser'
import { setupSwagger } from './utils/swagger.util'

async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.enableCors()

app.use(cookieParser())

const config = new DocumentBuilder()
.setTitle('Tracker Task API')
.setDescription('API для управления проектами и задачами')
.setVersion('1.0.0')
.addBearerAuth()
.build()

const document = SwaggerModule.createDocument(app, config)

SwaggerModule.setup('api/docs', app, cleanupOpenApiDoc(document))
setupSwagger(app)

await app.listen(4000)
}
Expand Down
15 changes: 15 additions & 0 deletions apps/api/src/utils/swagger.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { INestApplication } from '@nestjs/common'
import { SwaggerModule } from '@nestjs/swagger'
import { cleanupOpenApiDoc } from 'nestjs-zod'
import { getSwaggerConfig } from 'src/auth/config/swagger.config'

export function setupSwagger(app: INestApplication) {
const config = getSwaggerConfig()

const document = SwaggerModule.createDocument(app, config)

SwaggerModule.setup('api/docs', app, cleanupOpenApiDoc(document), {
jsonDocumentUrl: '/swagger.json',
yamlDocumentUrl: '/swagger.yaml',
})
}
Loading