实现登出接口

This commit is contained in:
2025-05-07 14:44:07 +08:00
parent 1246613fb1
commit 6a44e902fd
2 changed files with 27 additions and 1 deletions

View File

@@ -1,12 +1,15 @@
import { BadRequestException, Body, Controller, Get, Post, Request } from '@nestjs/common';
import { BadRequestException, Body, Controller, Get, Post, Request, UseGuards } from '@nestjs/common';
import { LoginDto } from './dto/login.dto';
import { AuthService } from './auth.service';
import { AuthGuard } from '@nestjs/passport';
import { UserSessionService } from 'src/user/services/user-session.service';
@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly userSessionService: UserSessionService,
) { }
@Post('login')
@@ -22,4 +25,13 @@ export class AuthController {
throw new BadRequestException('服务器错误');
}
}
@UseGuards(AuthGuard('jwt'))
@Get('logout')
async logout(@Request() req) {
const { userId, sessionId } = req.user;
await this.userSessionService.invalidateSession(userId, sessionId);
return true;
}
}

View File

@@ -30,4 +30,18 @@ export class UserSessionService {
return !!session;
}
async invalidateSession(userId: string, sessionId: string): Promise<void> {
const session = await this.userSessionRepository.findOne({
where: {
userId,
sessionId,
deletedAt: null,
}
});
if (session) {
await this.userSessionRepository.softDelete(session.id);
}
}
}