role based auth

implemented superadmin -> admin -> traniner
This commit is contained in:
dimitar committed 2026-03-18 06:06:01 +01:00
1 parent 16217f46ff
commit 624cdfc45c
16 files changed
+1105 -54

No files matched your search

+231
View File
@@ -0,0 +1,231 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { USER_ROLES, type UserRole } from "@fitai/shared";
import { getDatabase } from "../database";
export interface AuthContext {
userId: string;
role: UserRole;
gymId: string | null;
}
export interface AuthResult extends AuthContext {}
/**
* Get the full authentication context including gymId
* Combines Clerk session claims with database lookup for accurate gym assignment
*
* @returns AuthContext with userId, role, and gymId
*
* @example
* const { userId, role, gymId } = await getAuthContext();
* // userId: "user_abc123"
* // role: "admin"
* // gymId: "gym_xyz"
*/
export async function getAuthContext(): Promise<AuthContext> {
const { userId, sessionClaims } = await auth();
if (!userId) {
throw new Error("Unauthorized: No authenticated user");
}
// Get role from Clerk metadata
const role = (sessionClaims?.metadata as { role?: UserRole })?.role;
if (!role || !USER_ROLES.includes(role)) {
throw new Error(`Forbidden: Invalid or missing role - ${role}`);
}
// Get gymId from Clerk metadata or database
let gymId: string | null = null;
// First try Clerk metadata (faster path)
const clerkGymId = (sessionClaims?.metadata as { gymId?: string })?.gymId;
if (clerkGymId) {
gymId = clerkGymId;
} else {
// Fallback to database lookup
try {
const db = await getDatabase();
const user = await db.getUserById(userId);
gymId = user?.gymId ?? null;
} catch (error) {
console.error("Failed to get gymId from database:", error);
gymId = null;
}
}
return { userId, role, gymId };
}
/**
* Middleware to require authentication and optionally check user role
* Enhanced version that also retrieves gymId
*
* @param allowedRoles - Array of roles allowed to access the endpoint (optional)
* @returns Authentication result with userId, role, and gymId, or NextResponse error
*
* @example
* export async function DELETE(request: NextRequest) {
* const authResult = await requireAuth(["admin", "superAdmin"]);
* if (authResult instanceof NextResponse) return authResult;
* const { userId, role, gymId } = authResult;
* // ... proceed with authorized logic
* }
*/
export async function requireAuth(
allowedRoles?: UserRole[],
): Promise<AuthResult | NextResponse> {
try {
const context = await getAuthContext();
// Check if user has required role
if (allowedRoles && allowedRoles.length > 0) {
if (!allowedRoles.includes(context.role)) {
return NextResponse.json(
{
error: `Forbidden - Requires one of: ${allowedRoles.join(", ")}`,
requiredRoles: allowedRoles,
userRole: context.role,
},
{ status: 403 },
);
}
}
return context;
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message.includes("Unauthorized")) {
return NextResponse.json(
{ error: "Unauthorized - Authentication required" },
{ status: 401 },
);
}
if (message.includes("Forbidden")) {
return NextResponse.json({ error: message }, { status: 403 });
}
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 },
);
}
}
/**
* Require authentication with gym access validation
* Use this for endpoints that need to verify the user can access a specific gym
*
* @param allowedRoles - Roles allowed to access this endpoint
* @param requiredGymId - Gym ID that must be accessed (optional - uses user's gym if not provided)
* @returns AuthResult with full context, or NextResponse error
*
* @example
* // Admin accessing their own gym
* const result = await requireGymAccess(["admin"]);
*
* // SuperAdmin accessing specific gym
* const result = await requireGymAccess(["superAdmin"], "gym_123");
*/
export async function requireGymAccess(
allowedRoles: UserRole[],
requiredGymId?: string,
): Promise<AuthResult | NextResponse> {
const authResult = await requireAuth(allowedRoles);
if (authResult instanceof NextResponse) {
return authResult;
}
const { role, gymId: userGymId } = authResult;
// Determine target gym
const targetGymId = requiredGymId ?? userGymId;
// SuperAdmin can access any gym
if (role === "superAdmin") {
return { ...authResult, gymId: targetGymId };
}
// Other roles must have matching gym
if (!targetGymId) {
return NextResponse.json(
{ error: "Forbidden - User is not assigned to a gym" },
{ status: 403 },
);
}
if (userGymId !== targetGymId) {
return NextResponse.json(
{ error: "Forbidden - Cannot access other gym's data" },
{ status: 403 },
);
}
return { ...authResult, gymId: targetGymId };
}
/**
* Get the target gym ID from request for superAdmin context switching
* SuperAdmins can pass ?gymId to view specific gym data
*
* @param request - NextRequest with query params
* @param userRole - Current user's role
* @param userGymId - Current user's gym ID
* @returns Target gym ID or undefined for superAdmin viewing all
*
* @example
* const targetGymId = getTargetGymId(request, role, gymId);
* // For superAdmin with ?gymId=abc -> "abc"
* // For superAdmin without param -> undefined (all gyms)
* // For admin -> always returns their gymId
*/
export function getTargetGymId(
request: NextRequest,
userRole: UserRole,
userGymId: string | null,
): string | undefined {
// For superAdmin, allow gymId query param for context switching
if (userRole === "superAdmin") {
const queryGymId = request.nextUrl.searchParams.get("gymId");
return queryGymId ?? undefined;
}
// For other roles, they can only access their own gym
return userGymId ?? undefined;
}
/**
* Check if the authenticated user is trying to modify their own account
* Useful for preventing self-deletion or self-demotion
*/
export function isSelfModification(
userId: string,
targetUserId: string,
): boolean {
return userId === targetUserId;
}
/**
* Validate that an admin isn't demoting themselves or deleting their own account
*/
export function preventSelfModification(
userId: string,
targetUserId: string,
action: string,
): NextResponse | undefined {
if (isSelfModification(userId, targetUserId)) {
return NextResponse.json(
{
error: `Cannot ${action} your own account`,
hint: "Ask another administrator to perform this action",
},
{ status: 403 },
);
}
return undefined;
}
+249
View File
@@ -0,0 +1,249 @@
import type { UserRole } from "@fitai/shared";
import { NextResponse } from "next/server";
/**
* Check if a user can access data from a specific gym
*
* @param userRole - The role of the requesting user
* @param userGymId - The gym ID of the requesting user (null for superAdmin)
* @param targetGymId - The gym ID being accessed (undefined means all gyms)
* @returns true if access is allowed
*
* @example
* // SuperAdmin accessing any gym
* canAccessGym("superAdmin", null, "gym_123") // true
*
* // Admin accessing their own gym
* canAccessGym("admin", "gym_abc", "gym_abc") // true
*
* // Admin trying to access other gym
* canAccessGym("admin", "gym_abc", "gym_xyz") // false
*/
export function canAccessGym(
userRole: UserRole,
userGymId: string | null,
targetGymId: string | undefined,
): boolean {
// SuperAdmin can access any gym
if (userRole === "superAdmin") {
return true;
}
// If no target gym specified, allow access to own gym
if (targetGymId === undefined) {
return true;
}
// Non-superAdmins must have a gymId
if (!userGymId) {
return false;
}
// Must match the gym
return userGymId === targetGymId;
}
/**
* Check if a user can manage (create/update/delete) another user
* Based on role hierarchy and gym membership
*
* @param requesterRole - Role of the user making the request
* @param requesterGymId - Gym ID of the requesting user
* @param targetRole - Role of the user being managed
* @param targetGymId - Gym ID of the user being managed
* @returns true if management is allowed
*
* @example
* // SuperAdmin can manage anyone
* canManageUser("superAdmin", null, "admin", "gym_abc") // true
*
* // Admin can manage trainers and clients in their gym
* canManageUser("admin", "gym_abc", "trainer", "gym_abc") // true
* canManageUser("admin", "gym_abc", "client", "gym_abc") // true
*
* // Admin cannot manage users in other gyms
* canManageUser("admin", "gym_abc", "trainer", "gym_xyz") // false
*
* // Trainer can manage clients in their gym
* canManageUser("trainer", "gym_abc", "client", "gym_abc") // true
*/
export function canManageUser(
requesterRole: UserRole,
requesterGymId: string | null,
targetRole: UserRole,
targetGymId: string | null,
): boolean {
// SuperAdmin can manage anyone
if (requesterRole === "superAdmin") {
return true;
}
// Role hierarchy: admin > trainer > client
const roleHierarchy: Record<UserRole, number> = {
superAdmin: 4,
admin: 3,
trainer: 2,
client: 1,
};
const requesterLevel = roleHierarchy[requesterRole];
const targetLevel = roleHierarchy[targetRole];
// Cannot manage users at same or higher level
if (requesterLevel <= targetLevel) {
return false;
}
// Must have gym access
if (!requesterGymId) {
return false;
}
// For admin/trainer, target must be in same gym
if (requesterRole === "admin" || requesterRole === "trainer") {
return requesterGymId === targetGymId;
}
return false;
}
/**
* Check if a trainer can access a specific client's data
* Trainer must be assigned to that client via trainerClients table
*
* @param trainerGymId - Gym ID of the trainer
* @param clientGymId - Gym ID of the client
* @returns true if in same gym
*
* @note In a more complex system, this would query trainerClients table
* For now, we use gym-based access (trainer and client in same gym)
*/
export function canTrainerAccessClient(
trainerGymId: string | null,
clientGymId: string | null,
): boolean {
if (!trainerGymId || !clientGymId) {
return false;
}
return trainerGymId === clientGymId;
}
/**
* Get the roles that a specific role can invite
* Based on role hierarchy
*
* @param role - The role wanting to invite
* @returns Array of roles that can be invited
*
* @example
* getInvitableRoles("superAdmin") // ["admin", "trainer", "client"]
* getInvitableRoles("admin") // ["trainer", "client"]
* getInvitableRoles("trainer") // ["client"]
* getInvitableRoles("client") // []
*/
export function getInvitableRoles(role: UserRole): UserRole[] {
const invitationRules: Record<UserRole, UserRole[]> = {
superAdmin: ["admin", "trainer", "client"],
admin: ["trainer", "client"],
trainer: ["client"],
client: [],
};
return invitationRules[role] ?? [];
}
/**
* Validate gym access and return error response if denied
* Use this in API routes to enforce gym-based access control
*
* @param request - NextRequest for getting query params
* @param userRole - Current user's role
* @param userGymId - Current user's gym ID
* @param targetGymId - Gym being accessed (optional)
* @returns NextResponse if denied, undefined if allowed
*
* @example
* export async function GET(request: NextRequest) {
* const error = await validateGymAccess(request, role, gymId);
* if (error) return error;
* // ... proceed
* }
*/
export function validateGymAccess(
userRole: UserRole,
userGymId: string | null,
targetGymId?: string,
): NextResponse | undefined {
if (!canAccessGym(userRole, userGymId, targetGymId)) {
return NextResponse.json(
{ error: "Forbidden - Cannot access this gym's data" },
{ status: 403 },
);
}
return undefined;
}
/**
* Get filter condition for gym-scoped queries
* Returns appropriate filter based on user role
*
* @param userRole - Current user's role
* @param userGymId - Current user's gym ID
* @returns Filter object or undefined (no filter = all gyms)
*
* @example
* // For superAdmin: returns undefined (no filter)
* getGymFilter("superAdmin", null) // undefined
*
* // For admin: returns { gymId: "gym_abc" }
* getGymFilter("admin", "gym_abc") // { gymId: "gym_abc" }
*/
export function getGymFilter(
userRole: UserRole,
userGymId: string | null,
): { gymId: string } | undefined {
// SuperAdmin sees all gyms
if (userRole === "superAdmin") {
return undefined;
}
// Other roles filtered by their gym
if (userGymId) {
return { gymId: userGymId };
}
// No gym assigned - return filter that matches nothing
return { gymId: "" };
}
/**
* Get all gym IDs a user can access
* SuperAdmin gets all gyms, others get only their own
*
* @param userRole - Current user's role
* @param userGymId - Current user's gym ID
* @param allGymIds - List of all gym IDs in system (for superAdmin)
* @returns Array of accessible gym IDs
*
* @example
* getAccessibleGymIds("admin", "gym_abc", ["gym_abc", "gym_xyz"])
* // Returns: ["gym_abc"]
*
* getAccessibleGymIds("superAdmin", null, ["gym_abc", "gym_xyz"])
* // Returns: ["gym_abc", "gym_xyz"]
*/
export function getAccessibleGymIds(
userRole: UserRole,
userGymId: string | null,
allGymIds: string[],
): string[] {
if (userRole === "superAdmin") {
return allGymIds;
}
if (userGymId) {
return [userGymId];
}
return [];
}