Skip to content

Commit

Permalink
Merge pull request #3 from tscenping/yubin
Browse files Browse the repository at this point in the history
Yubin
  • Loading branch information
yubinquitous authored Nov 10, 2023
2 parents ff8070b + 0067593 commit 2bfa619
Show file tree
Hide file tree
Showing 15 changed files with 149 additions and 52 deletions.
16 changes: 15 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"pg": "^8.11.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
"rxjs": "^7.2.0",
"zod": "^3.22.4"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
Expand Down
13 changes: 9 additions & 4 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeOrmConfig } from './common/config/typeorm.config';
import { AuthModule } from './auth/auth.module';
import ftConfig from './config/ft.config';
import jwtConfig from './config/jwt.config';
import pgadminConfig from './config/pgadmin.config';
import { typeOrmConfig } from './config/typeorm.config';
import userConfig from './config/user.config';
import { UsersModule } from './users/users.module';
import { ConfigModule } from '@nestjs/config';

@Module({
imports: [
TypeOrmModule.forRootAsync(typeOrmConfig),
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
envFilePath: './BE-config/.env',
load: [ftConfig, userConfig, pgadminConfig, jwtConfig],
}),
AuthModule,
UsersModule,
Expand Down
34 changes: 25 additions & 9 deletions src/auth/auth-42.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
Inject,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import axios from 'axios';
import ftConfig from './../config/ft.config';
import { User42Dto } from './dto/user-42.dto';

type FtOauthResponseBody = {
grant_type: string;
client_id: string;
client_secret: string;
code: string;
redirect_uri: string;
};

@Injectable()
export class Auth42Service {
constructor(private readonly configService: ConfigService) {}
constructor(
@Inject(ftConfig.KEY)
private readonly ftConfigure: ConfigType<typeof ftConfig>,
) {}

private readonly logger = new Logger(Auth42Service.name);
private readonly baseUrl = 'https://api.intra.42.fr';
Expand All @@ -16,13 +33,11 @@ export class Auth42Service {
`${this.baseUrl}/oauth/token`,
{
grant_type: 'authorization_code',
client_id: this.configService.get<string>('FORTYTWO_CLIENT_ID'),
client_secret: this.configService.get<string>(
'FORTYTWO_CLIENT_SECRET',
),
client_id: this.ftConfigure.FT_CLIENT_ID,
client_secret: this.ftConfigure.FT_CLIENT_SECRET,
code,
redirect_uri: this.configService.get<string>('FORTYTWO_REDIRECT_URI'),
},
redirect_uri: this.ftConfigure.FT_REDIRECT_URI,
} satisfies FtOauthResponseBody,
{
headers: {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -51,6 +66,7 @@ export class Auth42Service {
fortyTwoId: response.data.id,
};
this.logger.log('user: ', userData);

return userData;
} catch (error) {
this.logger.error(error);
Expand Down
11 changes: 6 additions & 5 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ import {
Controller,
HttpException,
HttpStatus,
Inject,
Logger,
Post,
Res,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ConfigType } from '@nestjs/config';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import userConfig from 'src/config/user.config';
import { User } from 'src/users/entities/user.entity';
import { UsersService } from './../users/users.service';
import { Auth42Service } from './auth-42.service';
Expand All @@ -29,11 +31,10 @@ export class AuthController {
private readonly authService: AuthService,
private readonly auth42Service: Auth42Service,
private readonly usersService: UsersService,
private readonly configService: ConfigService,
@Inject(userConfig.KEY)
private readonly userConfigure: ConfigType<typeof userConfig>,
) {
this.nicknamePrefix = this.configService.getOrThrow<string>(
'FIRST_NICKNAME_PREFIX',
);
this.nicknamePrefix = this.userConfigure.FIRST_NICKNAME_PREFIX;
}
private readonly logger = new Logger(AuthController.name);

Expand Down
18 changes: 11 additions & 7 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
import { Module } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { MulterModule } from '@nestjs/platform-express';
import { TypeOrmModule } from '@nestjs/typeorm';
import { jwtConfig } from '../common/config/jwt.config';
import { multerConfig } from '../common/config/multer.config';
import jwtConfig from '../config/jwt.config';
import { multerConfig } from '../config/multer.config';
import { User } from '../users/entities/user.entity';
import { UserRepository } from '../users/users.repository';
import { UsersService } from '../users/users.service';
import { Auth42Service } from './auth-42.service';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtAccessStrategy } from './jwt-access.strategy';
import { User } from '../users/entities/user.entity';
import { UserRepository } from '../users/users.repository';
import { UsersService } from '../users/users.service';
import { Module } from '@nestjs/common';

@Module({
imports: [
TypeOrmModule.forFeature([User]),
PassportModule,
JwtModule.registerAsync(jwtConfig),
JwtModule.registerAsync({
inject: [jwtConfig.KEY],
useFactory: (jwtConfigure: ConfigType<typeof jwtConfig>) => jwtConfigure,
}),
MulterModule.registerAsync(multerConfig),
],
controllers: [AuthController],
Expand Down
15 changes: 9 additions & 6 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ConfigService } from '@nestjs/config';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import userConfig from 'src/config/user.config';
import { User } from 'src/users/entities/user.entity';
import { UserRepository } from './../users/users.repository';
import { User42Dto } from './dto/user-42.dto';
Expand All @@ -17,11 +18,10 @@ export class AuthService {
constructor(
private readonly userRepository: UserRepository,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
@Inject(userConfig.KEY)
private readonly userConfigure: ConfigType<typeof userConfig>,
) {
this.nicknamePrefix = this.configService.getOrThrow<string>(
'FIRST_NICKNAME_PREFIX',
);
this.nicknamePrefix = this.userConfigure.FIRST_NICKNAME_PREFIX;
}

private async createMfaCode(): Promise<string> {
Expand Down Expand Up @@ -53,10 +53,13 @@ export class AuthService {
const payload = { id: user.id, email: user.email };
// accessToken 생성
const accessToken = await this.jwtService.signAsync(payload);

// refreshToken 생성
const refreshToken = await this.jwtService.signAsync({ id: payload.id });

// refreshToken을 DB에 저장한다.
await this.userRepository.update(user.id, { refreshToken });

return { jwtAccessToken: accessToken, jwtRefreshToken: refreshToken };
}

Expand Down
10 changes: 6 additions & 4 deletions src/auth/jwt-access.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import jwtConfig from 'src/config/jwt.config';
import { User } from 'src/users/entities/user.entity';
import { UserRepository } from 'src/users/users.repository';

Expand All @@ -15,10 +16,11 @@ export class JwtAccessStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UserRepository)
private readonly userRepository: UserRepository,
private readonly configService: ConfigService,
@Inject(jwtConfig.KEY)
private readonly jwtConfigure: ConfigType<typeof jwtConfig>,
) {
super({
secretOrKey: configService.getOrThrow<string>('JWT_SECRET'),
secretOrKey: jwtConfigure.secret,
jwtFromRequest: ExtractJwt.fromExtractors([
(request) => request.cookies?.accessToken,
]),
Expand Down
13 changes: 0 additions & 13 deletions src/common/config/jwt.config.ts

This file was deleted.

16 changes: 16 additions & 0 deletions src/config/ft.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { registerAs } from '@nestjs/config';
import { z } from 'zod';

export const FT_CONFIG = 'ft';

export default registerAs(FT_CONFIG, () => {
const FT_CLIENT_ID = z.string().parse(process.env.FORTYTWO_CLIENT_ID);
const FT_CLIENT_SECRET = z.string().parse(process.env.FORTYTWO_CLIENT_SECRET);
const FT_REDIRECT_URI = z.string().parse(process.env.FORTYTWO_REDIRECT_URI);

return {
FT_CLIENT_ID,
FT_CLIENT_SECRET,
FT_REDIRECT_URI,
};
});
15 changes: 15 additions & 0 deletions src/config/jwt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { registerAs } from '@nestjs/config';
import type { JwtModuleOptions } from '@nestjs/jwt';
import { z } from 'zod';

export default registerAs('jwt', () => {
const secret = z.string().parse(process.env.JWT_SECRET);
const expiresIn = z.string().parse(process.env.JWT_EXPIRATION_TIME);

return {
secret,
signOptions: {
expiresIn,
},
} satisfies JwtModuleOptions;
});
File renamed without changes.
19 changes: 19 additions & 0 deletions src/config/pgadmin.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { registerAs } from '@nestjs/config';
import { z } from 'zod';

export const PGADMIN_CONFIG = 'pgadmin';

export default registerAs(PGADMIN_CONFIG, () => {
const PGADMIN_DEFAULT_EMAIL = z
.string()
.parse(process.env.PGADMIN_DEFAULT_EMAIL);

const PGADMIN_DEFAULT_PASSWORD = z
.string()
.parse(process.env.PGADMIN_DEFAULT_PASSWORD);

return {
PGADMIN_DEFAULT_EMAIL,
PGADMIN_DEFAULT_PASSWORD,
};
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleAsyncOptions } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';

export const typeOrmConfig: TypeOrmModuleAsyncOptions = {
inject: [ConfigService],
Expand All @@ -11,7 +11,7 @@ export const typeOrmConfig: TypeOrmModuleAsyncOptions = {
username: configService.get<string>('POSTGRES_USER'),
password: configService.get<string>('POSTGRES_PASSWORD'),
database: configService.get<string>('POSTGRES_DB'),
entities: [__dirname + '/../../**/entities/*.entity.{js,ts}'],
entities: [__dirname + '/../**/entities/*.entity.{js,ts}'],
synchronize: true,
};
},
Expand Down
14 changes: 14 additions & 0 deletions src/config/user.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { registerAs } from '@nestjs/config';
import { z } from 'zod';

export const USER_CONFIG = 'user';

export default registerAs(USER_CONFIG, () => {
const FIRST_NICKNAME_PREFIX = z
.string()
.parse(process.env.FIRST_NICKNAME_PREFIX);

return {
FIRST_NICKNAME_PREFIX,
};
});

0 comments on commit 2bfa619

Please sign in to comment.