From cc54f315a586f24d239029ce42fbf5efab9c59ca Mon Sep 17 00:00:00 2001 From: Luke Taylor Date: Sun, 26 Nov 2023 21:53:11 -0500 Subject: [PATCH] refactor: Make a COOKIE_DOMAIN constant --- packages/api-v2/src/auth/auth.controller.ts | 16 +++++++--------- packages/api-v2/src/constants.ts | 9 +++++++++ 2 files changed, 16 insertions(+), 9 deletions(-) create mode 100644 packages/api-v2/src/constants.ts diff --git a/packages/api-v2/src/auth/auth.controller.ts b/packages/api-v2/src/auth/auth.controller.ts index eedde14fe..56720b7ca 100644 --- a/packages/api-v2/src/auth/auth.controller.ts +++ b/packages/api-v2/src/auth/auth.controller.ts @@ -31,6 +31,7 @@ import { } from "../../src/student/student.errors"; import { BadToken, InvalidPayload, TokenExpiredError } from "./auth.errors"; import { Throttle } from "@nestjs/throttler"; +import { COOKIE_DOMAIN } from "../../src/constants"; @Controller("auth") export class AuthController { @@ -61,14 +62,13 @@ export class AuthController { const { accessToken } = student; const isSecure = process.env.NODE_ENV !== "development"; - const domain = - process.env.NODE_ENV === "production" ? "graduatenu.com" : "localhost"; + // Store JWT token in a cookie response.cookie("auth_cookie", accessToken, { httpOnly: true, sameSite: "strict", secure: isSecure, - domain, + domain: COOKIE_DOMAIN, }); if (process.env.NODE_ENV !== "testing") { await this.emailConfirmationService.sendVerificationLink( @@ -93,14 +93,13 @@ export class AuthController { const { accessToken } = student; const isSecure = process.env.NODE_ENV !== "development"; - const domain = - process.env.NODE_ENV === "production" ? "graduatenu.com" : "localhost"; + // Store JWT token in a cookie response.cookie("auth_cookie", accessToken, { httpOnly: true, sameSite: "strict", secure: isSecure, - domain, + domain: COOKIE_DOMAIN, }); return student; @@ -158,13 +157,12 @@ export class AuthController { @Res({ passthrough: true }) response: Response ): Promise { const isSecure = process.env.NODE_ENV !== "development"; - const domain = - process.env.NODE_ENV === "production" ? "graduatenu.com" : "localhost"; + response.clearCookie("auth_cookie", { httpOnly: true, sameSite: "strict", secure: isSecure, - domain, + domain: COOKIE_DOMAIN, }); } } diff --git a/packages/api-v2/src/constants.ts b/packages/api-v2/src/constants.ts new file mode 100644 index 000000000..4af358ff8 --- /dev/null +++ b/packages/api-v2/src/constants.ts @@ -0,0 +1,9 @@ +/** + * The root Domain on which all cookies should be set. (See: + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_where_cookies_are_sent) + * + * In production, this should be set to "graduatenu.com" which allows + * api.graduatenu.com to set cookies on every other *.graduatenu.com domain. + */ +export const COOKIE_DOMAIN = + process.env.NODE_ENV === "production" ? "graduatenu.com" : "localhost";