实现登出接口
This commit is contained in:
@@ -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 { LoginDto } from './dto/login.dto';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
import { UserSessionService } from 'src/user/services/user-session.service';
|
||||||
|
|
||||||
@Controller('auth')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly authService: AuthService,
|
private readonly authService: AuthService,
|
||||||
|
private readonly userSessionService: UserSessionService,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
@Post('login')
|
@Post('login')
|
||||||
@@ -22,4 +25,13 @@ export class AuthController {
|
|||||||
throw new BadRequestException('服务器错误');
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,4 +30,18 @@ export class UserSessionService {
|
|||||||
|
|
||||||
return !!session;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user