Skip to content

Commit cc59d94

Browse files
committed
Added code to take JWT secret from env file
1 parent 16178bf commit cc59d94

File tree

5 files changed

+20
-9
lines changed

5 files changed

+20
-9
lines changed

server/.env.example

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
APP_SECRET=
12
DB_HOST=localhost
23
DB_PORT=3306
34
DB_USERNAME=root

server/src/config/app.config.ts

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export default () => ({
2+
appSecret: process.env.APP_SECRET,
3+
});

server/src/config/jwt.config.ts

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { JwtModuleAsyncOptions } from '@nestjs/jwt';
2+
3+
import appConfig from './app.config';
4+
5+
export const jwtConfig: JwtModuleAsyncOptions = {
6+
useFactory: () => {
7+
return {
8+
secret: appConfig().appSecret,
9+
signOptions: { expiresIn: '1d' },
10+
};
11+
},
12+
};

server/src/modules/auth/auth.module.ts

+2-8
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,10 @@ import { UserModule } from '../user/user.module';
66
import { PassportModule } from '@nestjs/passport';
77
import { JwtModule } from '@nestjs/jwt';
88
import { JwtStrategy } from './jwt.strategy';
9+
import { jwtConfig } from '../../config/jwt.config';
910

1011
@Module({
11-
imports: [
12-
UserModule,
13-
PassportModule,
14-
JwtModule.register({
15-
secret: 'asdasghgfhgfh5355dfgfg345345',
16-
signOptions: { expiresIn: '1d' },
17-
}),
18-
],
12+
imports: [UserModule, PassportModule, JwtModule.registerAsync(jwtConfig)],
1913
providers: [AuthService, LocalStrategy, JwtStrategy],
2014
controllers: [AuthController],
2115
})

server/src/modules/auth/jwt.strategy.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import { PassportStrategy } from '@nestjs/passport';
22
import { ExtractJwt, Strategy } from 'passport-jwt';
3+
import appConfig from '../../config/app.config';
34

45
export class JwtStrategy extends PassportStrategy(Strategy) {
56
constructor() {
67
super({
78
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
8-
secretOrKey: 'asdasghgfhgfh5355dfgfg345345',
9+
secretOrKey: appConfig().appSecret,
910
});
1011
}
1112

0 commit comments

Comments
 (0)