Skip to content

Commit

Permalink
Merge pull request #43 from boostcampwm-2024/refactor-be-#42
Browse files Browse the repository at this point in the history
로그인 여부 체크 api 구현
  • Loading branch information
github-actions[bot] authored Jan 16, 2025
2 parents a6e1967 + a596d57 commit 2b59850
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
16 changes: 16 additions & 0 deletions apps/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,22 @@ import { AuthService } from './auth.service';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { Response } from 'express';
import { MessageResponseDto } from './dtos/messageResponse.dto';
import { LoginResponseDto } from './dtos/loginResponse.dto';
import { ApiOperation, ApiResponse } from '@nestjs/swagger';
import { TokenService } from './token/token.service';
import { UpdateUserDto } from './dtos/UpdateUser.dto';

export enum AuthResponseMessage {
AUTH_LOGGED_OUT = '로그아웃하였습니다.',
AUTH_STATUS = '로그인 여부를 확인하였습니다',
}

@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly tokenService: TokenService,
private readonly jwtAuthGuard: JwtAuthGuard,
) {}

@Get('naver')
Expand Down Expand Up @@ -94,6 +97,19 @@ export class AuthController {
});
}

// 클라이언트가 사용자가 로그인되어 있는지 확인할 수 있는 엔드포인트
// auth/status
@ApiResponse({ type: LoginResponseDto })
@ApiOperation({ summary: '사용자가 로그인 여부를 체크합니다.' })
@Get('status')
async checkLogin(@Req() req, @Res() res: Response) {
const isLoggedIn = await this.jwtAuthGuard.isLoggedIn(req, res);
return res.status(200).json({
message: AuthResponseMessage.AUTH_STATUS,
loggedIn: isLoggedIn,
});
}

// 클라이언트가 사용자의 외부 id(snowflakeId) + 이름을 알 수 있는 엔드포인트
// auth/profile
@Get('profile')
Expand Down
18 changes: 18 additions & 0 deletions apps/backend/src/auth/dtos/loginResponse.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsBoolean } from 'class-validator';

export class LoginResponseDto {
@ApiProperty({
example: 'OO 생성에 성공했습니다.',
description: 'api 요청 결과 메시지',
})
@IsString()
message: string;

@ApiProperty({
example: true,
description: '로그인 여부',
})
@IsBoolean()
loggedIn: string;
}
44 changes: 44 additions & 0 deletions apps/backend/src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,48 @@ export class JwtAuthGuard implements CanActivate {
}
}
}

// 제대로 로그인이 안되어있으면 exception 대신 false return
// 쿠키 처리해줌
async isLoggedIn(request, response): Promise<boolean> {
const cookies = request.cookies;

// 쿠키가 없는 경우 false 반환
if (!cookies || !cookies.accessToken || !cookies.refreshToken) {
return false;
}

const { accessToken, refreshToken } = cookies;

try {
// JWT 검증
this.jwtService.verify(accessToken, {
secret: process.env.JWT_SECRET,
});

return true;
} catch (error) {
// accessToken이 만료된 경우
if (error instanceof TokenExpiredError) {
try {
// 새로운 accessToken 발급받기
const newAccessToken =
await this.tokenService.refreshAccessToken(refreshToken);

// 쿠키 업데이트
this.tokenService.setAccessTokenCookie(response, newAccessToken);

return true;
} catch (refreshError) {
// refreshToken 디코딩 실패 시 처리 쿠키 비워줌
this.tokenService.clearCookies(response);
return false;
}
} else {
// accessToken 디코딩(만료가 아닌 이유로) 실패 시 처리 쿠키 비워줌
this.tokenService.clearCookies(response);
return false;
}
}
}
}

0 comments on commit 2b59850

Please sign in to comment.