feat: utilise ConfigService in util functions

This commit is contained in:
Mir Arif Hasan
2023-11-27 11:30:34 +06:00
parent 0a10f7c654
commit 6157848f56
3 changed files with 37 additions and 22 deletions

View File

@@ -6,6 +6,7 @@ import { Response } from 'express';
import * as cookie from 'cookie';
import { AUTH_PROVIDER_NOT_SPECIFIED, COOKIES_NOT_FOUND } from 'src/errors';
import { throwErr } from 'src/utils';
import { ConfigService } from '@nestjs/config';
enum AuthTokenType {
ACCESS_TOKEN = 'access_token',
@@ -45,15 +46,17 @@ export const authCookieHandler = (
redirect: boolean,
redirectUrl: string | null,
) => {
const configService = new ConfigService();
const currentTime = DateTime.now();
const accessTokenValidity = currentTime
.plus({
milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),
milliseconds: parseInt(configService.get('ACCESS_TOKEN_VALIDITY')),
})
.toMillis();
const refreshTokenValidity = currentTime
.plus({
milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),
milliseconds: parseInt(configService.get('REFRESH_TOKEN_VALIDITY')),
})
.toMillis();
@@ -75,10 +78,12 @@ export const authCookieHandler = (
}
// check to see if redirectUrl is a whitelisted url
const whitelistedOrigins = process.env.WHITELISTED_ORIGINS.split(',');
const whitelistedOrigins = configService
.get('WHITELISTED_ORIGINS')
.split(',');
if (!whitelistedOrigins.includes(redirectUrl))
// if it is not redirect by default to REDIRECT_URL
redirectUrl = process.env.REDIRECT_URL;
redirectUrl = configService.get('REDIRECT_URL');
return res.status(HttpStatus.OK).redirect(redirectUrl);
};
@@ -113,14 +118,17 @@ export const subscriptionContextCookieParser = (rawCookies: string) => {
* @returns Boolean if provider specified is present or not
*/
export function authProviderCheck(provider: string) {
const configService = new ConfigService();
if (!provider) {
throwErr(AUTH_PROVIDER_NOT_SPECIFIED);
}
const envVariables = process.env.VITE_ALLOWED_AUTH_PROVIDERS
? process.env.VITE_ALLOWED_AUTH_PROVIDERS.split(',').map((provider) =>
provider.trim().toUpperCase(),
)
const envVariables = configService.get('VITE_ALLOWED_AUTH_PROVIDERS')
? configService
.get('VITE_ALLOWED_AUTH_PROVIDERS')
.split(',')
.map((provider) => provider.trim().toUpperCase())
: [];
if (!envVariables.includes(provider.toUpperCase())) return false;

View File

@@ -6,18 +6,21 @@ import { VersioningType } from '@nestjs/common';
import * as session from 'express-session';
import { emitGQLSchemaFile } from './gql-schema';
import { checkEnvironmentAuthProvider } from './utils';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
console.log(`Running in production: ${process.env.PRODUCTION}`);
console.log(`Port: ${process.env.PORT}`);
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
console.log(`Running in production: ${configService.get('PRODUCTION')}`);
console.log(`Port: ${configService.get('PORT')}`);
checkEnvironmentAuthProvider();
const app = await NestFactory.create(AppModule);
app.use(
session({
secret: process.env.SESSION_SECRET,
secret: configService.get('SESSION_SECRET'),
}),
);
@@ -28,18 +31,18 @@ async function bootstrap() {
}),
);
if (process.env.PRODUCTION === 'false') {
if (configService.get('PRODUCTION') === 'false') {
console.log('Enabling CORS with development settings');
app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','),
origin: configService.get('WHITELISTED_ORIGINS').split(','),
credentials: true,
});
} else {
console.log('Enabling CORS with production settings');
app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','),
origin: configService.get('WHITELISTED_ORIGINS').split(','),
credentials: true,
});
}
@@ -47,7 +50,7 @@ async function bootstrap() {
type: VersioningType.URI,
});
app.use(cookieParser());
await app.listen(process.env.PORT || 3170);
await app.listen(configService.get('PORT') || 3170);
}
if (!process.env.GENERATE_GQL_SCHEMA) {

View File

@@ -16,6 +16,7 @@ import {
JSON_INVALID,
} from './errors';
import { AuthProvider } from './auth/helper';
import { ConfigService } from '@nestjs/config';
/**
* A workaround to throw an exception in an expression.
@@ -165,17 +166,20 @@ export function isValidLength(title: string, length: number) {
* If not, it throws an error.
*/
export function checkEnvironmentAuthProvider() {
if (!process.env.hasOwnProperty('VITE_ALLOWED_AUTH_PROVIDERS')) {
const configService = new ConfigService();
if (!configService.get('VITE_ALLOWED_AUTH_PROVIDERS')) {
throw new Error(ENV_NOT_FOUND_KEY_AUTH_PROVIDERS);
}
if (process.env.VITE_ALLOWED_AUTH_PROVIDERS === '') {
if (configService.get('VITE_ALLOWED_AUTH_PROVIDERS') === '') {
throw new Error(ENV_EMPTY_AUTH_PROVIDERS);
}
const givenAuthProviders = process.env.VITE_ALLOWED_AUTH_PROVIDERS.split(
',',
).map((provider) => provider.toLocaleUpperCase());
const givenAuthProviders = configService
.get('VITE_ALLOWED_AUTH_PROVIDERS')
.split(',')
.map((provider) => provider.toLocaleUpperCase());
const supportedAuthProviders = Object.values(AuthProvider).map(
(provider: string) => provider.toLocaleUpperCase(),
);