Skip to content

Commit e7dab55

Browse files
committed
Refactor env variable imports
1 parent d9b3d46 commit e7dab55

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+276
-149
lines changed

backend/auth-service/src/app.controller.spec.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,4 @@ describe('AppController', () => {
1313

1414
appController = app.get<AppController>(AppController);
1515
});
16-
1716
});

backend/auth-service/src/app.module.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ import { AppController } from './app.controller';
33
import { AppService } from './app.service';
44
import { PassportModule } from '@nestjs/passport';
55
import { JwtModule } from '@nestjs/jwt';
6-
import { ClientsModule, Transport } from '@nestjs/microservices';
6+
import { ClientsModule } from '@nestjs/microservices';
77
import { HttpModule } from '@nestjs/axios';
8+
import { config } from './configs';
89
import {
910
AccessTokenStrategy,
1011
RefreshTokenStrategy,
@@ -14,16 +15,18 @@ import {
1415

1516
@Module({
1617
imports: [
17-
PassportModule.register({ defaultStrategy: 'jwt' }),
18+
PassportModule.register({
19+
defaultStrategy: config.strategies.accessTokenStrategy
20+
}),
1821
HttpModule,
1922
JwtModule.register({}),
2023
ClientsModule.register([
2124
{
2225
name: 'USER_SERVICE',
23-
transport: Transport.TCP,
26+
transport: config.userService.transport,
2427
options: {
25-
host: 'user-service',
26-
port: 3001,
28+
host: config.userService.host,
29+
port: config.userService.port,
2730
},
2831
},
2932
]),

backend/auth-service/src/app.service.ts

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import axios, { AxiosResponse } from 'axios';
1717
import { Token, TokenPayload } from './interfaces';
1818
import { AccountProvider } from './constants/account-provider.enum';
1919
import * as nodemailer from 'nodemailer';
20+
import { config } from 'src/configs';
2021

2122
const SALT_ROUNDS = 10;
2223

@@ -30,9 +31,9 @@ export class AppService {
3031
@Inject('USER_SERVICE') private readonly userClient: ClientProxy,
3132
) {
3233
this.oauthClient = new OAuth2Client({
33-
clientId: process.env.GOOGLE_CLIENT_ID,
34-
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
35-
redirectUri: process.env.GOOGLE_CALLBACK_URL,
34+
clientId: config.auth.google.clientId,
35+
clientSecret: config.auth.google.clientSecret,
36+
redirectUri: config.auth.google.callbackUrl,
3637
});
3738
}
3839

@@ -154,7 +155,9 @@ export class AppService {
154155
}
155156
}
156157

157-
public async generateResetPasswordRequest(dto: ResetPasswordRequestDto): Promise<boolean> {
158+
public async generateResetPasswordRequest(
159+
dto: ResetPasswordRequestDto,
160+
): Promise<boolean> {
158161
const user = await firstValueFrom(
159162
this.userClient.send(
160163
{
@@ -171,7 +174,7 @@ export class AppService {
171174
const resetToken = this.jwtService.sign(
172175
{ userId: user._id.toString(), email: dto.email, type: 'reset-password' },
173176
{
174-
secret: process.env.JWT_SECRET,
177+
secret: config.auth.local.jwtSecret,
175178
expiresIn: '1hr',
176179
},
177180
);
@@ -204,7 +207,7 @@ export class AppService {
204207
public async validatePasswordResetToken(token: string): Promise<any> {
205208
try {
206209
const decoded = this.jwtService.verify(token, {
207-
secret: process.env.JWT_SECRET,
210+
secret: config.auth.local.jwtSecret,
208211
});
209212
const { userId, email, type } = decoded;
210213
if (type !== 'reset-password') {
@@ -223,16 +226,16 @@ export class AppService {
223226
}
224227

225228
private async sendResetEmail(email: string, token: string) {
226-
const resetUrl = `${process.env.FRONTEND_URL}/reset-password?token=${token}`; // To change next time
229+
const resetUrl = `${config.frontendUrl}/reset-password?token=${token}`; // To change next time
227230

228231
const transporter = nodemailer.createTransport({
229232
service: 'gmail',
230233
host: 'smtp.gmail.com',
231234
port: 465,
232235
secure: true,
233236
auth: {
234-
user: process.env.NODEMAILER_GMAIL_USER,
235-
pass: process.env.NODEMAILER_GMAIL_PASSWORD,
237+
user: config.mailer.user,
238+
pass: config.mailer.password,
236239
},
237240
});
238241

@@ -253,7 +256,7 @@ export class AppService {
253256
public async validateAccessToken(accessToken: string): Promise<any> {
254257
try {
255258
const decoded = this.jwtService.verify(accessToken, {
256-
secret: process.env.JWT_SECRET,
259+
secret: config.auth.local.jwtSecret,
257260
});
258261
return decoded;
259262
} catch (error) {
@@ -264,7 +267,7 @@ export class AppService {
264267
public async validateRefreshToken(refreshToken: string): Promise<any> {
265268
try {
266269
const decoded = this.jwtService.verify(refreshToken, {
267-
secret: process.env.JWT_REFRESH_SECRET,
270+
secret: config.auth.local.jwtRefreshSecret,
268271
});
269272
return decoded;
270273
} catch (error) {
@@ -293,13 +296,13 @@ export class AppService {
293296

294297
const [accessToken, refreshToken] = await Promise.all([
295298
this.jwtService.signAsync(
296-
{
297-
sub: id,
298-
...rest,
299-
},
300-
{
301-
secret: process.env.JWT_SECRET,
302-
expiresIn: '1h', // 1 hour
299+
{
300+
sub: id,
301+
...rest,
302+
},
303+
{
304+
secret: config.auth.local.jwtSecret,
305+
expiresIn: '1h', // 1 hour
303306
},
304307
),
305308
this.jwtService.signAsync(
@@ -308,7 +311,7 @@ export class AppService {
308311
...rest,
309312
},
310313
{
311-
secret: process.env.JWT_REFRESH_SECRET,
314+
secret: config.auth.local.jwtRefreshSecret,
312315
expiresIn: '7d', // 1 week
313316
},
314317
),
@@ -321,8 +324,8 @@ export class AppService {
321324
}
322325

323326
getGoogleOAuthUrl(): string {
324-
const clientId = process.env.GOOGLE_CLIENT_ID;
325-
const redirectUri = process.env.GOOGLE_CALLBACK_URL;
327+
const clientId = config.auth.google.clientId;
328+
const redirectUri = config.auth.google.callbackUrl;
326329
const scope = encodeURIComponent('email profile');
327330
const responseType = 'code';
328331
const state = 'secureRandomState';
@@ -402,7 +405,7 @@ export class AppService {
402405

403406
const ticket = await this.oauthClient.verifyIdToken({
404407
idToken: tokens.id_token,
405-
audience: process.env.GOOGLE_CLIENT_ID,
408+
audience: config.auth.google.clientId,
406409
});
407410

408411
const payload = ticket.getPayload();
@@ -426,8 +429,8 @@ export class AppService {
426429
}
427430

428431
getGithubOAuthUrl(): string {
429-
const clientId = process.env.GITHUB_CLIENT_ID;
430-
const redirectUri = process.env.GITHUB_CALLBACK_URL;
432+
const clientId = config.auth.github.clientId;
433+
const redirectUri = config.auth.github.callbackUrl;
431434
const scope = 'user:email';
432435

433436
const githubLoginUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(
@@ -484,10 +487,10 @@ export class AppService {
484487
private async exchangeGithubCodeForTokens(code: string) {
485488
try {
486489
const params = {
487-
client_id: process.env.GITHUB_CLIENT_ID,
488-
client_secret: process.env.GITHUB_CLIENT_SECRET,
490+
client_id: config.auth.github.clientId,
491+
client_secret: config.auth.github.clientSecret,
489492
code: code,
490-
redirect_uri: process.env.GITHUB_CALLBACK_URL,
493+
redirect_uri: config.auth.github.callbackUrl,
491494
};
492495
const headers = {
493496
Accept: 'application/json',
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { Transport } from '@nestjs/microservices';
2+
3+
export const config = {
4+
authService: {
5+
port: parseInt(process.env.AUTH_SERVICE_PORT) || 3003,
6+
host: process.env.AUTH_SERVICE_HOST || '0.0.0.0',
7+
transport: Transport[process.env.AUTH_SERVICE_TRANSPORT] || Transport.TCP,
8+
},
9+
userService: {
10+
port: parseInt(process.env.USER_SERVICE_PORT) || 3001,
11+
host: process.env.USER_SERVICE_HOST || 'user-service',
12+
transport: Transport[process.env.USER_SERVICE_TRANSPORT] || Transport.TCP,
13+
},
14+
strategies: {
15+
accessTokenStrategy: process.env.ACCESS_TOKEN_STRATEGY || 'jwt',
16+
refreshTokenStrategy: process.env.REFRESH_TOKEN_STRATEGY || 'jwt-refresh',
17+
googleStrategy: process.env.GOOGLE_STRATEGY || 'google',
18+
githubStrategy: process.env.GITHUB_STRATEGY || 'github',
19+
},
20+
auth: {
21+
local: {
22+
jwtSecret: process.env.JWT_SECRET,
23+
jwtRefreshSecret: process.env.JWT_REFRESH_SECRET,
24+
},
25+
google: {
26+
clientId: process.env.GOOGLE_CLIENT_ID,
27+
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
28+
callbackUrl: process.env.GOOGLE_CALLBACK_URL,
29+
},
30+
github: {
31+
clientId: process.env.GITHUB_CLIENT_ID,
32+
clientSecret: process.env.GITHUB_CLIENT_SECRET,
33+
callbackUrl: process.env.GITHUB_CALLBACK_URL,
34+
},
35+
},
36+
mailer: {
37+
user: process.env.NODEMAILER_GMAIL_USER,
38+
password: process.env.NODEMAILER_GMAIL_PASSWORD,
39+
},
40+
frontendUrl: process.env.FRONTEND_URL || 'http://localhost:3000',
41+
};
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './env.config';

backend/auth-service/src/main.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,21 @@ import { NestFactory } from '@nestjs/core';
22
import { AppModule } from './app.module';
33
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
44
import { ValidationPipe } from '@nestjs/common';
5+
import { config } from './configs';
56

67
async function bootstrap() {
78
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
89
AppModule,
910
{
10-
transport: Transport.TCP,
11+
transport: config.authService.transport,
1112
options: {
12-
host: '0.0.0.0',
13-
port: 3003,
13+
host: config.authService.host,
14+
port: config.authService.port,
1415
},
1516
},
1617
);
1718
app.useGlobalPipes(new ValidationPipe());
1819
await app.listen();
19-
console.log('Auth Service is listening on port 3003');
20+
console.log('Auth Service is listening on port', config.authService.port);
2021
}
2122
bootstrap();

backend/auth-service/src/strategies/access-token.strategy.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import { Injectable } from '@nestjs/common';
22
import { PassportStrategy } from '@nestjs/passport';
33
import { Strategy, ExtractJwt } from 'passport-jwt';
4+
import { config } from 'src/configs';
45

56
@Injectable()
6-
export class AccessTokenStrategy extends PassportStrategy(Strategy, 'jwt') {
7+
export class AccessTokenStrategy extends PassportStrategy(Strategy, config.strategies.accessTokenStrategy) {
78
constructor() {
89
super({
910
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
1011
ignoreExpiration: false,
11-
secretOrKey: process.env.JWT_SECRET,
12+
secretOrKey: config.auth.local.jwtSecret,
1213
});
1314
}
1415

backend/auth-service/src/strategies/github.strategy.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
import { PassportStrategy } from '@nestjs/passport';
22
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
33
import { Injectable } from '@nestjs/common';
4+
import { config } from 'src/configs';
45

56
@Injectable()
6-
export class GithubStrategy extends PassportStrategy(Strategy, 'github') {
7+
export class GithubStrategy extends PassportStrategy(
8+
Strategy,
9+
config.strategies.githubStrategy
10+
) {
711
constructor() {
812
super({
9-
clientID: process.env.GITHUB_CLIENT_ID,
10-
clientSecret: process.env.GITHUB_CLIENT_SECRET,
11-
callbackURL: process.env.GITHUB_CALLBACK_URL,
13+
clientID: config.auth.github.clientId,
14+
clientSecret: config.auth.github.clientSecret,
15+
callbackURL: config.auth.github.callbackUrl,
1216
scope: ['user:email'],
1317
});
1418
}

backend/auth-service/src/strategies/google.strategy.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
import { PassportStrategy } from '@nestjs/passport';
22
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
33
import { Injectable } from '@nestjs/common';
4+
import { config } from 'src/configs';
45

56
@Injectable()
6-
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
7+
export class GoogleStrategy extends PassportStrategy(
8+
Strategy,
9+
config.strategies.googleStrategy
10+
) {
711
constructor() {
812
super({
9-
clientID: process.env.GOOGLE_CLIENT_ID,
10-
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
11-
callbackURL: process.env.GOOGLE_CALLBACK_URL,
13+
clientID: config.auth.google.clientId,
14+
clientSecret: config.auth.google.clientSecret,
15+
callbackURL: config.auth.google.callbackUrl,
1216
scope: ['email', 'profile'],
1317
});
1418
}

backend/auth-service/src/strategies/refresh-token.strategy.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@ import { PassportStrategy } from '@nestjs/passport';
22
import { Strategy, ExtractJwt } from 'passport-jwt';
33
import { Request } from 'express';
44
import { Injectable } from '@nestjs/common';
5+
import { config } from 'src/configs';
56

67
@Injectable()
78
export class RefreshTokenStrategy extends PassportStrategy(
89
Strategy,
9-
'jwt-refresh',
10+
config.strategies.refreshTokenStrategy,
1011
) {
1112
constructor() {
1213
super({
1314
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
1415
ignoreExpiration: false,
15-
secretOrKey: process.env.JWT_REFRESH_SECRET,
16+
secretOrKey: config.auth.local.jwtRefreshSecret,
1617
passReqToCallback: true, // Pass the token back to the callback
1718
});
1819
}

0 commit comments

Comments
 (0)