Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

수정코드 #81

Merged
merged 4 commits into from
Nov 27, 2024
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
3 changes: 2 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { EventsModule } from './events/evnets.module';
import { MessageService } from './message/message.service';
import { MessageModule } from './message/message.module';
import { LoggerMiddleware } from './global/middleware/logger.middleware';
import { HealthController } from './health.controller';

@Module({
imports: [
Expand All @@ -31,7 +32,7 @@ import { LoggerMiddleware } from './global/middleware/logger.middleware';
SseModule,
UserModule,
],
controllers: [SseController],
controllers: [SseController,HealthController],
providers: [MessageService],
})
export class AppModule implements NestModule {
Expand Down
100 changes: 57 additions & 43 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import {
} from '@nestjs/common';
import axios from 'axios';
import { Request, Response } from 'express';
import { UserService } from '../user/user.service';
import { UserService } from 'src/user/user.service';
import { AuthService } from './auth.service';
import { ConfigService } from '@nestjs/config';
import { ApiTags } from '@nestjs/swagger';
import * as domain from "domain";

@ApiTags('Auth')
@Controller('api/v1/auth')
Expand All @@ -29,9 +30,9 @@ export class AuthController {
private readonly refreshTokenPath = '/api/v1/auth/redirect';

constructor(
private readonly config: ConfigService,
private readonly userService: UserService,
private readonly authService: AuthService,
private readonly config: ConfigService,
private readonly userService: UserService,
private readonly authService: AuthService,
) {
this.origin = this.config.get<string>('ORIGIN');
this.client_id = this.config.get<string>('REST_API');
Expand Down Expand Up @@ -60,24 +61,24 @@ export class AuthController {

try {
const accessTokenResponse = await axios.post(
'https://kauth.kakao.com/oauth/token',
data,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'https://kauth.kakao.com/oauth/token',
data,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
},
);

const kakaoUserInfoResponse = await axios.post(
'https://kapi.kakao.com/v2/user/me',
{},
{
headers: {
Authorization: 'Bearer ' + accessTokenResponse.data.access_token,
'Content-Type': 'application/x-www-form-urlencoded',
'https://kapi.kakao.com/v2/user/me',
{},
{
headers: {
Authorization: 'Bearer ' + accessTokenResponse.data.access_token,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
},
);

const kakaoId = kakaoUserInfoResponse.data.id;
Expand All @@ -86,20 +87,21 @@ export class AuthController {
let user = await this.userService.getUserByKakaoId(kakaoId);
if (!user) {
user = await this.userService.createUserWithKakaoIdAndUsername(
kakaoId,
nickname,
kakaoId,
nickname,
);
}

const { accessToken, refreshToken } = await this.authService.createTokens(
user.id,
const {accessToken, refreshToken} = await this.authService.createTokens(
user.id,
);

this.setTokens(
res,
accessToken,
refreshToken,
'http://localhost:3000/boards',
res,
accessToken,
refreshToken,
'here-there-fe.vercel.app',
'https://here-there-fe.vercel.app/boards',
);
} catch {
throw new BadRequestException();
Expand All @@ -108,17 +110,17 @@ export class AuthController {

@Get('redirect/refresh')
async refresh(@Req() req: Request, @Res() res: Response) {
const { accessToken, refreshToken } = await this.authService.refreshTokens(
req.cookies['refreshToken'],
const {accessToken, refreshToken} = await this.authService.refreshTokens(
req.cookies['refreshToken'],
);

this.setTokens(res, accessToken, refreshToken);
this.setTokens(res, accessToken, refreshToken, 'here-there-fe.vercel.app');
}

@Post('logout')
async logout(@Res() res: Response) {
res.clearCookie('accessToken', { path: this.accessTokenPath });
res.clearCookie('refreshToken', { path: this.refreshTokenPath });
res.clearCookie('accessToken', {path: this.accessTokenPath});
res.clearCookie('refreshToken', {path: this.refreshTokenPath});

res.sendStatus(204);
}
Expand All @@ -139,28 +141,37 @@ export class AuthController {
}

private setTokens(
res: Response,
accessToken: string,
refreshToken: string,
redirectUrl?: string,
res: Response,
accessToken: string,
refreshToken: string,
domain: string,
redirectUrl?: string,
) {
// 쿠키 설정 로그 추가
this.logger.log(`Setting accessToken cookie: ${accessToken}`);
this.logger.log(`Setting refreshToken cookie: ${refreshToken}`);
this.logger.log(`Cookie domain: ${domain}`);
this.logger.log(`Redirect URL: ${redirectUrl}`);


res.cookie('accessToken', accessToken, {
httpOnly: true,
// secure: true, // HTTPS 사용 시 활성화
sameSite: 'strict',
path: this.accessTokenPath, // 쿠키가 /api/v1 경로에서만 유효
secure: true,
sameSite: 'none',
//domain,
path: this.accessTokenPath,
});

res.cookie('refreshToken', refreshToken, {
httpOnly: true,
// secure: true, // HTTPS 사용 시 활성화
sameSite: 'strict',
path: this.refreshTokenPath, // 쿠키가 /api/v1/auth/redirect 경로에서만 유효
secure: true,
sameSite: 'none',
//domain,
path: this.refreshTokenPath,
});

this.logger.log(
`Tokens issued - Access Token: ${accessToken}, Refresh Token: ${refreshToken}`,
);

this.logger.log(`Tokens issued - Access Token: ${accessToken}, Refresh Token: ${refreshToken}`);

if (redirectUrl) {
res.redirect(302, redirectUrl);
Expand All @@ -169,3 +180,6 @@ export class AuthController {
}
}
}



6 changes: 3 additions & 3 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { ConfigService } from '@nestjs/config';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
Expand All @@ -37,4 +37,4 @@ export class AuthGuard implements CanActivate {
private extractTokenFromCookie(request: Request): string | undefined {
return request.cookies['accessToken'];
}
}
}
5 changes: 3 additions & 2 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtModule } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { UserModule } from '../user/user.module';
import { AuthGuard } from './auth.guard';

@Module({
imports: [
ConfigModule,
JwtModule.registerAsync({
global: true,
inject: [ConfigService],
Expand All @@ -22,6 +23,6 @@ import { AuthGuard } from './auth.guard';
],
controllers: [AuthController],
providers: [AuthService, AuthGuard],
exports: [AuthGuard],
exports: [AuthGuard, JwtModule],
})
export class AuthModule {}
36 changes: 19 additions & 17 deletions src/board/board.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ import { BoardIdDto } from './dto/boardId.dto';
@ApiTags('Boards')
@Controller('api/v1/boards')
export class BoardController {
constructor(private readonly boardService: BoardService) {}
constructor(private readonly boardService: BoardService,
private readonly jwtService: JwtService,) {}

@ApiQuery({
name: 'page',
Expand All @@ -60,38 +61,39 @@ export class BoardController {
@UseGuards(AuthGuard)
@Post()
async create(
@Body(ValidationPipe) createBoardDto: CreateBoardDto,
@Token('sub') id: number,
@Body(ValidationPipe) createBoardDto: CreateBoardDto,
@Token('sub') id: number,
): Promise<BoardResponseDto> {
console.log('Received CreateBoardDto:', createBoardDto); // 데이터 확인
return this.boardService.createBoard(createBoardDto, id);
}

@ApiOperation({ summary: '특정 게시물 조회' })
@Get(':boardId')
async findOne(
@Param() boardIdDto: BoardIdDto,
@Req() req: Request,
@Param() boardIdDto: BoardIdDto,
@Req() req: Request,
): Promise<BoardResponseDto> {
// 쿠키에서 JWT 토큰을 추출
const token = req.cookies['accessToken'];

if (!token) {
throw new UnauthorizedException('JWT 토큰이 쿠키에 없습니다.');
}
const token = req.cookies?.['accessToken']; // 쿠키가 없는 경우도 처리

// JwtService를 이용해 토큰 디코딩
const jwtService = new JwtService({ secret: 'JWT_SECRET' });
const decodedToken = jwtService.decode(token) as any;
let userId: number | null = null;

// sub 클레임에서 userId 추출
const userId = decodedToken?.sub;
if (!userId) {
throw new UnauthorizedException('유효한 사용자 ID가 아닙니다.');
// 토큰이 있는 경우 디코딩
if (token) {
try {
const decodedToken = this.jwtService.decode(token) as any;
userId = decodedToken?.sub || null;
} catch (error) {
console.warn('JWT 디코딩 실패:', error.message);
userId = null; // 디코딩 실패 시 userId를 null로 설정
}
}

return this.boardService.findOne(boardIdDto.boardId, userId);
}


@ApiOperation({ summary: '게시물 업데이트' })
@ApiCookieAuth()
@UseGuards(AuthGuard)
Expand Down
38 changes: 26 additions & 12 deletions src/board/board.service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Request } from 'express';
import {
ConflictException,
Injectable,
Expand Down Expand Up @@ -148,22 +149,25 @@ export class BoardService {
};
}

async findOne(id: number, userId: number): Promise<BoardResponseDto> {
async findOne(id: number, userId: number | null): Promise<BoardResponseDto> {
const board = await this.boardRepository.findOne({
where: { id },
relations: ['user', 'location'],
});

if (!board) {
throw new NotFoundException(`ID가 ${id}인 게시판을 찾을 수 없습니다.`);
}

const chatRoom: ChatRoom =
await this.chatRoomService.findChatRoomByBoardId(id);
const chatRoom: ChatRoom = await this.chatRoomService.findChatRoomByBoardId(id);
if (!chatRoom) {
throw new NotFoundException('게시판에 연결된 채팅방을 찾을 수 없습니다.');
}

return this.boardMapper.toBoardResponseDto(board, userId, chatRoom);
const response = this.boardMapper.toBoardResponseDto(board, userId, chatRoom);
response.editable = userId === board.user.id;

return response;
}

async updateBoard(
Expand Down Expand Up @@ -235,26 +239,36 @@ export class BoardService {
}

private async getOrCreateLocation(
location: { latitude: number; longitude: number },
location_name: string,
location: { latitude: number; longitude: number },
locationName: string,
): Promise<Location> {
console.log('Received locationName:', locationName); // 추가
console.log('Received location:', location); // 추가

let newLocation: Location =
await this.locationService.findLocationByCoordinates(
location.latitude,
location.longitude,
);
await this.locationService.findLocationByCoordinates(
location.latitude,
location.longitude,
);

if (!newLocation) {
console.log('Creating new location:', {
latitude: location.latitude,
longitude: location.longitude,
location_name: locationName, // 디버깅
});
newLocation = await this.locationService.createLocation({
latitude: location.latitude,
longitude: location.longitude,
location_name,
location_name: locationName, // 필드명 확인
});
} else {
newLocation.locationName = location_name;
console.log('Updating existing location:', newLocation);
newLocation.locationName = locationName;
await this.locationService.updateLocation(newLocation);
}

return newLocation;
}

}
3 changes: 2 additions & 1 deletion src/board/entities/board.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export class Board extends TimeStamp {
@ApiProperty({ description: '날짜', nullable: false })
date: string;

@OneToOne(() => ChatRoom, (chatRoom) => chatRoom.board)
@OneToOne(() => ChatRoom, (chatRoom) => chatRoom.board, { eager: true })
@JoinColumn({ name: 'chat_room_id' })
@ApiProperty({ description: '채팅방' })
chatRoom: ChatRoom;
}
Loading