trust-module-backend/src/auth/auth.controller.ts

82 lines
2.8 KiB
TypeScript

import { Controller, Post, Get, Body, Res, Req, UnauthorizedException, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { Response, Request } from 'express';
import { JwtAuthGuard } from './jwt-auth.guard';
import { Logger } from '@nestjs/common/services';
@Controller('auth')
export class AuthController {
private readonly logger = new Logger(AuthController.name);
constructor(private authService: AuthService) { }
@Get('check')
@UseGuards(JwtAuthGuard)
async checkAuth(@Req() req: Request) {
this.logger.debug(`Check auth request. Cookies: ${JSON.stringify(req.cookies)}`);
this.logger.debug(`Check auth request. Headers: ${JSON.stringify(req.headers)}`);
if (!req.user) {
this.logger.warn('Unauthorized access attempt');
throw new UnauthorizedException('Пользователь не аутентифицирован');
}
// Явно указываем тип для req.user
const user = req.user as { userId: number; username: string; login?: string };
const userWithoutPassword = { ...user };
this.logger.log(`User authenticated: ${user.username}`);
return {
isAuthenticated: true,
user: userWithoutPassword
};
}
@Post('login')
async login(
@Body() body: { login: string; password: string },
@Res({ passthrough: true }) res: Response,
@Req() req: Request
) {
this.logger.debug(`Login attempt for user: ${body.login}`);
this.logger.debug(`Request cookies: ${JSON.stringify(req.cookies)}`);
this.logger.debug(`Request headers: ${JSON.stringify(req.headers)}`);
const user = await this.authService.validateUser(body.login, body.password);
if (!user) {
this.logger.warn(`Failed login attempt for user: ${body.login}`);
throw new UnauthorizedException('Неверный логин или пароль');
}
const { access_token } = await this.authService.login(user);
res.cookie('access_token', access_token, {
httpOnly: true,
secure: process.env.COOKIE_SECURE === 'true',
sameSite: (process.env.COOKIE_SAME_SITE as 'strict' | 'lax' | 'none') || 'strict',
maxAge: 3600000,
path: '/',
});
this.logger.log(`User ${body.login} successfully logged in`);
this.logger.debug(`Set cookie: access_token=${access_token.substring(0, 10)}...`);
return {
success: true,
user: {
id: user.id,
login: user.login
},
access_token
};
}
@Post('logout')
@UseGuards(JwtAuthGuard)
async logout(@Res({ passthrough: true }) res: Response, @Req() req: Request) {
const user = req.user as { userId: number; username: string };
this.logger.log(`User ${user.username} logging out`);
res.clearCookie('access_token');
return { success: true };
}
}