7/15 JWT(2)

JK·2023년 7월 16일
0

여기저기 정보를 찾아보며 해보려는데 잘 안되는 거 같습니다...
코드는 클론 코딩을 해와서 잘 돌아가는 코드 일낸대 그걸 저희 파일에 붙이려니까 쉽지 않은 거 같습니다

typeorm이 버전이 올라가면서 많은 기능들이 바뀌어서 그걸 맞추면 다른 npm이랑 충돌이 나고... 그래도 계속 해봐야겠지요

오늘은 작성한 코드를 공유해보겠습니다

src/app.module.ts
import { MongooseModule } from '@nestjs/mongoose';
import { S3Module } from './s3/s3.module';
import { VideoModule } from './video/video.module';
import { AuthModule } from './auth/auth.module';

@Module({
  imports: [
    ConfigModule.forRoot({isGlobal:true}), //git에 중요정보를 올리지 않기 위해 .env 사용 - 다른 모듈에서도 사용가능
    MongooseModule.forRoot(process.env.MONGODB_URI),
    UserModule,
    S3Module,
    VideoModule],
    VideoModule,
    AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt/jwt.strategy';

@Module({
  imports: [
    // strategy 설정
    PassportModule.register({ defaultStrategy: 'jwt', session: false }),
    //
    JwtModule.register({
      secret: 'secret',
      signOptions: { expiresIn: '1y' },
    }),
  ],
  providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
src/auth/auth.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';

describe('AuthService', () => {
  let service: AuthService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [AuthService],
    }).compile();

    service = module.get<AuthService>(AuthService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});
src/auth/auth.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class AuthService {}
src/auth/jwt/jwt.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
src/auth/jwt/jwt.strategy.ts
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    // 토큰 추출, 시크릿 키, 로그인 만료기간
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey',
      ignoreExpiration: false,
    });
  }
  // 인증부분
  //   async validate(payload) {}
}
src/common/exceptions/http-exception.filter.ts
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const error = exception.getResponse() as
      | string
      | { error: string; statusCode: number; message: string | string[] };

    if (typeof error === 'string') {
      response.status(status).json({
        success: false,
        timestamp: new Date().toISOString(),
        path: request.url,
        error,
      });
    } else {
      response.status(status).json({
        success: false,
        timestamp: new Date().toISOString(),
        ...error,
      });
    }
  }
}

계속 고치면서 하고 있지만 쉽지 않네요. ㅠㅠㅠ
내일이어서 해보도록 하겠습니다

profile
^^

0개의 댓글

관련 채용 정보