Skip to content

Commit dfbf3b2

Browse files
authored
Merge pull request #79 from CS3219-AY2425S1/ms4-evan/shared-dto
Centralise env variables handling
2 parents b54726b + d911149 commit dfbf3b2

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

+267
-142
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: 21 additions & 20 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

@@ -173,7 +174,7 @@ export class AppService {
173174
const resetToken = this.jwtService.sign(
174175
{ userId: user._id.toString(), email: dto.email, type: 'reset-password' },
175176
{
176-
secret: process.env.JWT_SECRET,
177+
secret: config.auth.local.jwtSecret,
177178
expiresIn: '1hr',
178179
},
179180
);
@@ -206,7 +207,7 @@ export class AppService {
206207
public async validatePasswordResetToken(token: string): Promise<any> {
207208
try {
208209
const decoded = this.jwtService.verify(token, {
209-
secret: process.env.JWT_SECRET,
210+
secret: config.auth.local.jwtSecret,
210211
});
211212
const { userId, email, type } = decoded;
212213
if (type !== 'reset-password') {
@@ -225,16 +226,16 @@ export class AppService {
225226
}
226227

227228
private async sendResetEmail(email: string, token: string) {
228-
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
229230

230231
const transporter = nodemailer.createTransport({
231232
service: 'gmail',
232233
host: 'smtp.gmail.com',
233234
port: 465,
234235
secure: true,
235236
auth: {
236-
user: process.env.NODEMAILER_GMAIL_USER,
237-
pass: process.env.NODEMAILER_GMAIL_PASSWORD,
237+
user: config.mailer.user,
238+
pass: config.mailer.password,
238239
},
239240
});
240241

@@ -255,7 +256,7 @@ export class AppService {
255256
public async validateAccessToken(accessToken: string): Promise<any> {
256257
try {
257258
const decoded = this.jwtService.verify(accessToken, {
258-
secret: process.env.JWT_SECRET,
259+
secret: config.auth.local.jwtSecret,
259260
});
260261
return decoded;
261262
} catch (error) {
@@ -266,7 +267,7 @@ export class AppService {
266267
public async validateRefreshToken(refreshToken: string): Promise<any> {
267268
try {
268269
const decoded = this.jwtService.verify(refreshToken, {
269-
secret: process.env.JWT_REFRESH_SECRET,
270+
secret: config.auth.local.jwtRefreshSecret,
270271
});
271272
return decoded;
272273
} catch (error) {
@@ -300,7 +301,7 @@ export class AppService {
300301
...rest,
301302
},
302303
{
303-
secret: process.env.JWT_SECRET,
304+
secret: config.auth.local.jwtSecret,
304305
expiresIn: '1h', // 1 hour
305306
},
306307
),
@@ -310,7 +311,7 @@ export class AppService {
310311
...rest,
311312
},
312313
{
313-
secret: process.env.JWT_REFRESH_SECRET,
314+
secret: config.auth.local.jwtRefreshSecret,
314315
expiresIn: '7d', // 1 week
315316
},
316317
),
@@ -323,8 +324,8 @@ export class AppService {
323324
}
324325

325326
getGoogleOAuthUrl(): string {
326-
const clientId = process.env.GOOGLE_CLIENT_ID;
327-
const redirectUri = process.env.GOOGLE_CALLBACK_URL;
327+
const clientId = config.auth.google.clientId;
328+
const redirectUri = config.auth.google.callbackUrl;
328329
const scope = encodeURIComponent('email profile');
329330
const responseType = 'code';
330331
const state = 'secureRandomState';
@@ -404,7 +405,7 @@ export class AppService {
404405

405406
const ticket = await this.oauthClient.verifyIdToken({
406407
idToken: tokens.id_token,
407-
audience: process.env.GOOGLE_CLIENT_ID,
408+
audience: config.auth.google.clientId,
408409
});
409410

410411
const payload = ticket.getPayload();
@@ -428,8 +429,8 @@ export class AppService {
428429
}
429430

430431
getGithubOAuthUrl(): string {
431-
const clientId = process.env.GITHUB_CLIENT_ID;
432-
const redirectUri = process.env.GITHUB_CALLBACK_URL;
432+
const clientId = config.auth.github.clientId;
433+
const redirectUri = config.auth.github.callbackUrl;
433434
const scope = 'user:email';
434435

435436
const githubLoginUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(
@@ -486,10 +487,10 @@ export class AppService {
486487
private async exchangeGithubCodeForTokens(code: string) {
487488
try {
488489
const params = {
489-
client_id: process.env.GITHUB_CLIENT_ID,
490-
client_secret: process.env.GITHUB_CLIENT_SECRET,
490+
client_id: config.auth.github.clientId,
491+
client_secret: config.auth.github.clientSecret,
491492
code: code,
492-
redirect_uri: process.env.GITHUB_CALLBACK_URL,
493+
redirect_uri: config.auth.github.callbackUrl,
493494
};
494495
const headers = {
495496
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)