debug(auth): log session cookie source
This commit is contained in:
@@ -1,10 +1,18 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from "@nestjs/common";
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
UnauthorizedException,
|
||||
Logger,
|
||||
} from "@nestjs/common";
|
||||
import { AuthService } from "../auth.service";
|
||||
import type { AuthUser } from "@mosaic/shared";
|
||||
import type { MaybeAuthenticatedRequest } from "../types/better-auth-request.interface";
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(AuthGuard.name);
|
||||
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
@@ -59,7 +67,8 @@ export class AuthGuard implements CanActivate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract token from cookie (BetterAuth stores session token in better-auth.session_token cookie)
|
||||
* Extract token from cookie.
|
||||
* BetterAuth may prefix the cookie name with "__Secure-" when running on HTTPS.
|
||||
*/
|
||||
private extractTokenFromCookie(request: MaybeAuthenticatedRequest): string | undefined {
|
||||
// Express types `cookies` as `any`; cast to a known shape for type safety.
|
||||
@@ -68,8 +77,23 @@ export class AuthGuard implements CanActivate {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// BetterAuth uses 'better-auth.session_token' as the cookie name by default
|
||||
return cookies["better-auth.session_token"];
|
||||
// BetterAuth default cookie name is "better-auth.session_token"
|
||||
// When Secure cookies are enabled, BetterAuth prefixes with "__Secure-".
|
||||
const candidates = [
|
||||
"__Secure-better-auth.session_token",
|
||||
"better-auth.session_token",
|
||||
"__Host-better-auth.session_token",
|
||||
] as const;
|
||||
|
||||
for (const name of candidates) {
|
||||
const token = cookies[name];
|
||||
if (token) {
|
||||
this.logger.debug(`Session cookie found: ${name}`);
|
||||
return token;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user