chore: moved auth utility functions to auth/helper.ts from src/utils.ts

This commit is contained in:
Balu Babu
2023-02-01 18:47:11 +05:30
parent 587e7118c9
commit b5e7877912
4 changed files with 311 additions and 308 deletions

View File

@@ -1,4 +1,4 @@
import { ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { pipe } from 'fp-ts/lib/function';
import * as O from 'fp-ts/Option';
@@ -7,10 +7,6 @@ import * as T from 'fp-ts/Task';
import * as E from 'fp-ts/Either';
import { User } from './user/user.model';
import * as A from 'fp-ts/Array';
import { AuthError } from './types/AuthError';
import { AuthTokens } from './types/AuthTokens';
import { Response } from 'express';
import { DateTime } from 'luxon';
import { JSON_INVALID } from './errors';
/**
@@ -23,15 +19,6 @@ export function throwErr(errMessage: string): never {
throw new Error(errMessage);
}
/**
* This function allows throw to be used as an expression
* @param errMessage Message present in the error message
*/
export function throwHTTPErr(errorData: AuthError): never {
const { message, statusCode } = errorData;
throw new HttpException(message, statusCode);
}
/**
* Prints the given value to log and returns the same value.
* Used for debugging functional pipelines.
@@ -136,48 +123,6 @@ export const validateEmail = (email: string) => {
).test(email);
};
/**
* Sets and returns the cookies in the response object on successful authentication
* @param res Express Response Object
* @param authTokens Object containing the access and refresh tokens
* @param redirect if true will redirect to provided URL else just send a 200 status code
*/
export const authCookieHandler = (
res: Response,
authTokens: AuthTokens,
redirect: boolean,
) => {
const currentTime = DateTime.now();
const accessTokenValidity = currentTime
.plus({
milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),
})
.toMillis();
const refreshTokenValidity = currentTime
.plus({
milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),
})
.toMillis();
res.cookie('access_token', authTokens.access_token, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: accessTokenValidity,
signed: true,
});
res.cookie('refresh_token', authTokens.refresh_token, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: refreshTokenValidity,
signed: true,
});
if (redirect) {
res.status(HttpStatus.OK).redirect(process.env.REDIRECT_URL);
} else res.status(HttpStatus.OK).send();
};
/*
* String to JSON parser
* @param {str} str The string to parse