feat(#193): Align authentication mechanism between API and web client
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
- Update AuthUser type in @mosaic/shared to include workspace fields - Update AuthGuard to support both cookie-based and Bearer token authentication - Add /auth/session endpoint for session validation - Install and configure cookie-parser middleware - Update CurrentUser decorator to use shared AuthUser type - Update tests for cookie and token authentication (20 tests passing) This ensures consistent authentication handling across API and web client, with proper type safety and support for both web browsers (cookies) and API clients (Bearer tokens). Fixes #193 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -53,6 +53,7 @@
|
||||
"bullmq": "^5.67.2",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.3",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"discord.js": "^14.25.1",
|
||||
"gray-matter": "^4.0.3",
|
||||
"highlight.js": "^11.11.1",
|
||||
@@ -78,6 +79,7 @@
|
||||
"@swc/core": "^1.10.18",
|
||||
"@types/adm-zip": "^0.5.7",
|
||||
"@types/archiver": "^7.0.0",
|
||||
"@types/cookie-parser": "^1.4.10",
|
||||
"@types/express": "^5.0.1",
|
||||
"@types/highlight.js": "^10.1.0",
|
||||
"@types/node": "^22.13.4",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import type { AuthUser } from "@mosaic/shared";
|
||||
import type { AuthUser, AuthSession } from "@mosaic/shared";
|
||||
import { AuthController } from "./auth.controller";
|
||||
import { AuthService } from "./auth.service";
|
||||
|
||||
@@ -39,15 +39,100 @@ describe("AuthController", () => {
|
||||
url: "/auth/session",
|
||||
};
|
||||
|
||||
await controller.handleAuth(mockRequest);
|
||||
await controller.handleAuth(mockRequest as unknown as Request);
|
||||
|
||||
expect(mockAuthService.getAuth).toHaveBeenCalled();
|
||||
expect(mockHandler).toHaveBeenCalledWith(mockRequest);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSession", () => {
|
||||
it("should return user and session data", () => {
|
||||
const mockUser: AuthUser = {
|
||||
id: "user-123",
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
workspaceId: "workspace-123",
|
||||
};
|
||||
|
||||
const mockSession = {
|
||||
id: "session-123",
|
||||
token: "session-token",
|
||||
expiresAt: new Date(Date.now() + 86400000),
|
||||
};
|
||||
|
||||
const mockRequest = {
|
||||
user: mockUser,
|
||||
session: mockSession,
|
||||
};
|
||||
|
||||
const result = controller.getSession(mockRequest);
|
||||
|
||||
const expected: AuthSession = {
|
||||
user: mockUser,
|
||||
session: {
|
||||
id: mockSession.id,
|
||||
token: mockSession.token,
|
||||
expiresAt: mockSession.expiresAt,
|
||||
},
|
||||
};
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should throw error if user not found in request", () => {
|
||||
const mockRequest = {
|
||||
session: {
|
||||
id: "session-123",
|
||||
token: "session-token",
|
||||
expiresAt: new Date(),
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => controller.getSession(mockRequest)).toThrow("User session not found");
|
||||
});
|
||||
|
||||
it("should throw error if session not found in request", () => {
|
||||
const mockRequest = {
|
||||
user: {
|
||||
id: "user-123",
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => controller.getSession(mockRequest)).toThrow("User session not found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProfile", () => {
|
||||
it("should return user profile", () => {
|
||||
it("should return complete user profile with workspace fields", () => {
|
||||
const mockUser: AuthUser = {
|
||||
id: "user-123",
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
image: "https://example.com/avatar.jpg",
|
||||
emailVerified: true,
|
||||
workspaceId: "workspace-123",
|
||||
currentWorkspaceId: "workspace-456",
|
||||
workspaceRole: "admin",
|
||||
};
|
||||
|
||||
const result = controller.getProfile(mockUser);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: mockUser.id,
|
||||
email: mockUser.email,
|
||||
name: mockUser.name,
|
||||
image: mockUser.image,
|
||||
emailVerified: mockUser.emailVerified,
|
||||
workspaceId: mockUser.workspaceId,
|
||||
currentWorkspaceId: mockUser.currentWorkspaceId,
|
||||
workspaceRole: mockUser.workspaceRole,
|
||||
});
|
||||
});
|
||||
|
||||
it("should return user profile with optional fields undefined", () => {
|
||||
const mockUser: AuthUser = {
|
||||
id: "user-123",
|
||||
email: "test@example.com",
|
||||
@@ -60,6 +145,11 @@ describe("AuthController", () => {
|
||||
id: mockUser.id,
|
||||
email: mockUser.email,
|
||||
name: mockUser.name,
|
||||
image: undefined,
|
||||
emailVerified: undefined,
|
||||
workspaceId: undefined,
|
||||
currentWorkspaceId: undefined,
|
||||
workspaceRole: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,25 +1,84 @@
|
||||
import { Controller, All, Req, Get, UseGuards } from "@nestjs/common";
|
||||
import type { AuthUser } from "@mosaic/shared";
|
||||
import { Controller, All, Req, Get, UseGuards, Request } from "@nestjs/common";
|
||||
import type { AuthUser, AuthSession } from "@mosaic/shared";
|
||||
import { AuthService } from "./auth.service";
|
||||
import { AuthGuard } from "./guards/auth.guard";
|
||||
import { CurrentUser } from "./decorators/current-user.decorator";
|
||||
|
||||
interface RequestWithSession {
|
||||
user?: AuthUser;
|
||||
session?: {
|
||||
id: string;
|
||||
token: string;
|
||||
expiresAt: Date;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
@Controller("auth")
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
/**
|
||||
* Get current session
|
||||
* Returns user and session data for authenticated user
|
||||
*/
|
||||
@Get("session")
|
||||
@UseGuards(AuthGuard)
|
||||
getSession(@Request() req: RequestWithSession): AuthSession {
|
||||
if (!req.user || !req.session) {
|
||||
// This should never happen after AuthGuard, but TypeScript needs the check
|
||||
throw new Error("User session not found");
|
||||
}
|
||||
|
||||
return {
|
||||
user: req.user,
|
||||
session: {
|
||||
id: req.session.id,
|
||||
token: req.session.token,
|
||||
expiresAt: req.session.expiresAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user profile
|
||||
* Returns basic user information
|
||||
*/
|
||||
@Get("profile")
|
||||
@UseGuards(AuthGuard)
|
||||
getProfile(@CurrentUser() user: AuthUser) {
|
||||
return {
|
||||
getProfile(@CurrentUser() user: AuthUser): AuthUser {
|
||||
// Return only defined properties to maintain type safety
|
||||
const profile: AuthUser = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
};
|
||||
|
||||
if (user.image !== undefined) {
|
||||
profile.image = user.image;
|
||||
}
|
||||
if (user.emailVerified !== undefined) {
|
||||
profile.emailVerified = user.emailVerified;
|
||||
}
|
||||
if (user.workspaceId !== undefined) {
|
||||
profile.workspaceId = user.workspaceId;
|
||||
}
|
||||
if (user.currentWorkspaceId !== undefined) {
|
||||
profile.currentWorkspaceId = user.currentWorkspaceId;
|
||||
}
|
||||
if (user.workspaceRole !== undefined) {
|
||||
profile.workspaceRole = user.workspaceRole;
|
||||
}
|
||||
|
||||
return profile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle all other auth routes (sign-in, sign-up, sign-out, etc.)
|
||||
* Delegates to BetterAuth
|
||||
*/
|
||||
@All("*")
|
||||
async handleAuth(@Req() req: Request) {
|
||||
async handleAuth(@Req() req: Request): Promise<unknown> {
|
||||
const auth = this.authService.getAuth();
|
||||
return auth.handler(req);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import type { ExecutionContext } from "@nestjs/common";
|
||||
import { createParamDecorator } from "@nestjs/common";
|
||||
import type { AuthenticatedRequest, AuthenticatedUser } from "../../common/types/user.types";
|
||||
import type { AuthUser } from "@mosaic/shared";
|
||||
|
||||
interface RequestWithUser {
|
||||
user?: AuthUser;
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): AuthenticatedUser | undefined => {
|
||||
const request = ctx.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
(_data: unknown, ctx: ExecutionContext): AuthUser | undefined => {
|
||||
const request = ctx.switchToHttp().getRequest<RequestWithUser>();
|
||||
return request.user;
|
||||
}
|
||||
);
|
||||
|
||||
@@ -29,9 +29,13 @@ describe("AuthGuard", () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const createMockExecutionContext = (headers: any = {}): ExecutionContext => {
|
||||
const createMockExecutionContext = (
|
||||
headers: Record<string, string> = {},
|
||||
cookies: Record<string, string> = {}
|
||||
): ExecutionContext => {
|
||||
const mockRequest = {
|
||||
headers,
|
||||
cookies,
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -42,57 +46,139 @@ describe("AuthGuard", () => {
|
||||
};
|
||||
|
||||
describe("canActivate", () => {
|
||||
it("should return true for valid session", async () => {
|
||||
const mockSessionData = {
|
||||
user: {
|
||||
id: "user-123",
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
},
|
||||
session: {
|
||||
id: "session-123",
|
||||
},
|
||||
};
|
||||
const mockSessionData = {
|
||||
user: {
|
||||
id: "user-123",
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
},
|
||||
session: {
|
||||
id: "session-123",
|
||||
token: "session-token",
|
||||
expiresAt: new Date(Date.now() + 86400000),
|
||||
},
|
||||
};
|
||||
|
||||
mockAuthService.verifySession.mockResolvedValue(mockSessionData);
|
||||
describe("Bearer token authentication", () => {
|
||||
it("should return true for valid Bearer token", async () => {
|
||||
mockAuthService.verifySession.mockResolvedValue(mockSessionData);
|
||||
|
||||
const context = createMockExecutionContext({
|
||||
authorization: "Bearer valid-token",
|
||||
const context = createMockExecutionContext({
|
||||
authorization: "Bearer valid-token",
|
||||
});
|
||||
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockAuthService.verifySession).toHaveBeenCalledWith("valid-token");
|
||||
});
|
||||
|
||||
const result = await guard.canActivate(context);
|
||||
it("should throw UnauthorizedException for invalid Bearer token", async () => {
|
||||
mockAuthService.verifySession.mockResolvedValue(null);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockAuthService.verifySession).toHaveBeenCalledWith("valid-token");
|
||||
const context = createMockExecutionContext({
|
||||
authorization: "Bearer invalid-token",
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow("Invalid or expired session");
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw UnauthorizedException if no token provided", async () => {
|
||||
const context = createMockExecutionContext({});
|
||||
describe("Cookie-based authentication", () => {
|
||||
it("should return true for valid session cookie", async () => {
|
||||
mockAuthService.verifySession.mockResolvedValue(mockSessionData);
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow("No authentication token provided");
|
||||
});
|
||||
const context = createMockExecutionContext(
|
||||
{},
|
||||
{
|
||||
"better-auth.session_token": "cookie-token",
|
||||
}
|
||||
);
|
||||
|
||||
it("should throw UnauthorizedException if session is invalid", async () => {
|
||||
mockAuthService.verifySession.mockResolvedValue(null);
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
const context = createMockExecutionContext({
|
||||
authorization: "Bearer invalid-token",
|
||||
expect(result).toBe(true);
|
||||
expect(mockAuthService.verifySession).toHaveBeenCalledWith("cookie-token");
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow("Invalid or expired session");
|
||||
});
|
||||
it("should prefer cookie over Bearer token when both present", async () => {
|
||||
mockAuthService.verifySession.mockResolvedValue(mockSessionData);
|
||||
|
||||
it("should throw UnauthorizedException if session verification fails", async () => {
|
||||
mockAuthService.verifySession.mockRejectedValue(new Error("Verification failed"));
|
||||
const context = createMockExecutionContext(
|
||||
{
|
||||
authorization: "Bearer bearer-token",
|
||||
},
|
||||
{
|
||||
"better-auth.session_token": "cookie-token",
|
||||
}
|
||||
);
|
||||
|
||||
const context = createMockExecutionContext({
|
||||
authorization: "Bearer error-token",
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockAuthService.verifySession).toHaveBeenCalledWith("cookie-token");
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow("Authentication failed");
|
||||
it("should fallback to Bearer token if no cookie", async () => {
|
||||
mockAuthService.verifySession.mockResolvedValue(mockSessionData);
|
||||
|
||||
const context = createMockExecutionContext(
|
||||
{
|
||||
authorization: "Bearer bearer-token",
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockAuthService.verifySession).toHaveBeenCalledWith("bearer-token");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error handling", () => {
|
||||
it("should throw UnauthorizedException if no token provided", async () => {
|
||||
const context = createMockExecutionContext({}, {});
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
"No authentication token provided"
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw UnauthorizedException if session verification fails", async () => {
|
||||
mockAuthService.verifySession.mockRejectedValue(new Error("Verification failed"));
|
||||
|
||||
const context = createMockExecutionContext({
|
||||
authorization: "Bearer error-token",
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow("Authentication failed");
|
||||
});
|
||||
|
||||
it("should attach user and session to request on success", async () => {
|
||||
mockAuthService.verifySession.mockResolvedValue(mockSessionData);
|
||||
|
||||
const mockRequest = {
|
||||
headers: {
|
||||
authorization: "Bearer valid-token",
|
||||
},
|
||||
cookies: {},
|
||||
};
|
||||
|
||||
const context = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => mockRequest,
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
|
||||
await guard.canActivate(context);
|
||||
|
||||
expect(mockRequest).toHaveProperty("user", mockSessionData.user);
|
||||
expect(mockRequest).toHaveProperty("session", mockSessionData.session);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from "@nestjs/common";
|
||||
import { AuthService } from "../auth.service";
|
||||
import type { AuthenticatedRequest } from "../../common/types/user.types";
|
||||
import type { AuthUser } from "@mosaic/shared";
|
||||
|
||||
/**
|
||||
* Request type with authentication context
|
||||
*/
|
||||
interface AuthRequest {
|
||||
user?: AuthUser;
|
||||
session?: Record<string, unknown>;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
cookies?: Record<string, string>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
const request = context.switchToHttp().getRequest<AuthRequest>();
|
||||
|
||||
// Try to get token from either cookie (preferred) or Authorization header
|
||||
const token = this.extractToken(request);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException("No authentication token provided");
|
||||
@@ -21,12 +33,13 @@ export class AuthGuard implements CanActivate {
|
||||
throw new UnauthorizedException("Invalid or expired session");
|
||||
}
|
||||
|
||||
// Attach user to request (with type assertion for session data structure)
|
||||
const user = sessionData.user as unknown as AuthenticatedRequest["user"];
|
||||
if (!user) {
|
||||
// Attach user and session to request
|
||||
const user = sessionData.user;
|
||||
// Validate user has required fields
|
||||
if (typeof user !== "object" || !("id" in user) || !("email" in user) || !("name" in user)) {
|
||||
throw new UnauthorizedException("Invalid user data in session");
|
||||
}
|
||||
request.user = user;
|
||||
request.user = user as unknown as AuthUser;
|
||||
request.session = sessionData.session;
|
||||
|
||||
return true;
|
||||
@@ -39,7 +52,36 @@ export class AuthGuard implements CanActivate {
|
||||
}
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request: AuthenticatedRequest): string | undefined {
|
||||
/**
|
||||
* Extract token from cookie (preferred) or Authorization header
|
||||
*/
|
||||
private extractToken(request: AuthRequest): string | undefined {
|
||||
// Try cookie first (BetterAuth default)
|
||||
const cookieToken = this.extractTokenFromCookie(request);
|
||||
if (cookieToken) {
|
||||
return cookieToken;
|
||||
}
|
||||
|
||||
// Fallback to Authorization header for API clients
|
||||
return this.extractTokenFromHeader(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract token from cookie (BetterAuth stores session token in better-auth.session_token cookie)
|
||||
*/
|
||||
private extractTokenFromCookie(request: AuthRequest): string | undefined {
|
||||
if (!request.cookies) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// BetterAuth uses 'better-auth.session_token' as the cookie name by default
|
||||
return request.cookies["better-auth.session_token"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract token from Authorization header (Bearer token)
|
||||
*/
|
||||
private extractTokenFromHeader(request: AuthRequest): string | undefined {
|
||||
const authHeader = request.headers.authorization;
|
||||
if (typeof authHeader !== "string") {
|
||||
return undefined;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NestFactory } from "@nestjs/core";
|
||||
import { ValidationPipe } from "@nestjs/common";
|
||||
import cookieParser from "cookie-parser";
|
||||
import { AppModule } from "./app.module";
|
||||
import { GlobalExceptionFilter } from "./filters/global-exception.filter";
|
||||
|
||||
@@ -28,6 +29,9 @@ function getPort(): number {
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
|
||||
// Enable cookie parser for session handling
|
||||
app.use(cookieParser());
|
||||
|
||||
// Enable global validation pipe with transformation
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
|
||||
Reference in New Issue
Block a user