From e635fff587719777cd162cb78d5e839af62f0a8c Mon Sep 17 00:00:00 2001 From: anteqkois Date: Sun, 26 May 2024 17:51:16 +0200 Subject: [PATCH] fix(auth): change cookies logic --- apps/web/middleware.ts | 4 +++- .../src/modules/users/auth/auth.controller.ts | 15 ++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index 5fb3eff5..54edb024 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -5,8 +5,10 @@ import { NextRequest, NextResponse } from 'next/server' export function middleware(req: NextRequest) { const authStatus = req.cookies.get(Cookies.AUTH_STATUS) const accessToken = req.cookies.get(Cookies.ACCESS_TOKEN) - if (!authStatus || !accessToken || authStatus.value !== AuthStatus.AUTHENTICATED) + if (!authStatus || !accessToken || authStatus.value !== AuthStatus.AUTHENTICATED) { + console.log('Unauthorized request', req.nextUrl.pathname, req.url) return NextResponse.redirect(new URL(`/login?from=${req.nextUrl.pathname}`, req.url)) + } return NextResponse.next() } diff --git a/libs/nest-core/src/modules/users/auth/auth.controller.ts b/libs/nest-core/src/modules/users/auth/auth.controller.ts index 58686a76..8df6435e 100644 --- a/libs/nest-core/src/modules/users/auth/auth.controller.ts +++ b/libs/nest-core/src/modules/users/auth/auth.controller.ts @@ -29,15 +29,19 @@ export class AuthController { async signup(@BodySchema(signUpInputSchema) body: SignUpInput, @Response({ passthrough: true }) res: FastifyReply): Promise { const { access_token, user: userRes } = await this.authService.signUp(body) const expireDateUnix = +this.configService.get('JWT_ACCES_TOKEN_EXPIRE_SSECONDS', 3600) + const domain = this.configService.getOrThrow('DOMAIN') res.setCookie(Cookies.ACCESS_TOKEN, access_token, { path: '/', + domain, httpOnly: true, secure: false, - sameSite: 'lax', + // sameSite: 'lax', + sameSite: 'none', expires: new Date(Date.now() + 1000 * expireDateUnix), }) res.setCookie(Cookies.AUTH_STATUS, AuthStatus.AUTHENTICATED, { + domain, path: '/', }) @@ -55,15 +59,19 @@ export class AuthController { const { access_token, user: userRes } = await this.authService.login(user) const expireDateUnix = +this.configService.get('JWT_ACCES_TOKEN_EXPIRE_SSECONDS', 3600) + const domain = this.configService.getOrThrow('DOMAIN') res.setCookie(Cookies.ACCESS_TOKEN, access_token, { path: '/', + domain, httpOnly: true, secure: false, - sameSite: 'lax', + // sameSite: 'lax', + sameSite: 'none', expires: new Date(Date.now() + 1000 * expireDateUnix), }) res.setCookie(Cookies.AUTH_STATUS, AuthStatus.AUTHENTICATED, { + domain, path: '/', }) @@ -107,7 +115,8 @@ export class AuthController { // res.setCookie('access_token', access_token, { // httpOnly: true, // secure: false, - // sameSite: 'lax', + // sameSite: 'lax', + // none: 'lax', // expires: new Date(Date.now() + expireDateUnix), // }) // return res.send({ user: userRes, status: 'ok' })