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 * as cookie from 'cookie';
import { AUTH_PROVIDER_NOT_SPECIFIED, COOKIES_NOT_FOUND } from 'src/errors'; import { AUTH_PROVIDER_NOT_SPECIFIED, COOKIES_NOT_FOUND } from 'src/errors';
import { throwErr } from 'src/utils'; import { throwErr } from 'src/utils';
import { ConfigService } from '@nestjs/config';
enum AuthTokenType { enum AuthTokenType {
ACCESS_TOKEN = 'access_token', ACCESS_TOKEN = 'access_token',
@@ -45,15 +46,17 @@ export const authCookieHandler = (
redirect: boolean, redirect: boolean,
redirectUrl: string | null, redirectUrl: string | null,
) => { ) => {
const configService = new ConfigService();
const currentTime = DateTime.now(); const currentTime = DateTime.now();
const accessTokenValidity = currentTime const accessTokenValidity = currentTime
.plus({ .plus({
milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY), milliseconds: parseInt(configService.get('ACCESS_TOKEN_VALIDITY')),
}) })
.toMillis(); .toMillis();
const refreshTokenValidity = currentTime const refreshTokenValidity = currentTime
.plus({ .plus({
milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY), milliseconds: parseInt(configService.get('REFRESH_TOKEN_VALIDITY')),
}) })
.toMillis(); .toMillis();
@@ -75,10 +78,12 @@ export const authCookieHandler = (
} }
// check to see if redirectUrl is a whitelisted url // 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 (!whitelistedOrigins.includes(redirectUrl))
// if it is not redirect by default to REDIRECT_URL // 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); 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 * @returns Boolean if provider specified is present or not
*/ */
export function authProviderCheck(provider: string) { export function authProviderCheck(provider: string) {
const configService = new ConfigService();
if (!provider) { if (!provider) {
throwErr(AUTH_PROVIDER_NOT_SPECIFIED); throwErr(AUTH_PROVIDER_NOT_SPECIFIED);
} }
const envVariables = process.env.VITE_ALLOWED_AUTH_PROVIDERS const envVariables = configService.get('VITE_ALLOWED_AUTH_PROVIDERS')
? process.env.VITE_ALLOWED_AUTH_PROVIDERS.split(',').map((provider) => ? configService
provider.trim().toUpperCase(), .get('VITE_ALLOWED_AUTH_PROVIDERS')
) .split(',')
.map((provider) => provider.trim().toUpperCase())
: []; : [];
if (!envVariables.includes(provider.toUpperCase())) return false; 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 * as session from 'express-session';
import { emitGQLSchemaFile } from './gql-schema'; import { emitGQLSchemaFile } from './gql-schema';
import { checkEnvironmentAuthProvider } from './utils'; import { checkEnvironmentAuthProvider } from './utils';
import { ConfigService } from '@nestjs/config';
async function bootstrap() { async function bootstrap() {
console.log(`Running in production: ${process.env.PRODUCTION}`); const app = await NestFactory.create(AppModule);
console.log(`Port: ${process.env.PORT}`);
const configService = app.get(ConfigService);
console.log(`Running in production: ${configService.get('PRODUCTION')}`);
console.log(`Port: ${configService.get('PORT')}`);
checkEnvironmentAuthProvider(); checkEnvironmentAuthProvider();
const app = await NestFactory.create(AppModule);
app.use( app.use(
session({ 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'); console.log('Enabling CORS with development settings');
app.enableCors({ app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','), origin: configService.get('WHITELISTED_ORIGINS').split(','),
credentials: true, credentials: true,
}); });
} else { } else {
console.log('Enabling CORS with production settings'); console.log('Enabling CORS with production settings');
app.enableCors({ app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','), origin: configService.get('WHITELISTED_ORIGINS').split(','),
credentials: true, credentials: true,
}); });
} }
@@ -47,7 +50,7 @@ async function bootstrap() {
type: VersioningType.URI, type: VersioningType.URI,
}); });
app.use(cookieParser()); app.use(cookieParser());
await app.listen(process.env.PORT || 3170); await app.listen(configService.get('PORT') || 3170);
} }
if (!process.env.GENERATE_GQL_SCHEMA) { if (!process.env.GENERATE_GQL_SCHEMA) {

View File

@@ -16,6 +16,7 @@ import {
JSON_INVALID, JSON_INVALID,
} from './errors'; } from './errors';
import { AuthProvider } from './auth/helper'; import { AuthProvider } from './auth/helper';
import { ConfigService } from '@nestjs/config';
/** /**
* A workaround to throw an exception in an expression. * 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. * If not, it throws an error.
*/ */
export function checkEnvironmentAuthProvider() { 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); 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); throw new Error(ENV_EMPTY_AUTH_PROVIDERS);
} }
const givenAuthProviders = process.env.VITE_ALLOWED_AUTH_PROVIDERS.split( const givenAuthProviders = configService
',', .get('VITE_ALLOWED_AUTH_PROVIDERS')
).map((provider) => provider.toLocaleUpperCase()); .split(',')
.map((provider) => provider.toLocaleUpperCase());
const supportedAuthProviders = Object.values(AuthProvider).map( const supportedAuthProviders = Object.values(AuthProvider).map(
(provider: string) => provider.toLocaleUpperCase(), (provider: string) => provider.toLocaleUpperCase(),
); );