clerkauth

implemented, sync with db to be added
This commit is contained in:
dimitar committed 2025-11-10 04:16:31 +01:00
1 parent ca790a7b97
commit 3a58d420d6
49 files changed
+9423 -779

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
# Clerk Authentication
# Get these values from https://dashboard.clerk.com
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_bmVlZGVkLWVsZXBoYW50LTY0LmNsZXJrLmFjY291bnRzLmRldiQ
CLERK_SECRET_KEY=sk_test_qnWnZSem1ZkodRip9NZDXszDnCP91HwlNwtAUAcHZ1
# Clerk URLs (customize these for your app)
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/
# Database
DATABASE_URL=./data/fitai.db
+18
View File
@@ -0,0 +1,18 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/app/globals.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib",
"ui": "@/components/ui"
}
}
Binary file not shown.
+194 -3
View File
@@ -8,6 +8,7 @@
"name": "@fitai/admin",
"version": "1.0.0",
"dependencies": {
"@clerk/nextjs": "^6.34.5",
"@fitai/shared": "file:../../packages/shared",
"@hookform/resolvers": "^5.2.2",
"@tailwindcss/postcss": "^4.1.17",
@@ -30,6 +31,7 @@
"recharts": "^3.3.0",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
"svix": "^1.81.0",
"tailwindcss": "^4.1.17",
"zod": "^4.1.12"
},
@@ -600,6 +602,103 @@
"dev": true,
"license": "MIT"
},
"node_modules/@clerk/backend": {
"version": "2.20.0",
"resolved": "https://registry.npmjs.org/@clerk/backend/-/backend-2.20.0.tgz",
"integrity": "sha512-RcZN7CAxGkkLydGtWpxCyq4C0pSo/1ch0LJMDQnckrt10Jx8mAjwce2nZQa2xRykxsOla4+boF9a5kDw3nUvVg==",
"license": "MIT",
"dependencies": {
"@clerk/shared": "^3.31.1",
"@clerk/types": "^4.97.2",
"cookie": "1.0.2",
"standardwebhooks": "^1.0.0",
"tslib": "2.8.1"
},
"engines": {
"node": ">=18.17.0"
}
},
"node_modules/@clerk/clerk-react": {
"version": "5.53.8",
"resolved": "https://registry.npmjs.org/@clerk/clerk-react/-/clerk-react-5.53.8.tgz",
"integrity": "sha512-TOiYk31rQUL9JOKZr/fhajf+fQCHicy1J4Rxq7vqtjHseJsnIBjzTigjOap/w8PrDAF28O6dbPC5CA0Tp7Md8w==",
"license": "MIT",
"dependencies": {
"@clerk/shared": "^3.31.1",
"tslib": "2.8.1"
},
"engines": {
"node": ">=18.17.0"
},
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0 || ^19.0.0-0",
"react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-0"
}
},
"node_modules/@clerk/nextjs": {
"version": "6.34.5",
"resolved": "https://registry.npmjs.org/@clerk/nextjs/-/nextjs-6.34.5.tgz",
"integrity": "sha512-f1OyucHc5HHBZovzEtJrPR0MUePZxEH2mqu3dt24iGTWTmV2UPnHMB5uSi4XVSWcungnzHWKgTKnHKTVF3vxUA==",
"license": "MIT",
"dependencies": {
"@clerk/backend": "^2.20.0",
"@clerk/clerk-react": "^5.53.8",
"@clerk/shared": "^3.31.1",
"@clerk/types": "^4.97.2",
"server-only": "0.0.1",
"tslib": "2.8.1"
},
"engines": {
"node": ">=18.17.0"
},
"peerDependencies": {
"next": "^13.5.7 || ^14.2.25 || ^15.2.3 || ^16",
"react": "^18.0.0 || ^19.0.0 || ^19.0.0-0",
"react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-0"
}
},
"node_modules/@clerk/shared": {
"version": "3.31.1",
"resolved": "https://registry.npmjs.org/@clerk/shared/-/shared-3.31.1.tgz",
"integrity": "sha512-mqxZqlzLJYJxA+ryLzhwFR0eO73teAvRd+wvA8bLUZLYvCRFvaiHsB9dEvbo9Z5bMYdq3NPwnx2uljMuu/tiQw==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"csstype": "3.1.3",
"dequal": "2.0.3",
"glob-to-regexp": "0.4.1",
"js-cookie": "3.0.5",
"std-env": "^3.9.0",
"swr": "2.3.4"
},
"engines": {
"node": ">=18.17.0"
},
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0 || ^19.0.0-0",
"react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-dom": {
"optional": true
}
}
},
"node_modules/@clerk/types": {
"version": "4.97.2",
"resolved": "https://registry.npmjs.org/@clerk/types/-/types-4.97.2.tgz",
"integrity": "sha512-xnJq3xzpmuuDnNnWuUMKJLPPkaEaLDM0kiv2Hm0gKIcL1+1P3VaGf2vL9roIhmhLswB2PUwtVvZKBmGjT5yOVw==",
"license": "MIT",
"dependencies": {
"@clerk/shared": "^3.31.1"
},
"engines": {
"node": ">=18.17.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.7.0.tgz",
@@ -2203,6 +2302,12 @@
"@sinonjs/commons": "^3.0.1"
}
},
"node_modules/@stablelib/base64": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
"license": "MIT"
},
"node_modules/@standard-schema/spec": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",
@@ -4607,6 +4712,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
"integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -4633,7 +4747,6 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
@@ -4954,9 +5067,7 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6"
}
@@ -5933,6 +6044,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/fast-sha256": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
"license": "Unlicense"
},
"node_modules/fastq": {
"version": "1.19.1",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
@@ -6414,6 +6531,12 @@
"node": ">=10.13.0"
}
},
"node_modules/glob-to-regexp": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
"integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
"license": "BSD-2-Clause"
},
"node_modules/glob/node_modules/brace-expansion": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
@@ -8333,6 +8456,15 @@
"jiti": "lib/jiti-cli.mjs"
}
},
"node_modules/js-cookie": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
"license": "MIT",
"engines": {
"node": ">=14"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -10652,6 +10784,12 @@
"node": ">=10"
}
},
"node_modules/server-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/server-only/-/server-only-0.0.1.tgz",
"integrity": "sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==",
"license": "MIT"
},
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
@@ -11091,6 +11229,22 @@
"node": ">=8"
}
},
"node_modules/standardwebhooks": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz",
"integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==",
"license": "MIT",
"dependencies": {
"@stablelib/base64": "^1.0.0",
"fast-sha256": "^1.3.0"
}
},
"node_modules/std-env": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
"license": "MIT"
},
"node_modules/stop-iteration-iterator": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",
@@ -11433,6 +11587,30 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/svix": {
"version": "1.81.0",
"resolved": "https://registry.npmjs.org/svix/-/svix-1.81.0.tgz",
"integrity": "sha512-Q4DiYb1ydhRYqez65vZES8AkGY2oxn26qP7mLVbMf8Orrveb54TZLkaVG5zr7eJT4T3zYRThkKf6aOnvzgwhYw==",
"license": "MIT",
"dependencies": {
"@stablelib/base64": "^1.0.0",
"fast-sha256": "^1.3.0",
"uuid": "^10.0.0"
}
},
"node_modules/swr": {
"version": "2.3.4",
"resolved": "https://registry.npmjs.org/swr/-/swr-2.3.4.tgz",
"integrity": "sha512-bYd2lrhc+VarcpkgWclcUi92wYCpOgMws9Sd1hG1ntAu0NEy+14CbotuFjshBU2kt9rYj9TSmDcybpxpeTU1fg==",
"license": "MIT",
"dependencies": {
"dequal": "^2.0.3",
"use-sync-external-store": "^1.4.0"
},
"peerDependencies": {
"react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/synckit": {
"version": "0.11.11",
"resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.11.tgz",
@@ -12000,6 +12178,19 @@
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/v8-to-istanbul": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz",
+2
View File
@@ -11,6 +11,7 @@
"test": "jest"
},
"dependencies": {
"@clerk/nextjs": "^6.34.5",
"@fitai/shared": "file:../../packages/shared",
"@hookform/resolvers": "^5.2.2",
"@tailwindcss/postcss": "^4.1.17",
@@ -33,6 +34,7 @@
"recharts": "^3.3.0",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
"svix": "^1.81.0",
"tailwindcss": "^4.1.17",
"zod": "^4.1.12"
},
@@ -0,0 +1,77 @@
import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
import { setUserRole, isAdmin, type UserRole } from '@/lib/clerk-helpers';
export async function POST(req: Request) {
try {
// Authenticate the request
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Check if the requesting user is an admin
const requestingUserIsAdmin = await isAdmin(userId);
if (!requestingUserIsAdmin) {
return NextResponse.json(
{ error: 'Forbidden: Admin access required' },
{ status: 403 }
);
}
// Parse request body
const body = await req.json();
const { targetUserId, role } = body;
// Validate inputs
if (!targetUserId || typeof targetUserId !== 'string') {
return NextResponse.json(
{ error: 'Invalid or missing targetUserId' },
{ status: 400 }
);
}
if (!role || !['admin', 'trainer', 'client'].includes(role)) {
return NextResponse.json(
{ error: 'Invalid role. Must be admin, trainer, or client' },
{ status: 400 }
);
}
// Prevent admin from changing their own role
if (userId === targetUserId) {
return NextResponse.json(
{ error: 'Cannot change your own role' },
{ status: 400 }
);
}
// Set the user's role
const updatedUser = await setUserRole(targetUserId, role as UserRole);
return NextResponse.json({
success: true,
message: `User role updated to ${role}`,
user: {
id: updatedUser.id,
email: updatedUser.emailAddresses[0]?.emailAddress,
firstName: updatedUser.firstName,
lastName: updatedUser.lastName,
role: updatedUser.publicMetadata.role,
},
});
} catch (error) {
console.error('Error setting user role:', error);
if (error instanceof Error && error.message.includes('not found')) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
+147
View File
@@ -0,0 +1,147 @@
import { Webhook } from 'svix';
import { headers } from 'next/headers';
import { WebhookEvent } from '@clerk/nextjs/server';
import { db } from '@fitai/database';
import { users } from '@fitai/database/schema';
import { eq } from 'drizzle-orm';
export async function POST(req: Request) {
// Get the webhook secret from environment variables
const WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET;
if (!WEBHOOK_SECRET) {
throw new Error('Please add CLERK_WEBHOOK_SECRET to your environment variables');
}
// Get the headers
const headerPayload = await headers();
const svix_id = headerPayload.get('svix-id');
const svix_timestamp = headerPayload.get('svix-timestamp');
const svix_signature = headerPayload.get('svix-signature');
// If there are no headers, error out
if (!svix_id || !svix_timestamp || !svix_signature) {
return new Response('Error: Missing svix headers', {
status: 400,
});
}
// Get the body
const payload = await req.json();
const body = JSON.stringify(payload);
// Create a new Svix instance with your webhook secret
const wh = new Webhook(WEBHOOK_SECRET);
let evt: WebhookEvent;
// Verify the webhook signature
try {
evt = wh.verify(body, {
'svix-id': svix_id,
'svix-timestamp': svix_timestamp,
'svix-signature': svix_signature,
}) as WebhookEvent;
} catch (err) {
console.error('Error verifying webhook:', err);
return new Response('Error: Verification failed', {
status: 400,
});
}
// Handle the webhook
const eventType = evt.type;
console.log(`Received webhook with ID ${evt.data.id} and type ${eventType}`);
try {
switch (eventType) {
case 'user.created': {
const { id, email_addresses, first_name, last_name, public_metadata } = evt.data;
// Get primary email
const primaryEmail = email_addresses.find(
(email) => email.id === evt.data.primary_email_address_id
);
if (!primaryEmail?.email_address) {
console.error('No primary email found for user:', id);
return new Response('Error: No primary email', { status: 400 });
}
// Determine role from metadata or default to 'client'
const role = (public_metadata?.role as 'admin' | 'trainer' | 'client') || 'client';
// Insert user into database
await db.insert(users).values({
id,
email: primaryEmail.email_address,
firstName: first_name || '',
lastName: last_name || '',
password: '', // Clerk handles authentication, no password needed
role,
phone: null,
createdAt: new Date(),
updatedAt: new Date(),
});
console.log(`✅ User ${id} created in database`);
break;
}
case 'user.updated': {
const { id, email_addresses, first_name, last_name, public_metadata } = evt.data;
// Get primary email
const primaryEmail = email_addresses.find(
(email) => email.id === evt.data.primary_email_address_id
);
if (!primaryEmail?.email_address) {
console.error('No primary email found for user:', id);
return new Response('Error: No primary email', { status: 400 });
}
// Determine role from metadata
const role = (public_metadata?.role as 'admin' | 'trainer' | 'client') || 'client';
// Update user in database
await db
.update(users)
.set({
email: primaryEmail.email_address,
firstName: first_name || '',
lastName: last_name || '',
role,
updatedAt: new Date(),
})
.where(eq(users.id, id));
console.log(`✅ User ${id} updated in database`);
break;
}
case 'user.deleted': {
const { id } = evt.data;
if (!id) {
console.error('No user ID provided for deletion');
return new Response('Error: No user ID', { status: 400 });
}
// Delete user from database (cascade will handle related records)
await db.delete(users).where(eq(users.id, id));
console.log(`✅ User ${id} deleted from database`);
break;
}
default:
console.log(`Unhandled webhook event type: ${eventType}`);
}
return new Response('Webhook processed successfully', { status: 200 });
} catch (error) {
console.error('Error processing webhook:', error);
return new Response('Error: Processing failed', { status: 500 });
}
}
+43 -13
View File
@@ -1,22 +1,52 @@
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import {
ClerkProvider,
SignedIn,
SignedOut,
SignInButton,
UserButton,
} from "@clerk/nextjs";
const inter = Inter({ subsets: ['latin'] })
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: 'FitAI Admin',
description: 'Fitness management admin dashboard',
}
title: "FitAI Admin",
description: "Fitness management admin dashboard",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
}
<ClerkProvider>
<html lang="en">
<body className={inter.className}>
<header className="bg-white shadow-sm border-b">
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
<div className="flex items-center gap-2">
<h1 className="text-xl font-bold text-gray-900">FitAI Admin</h1>
</div>
<div className="flex items-center gap-4">
<SignedIn>
<UserButton afterSignOutUrl="/" />
</SignedIn>
<SignedOut>
<SignInButton mode="modal">
<button className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
Sign In
</button>
</SignInButton>
</SignedOut>
</div>
</div>
</header>
{children}
</body>
</html>
</ClerkProvider>
);
}
+111
View File
@@ -0,0 +1,111 @@
"use client";
import { useEffect, useState } from "react";
import { useUser } from "@clerk/nextjs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
interface UserProfile {
firstName: string;
lastName: string;
email: string;
phoneNumber: string;
}
export default function ProfilePage() {
const { user, isLoaded } = useUser();
const [profile, setProfile] = useState<UserProfile>({
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
});
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
if (isLoaded && user) {
setProfile({
firstName: user.firstName || "",
lastName: user.lastName || "",
email: user.emailAddresses[0]?.emailAddress || "",
phoneNumber: user.phoneNumbers[0]?.phoneNumber || "",
});
}
}, [isLoaded, user]);
const handleSave = async () => {
try {
await user?.update({
firstName: profile.firstName,
lastName: profile.lastName,
});
setIsEditing(false);
} catch (error) {
console.error("Error updating profile:", error);
}
};
if (!isLoaded) {
return <div>Loading...</div>;
}
return (
<div className="container mx-auto py-8">
<div className="max-w-2xl mx-auto bg-white p-8 rounded-lg shadow">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold">Profile</h1>
<Button
variant={isEditing ? "default" : "outline"}
onClick={() => setIsEditing(!isEditing)}
>
{isEditing ? "Cancel" : "Edit Profile"}
</Button>
</div>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">First Name</label>
<Input
type="text"
value={profile.firstName}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setProfile({ ...profile, firstName: e.target.value })
}
disabled={!isEditing}
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Last Name</label>
<Input
type="text"
value={profile.lastName}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setProfile({ ...profile, lastName: e.target.value })
}
disabled={!isEditing}
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Email</label>
<Input type="email" value={profile.email} disabled />
</div>
<div>
<label className="block text-sm font-medium mb-1">
Phone Number
</label>
<Input type="tel" value={profile.phoneNumber} disabled />
</div>
{isEditing && (
<div className="pt-4">
<Button onClick={handleSave}>Save Changes</Button>
</div>
)}
</div>
</div>
</div>
);
}
View File
Whitespace-only changes.
+97
View File
@@ -0,0 +1,97 @@
"use client";
import { type ReactElement } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Home, Users, BarChart3, User } from "lucide-react";
import { SignedIn, UserButton } from "@clerk/nextjs";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
interface NavItem {
href: string;
label: string;
icon: React.ElementType;
}
const navItems: NavItem[] = [
{
href: "/",
label: "Dashboard",
icon: Home,
},
{
href: "/users",
label: "Clients",
icon: Users,
},
{
href: "/analytics",
label: "Analytics",
icon: BarChart3,
},
{
href: "/profile",
label: "Profile",
icon: User,
},
];
export function Navigation(): ReactElement {
const pathname = usePathname();
return (
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<nav className="container mx-auto px-4 h-16">
<div className="flex h-full items-center justify-between">
{/* Logo */}
<Link
href="/"
className="text-xl font-bold text-[#FF0000] hover:text-[#00FF00] transition-colors"
>
FitAI
</Link>
{/* Navigation Items */}
<ul
className="flex-1 flex justify-center items-center"
style={{ gap: "3rem" }}
>
{navItems.map((item) => (
<li key={item.href}>
<Button
asChild
variant={pathname === item.href ? "default" : "ghost"}
size="sm"
className={cn(
"h-9 px-4 py-2",
pathname === item.href &&
"bg-primary text-primary-foreground",
)}
aria-current={pathname === item.href ? "page" : undefined}
>
<Link href={item.href} className="flex items-center gap-2">
<item.icon className="h-4 w-4" />
<span>{item.label}</span>
</Link>
</Button>
</li>
))}
</ul>
{/* User Button */}
<SignedIn>
<UserButton
afterSignOutUrl="/"
appearance={{
elements: {
avatarBox: "h-8 w-8",
},
}}
/>
</SignedIn>
</div>
</nav>
</header>
);
}
+56
View File
@@ -0,0 +1,56 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
},
);
Button.displayName = "Button";
export { Button, buttonVariants };
+25
View File
@@ -0,0 +1,25 @@
import * as React from "react";
import { cn } from "@/lib/utils";
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = "Input";
export { Input };
+140
View File
@@ -0,0 +1,140 @@
"use client";
import * as React from "react";
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Sheet = SheetPrimitive.Root;
const SheetTrigger = SheetPrimitive.Trigger;
const SheetClose = SheetPrimitive.Close;
const SheetPortal = SheetPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
},
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
));
SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className,
)}
{...props}
/>
);
SheetHeader.displayName = "SheetHeader";
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className,
)}
{...props}
/>
);
SheetFooter.displayName = "SheetFooter";
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
));
SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};
+198
View File
@@ -0,0 +1,198 @@
import { clerkClient } from '@clerk/nextjs/server';
/**
* User roles available in the application
*/
export type UserRole = 'admin' | 'trainer' | 'client';
/**
* Set a user's role in Clerk public metadata
* This will trigger a webhook that syncs the role to the database
*
* @param userId - Clerk user ID
* @param role - Role to assign (admin, trainer, or client)
* @returns Updated user object
*
* @example
* await setUserRole('user_abc123', 'admin');
*/
export async function setUserRole(userId: string, role: UserRole) {
const client = await clerkClient();
return await client.users.updateUser(userId, {
publicMetadata: { role },
});
}
/**
* Get a user's role from Clerk public metadata
*
* @param userId - Clerk user ID
* @returns User role or null if not set
*
* @example
* const role = await getUserRole('user_abc123');
* console.log(role); // 'admin' | 'trainer' | 'client' | null
*/
export async function getUserRole(userId: string): Promise<UserRole | null> {
const client = await clerkClient();
const user = await client.users.getUser(userId);
const role = user.publicMetadata?.role as UserRole | undefined;
return role || null;
}
/**
* Check if a user has a specific role
*
* @param userId - Clerk user ID
* @param role - Role to check
* @returns True if user has the role
*
* @example
* const isAdmin = await hasRole('user_abc123', 'admin');
*/
export async function hasRole(userId: string, role: UserRole): Promise<boolean> {
const userRole = await getUserRole(userId);
return userRole === role;
}
/**
* Check if a user is an admin
*
* @param userId - Clerk user ID
* @returns True if user is an admin
*
* @example
* const isAdmin = await isAdmin('user_abc123');
*/
export async function isAdmin(userId: string): Promise<boolean> {
return hasRole(userId, 'admin');
}
/**
* Check if a user is a trainer
*
* @param userId - Clerk user ID
* @returns True if user is a trainer
*
* @example
* const isTrainer = await isTrainer('user_abc123');
*/
export async function isTrainer(userId: string): Promise<boolean> {
return hasRole(userId, 'trainer');
}
/**
* Check if a user is a client
*
* @param userId - Clerk user ID
* @returns True if user is a client
*
* @example
* const isClient = await isClient('user_abc123');
*/
export async function isClient(userId: string): Promise<boolean> {
return hasRole(userId, 'client');
}
/**
* Bulk update roles for multiple users
*
* @param userRoles - Array of {userId, role} objects
* @returns Array of updated users
*
* @example
* await bulkSetUserRoles([
* { userId: 'user_abc123', role: 'admin' },
* { userId: 'user_def456', role: 'trainer' },
* ]);
*/
export async function bulkSetUserRoles(
userRoles: Array<{ userId: string; role: UserRole }>
): Promise<void> {
const client = await clerkClient();
await Promise.all(
userRoles.map(({ userId, role }) =>
client.users.updateUser(userId, {
publicMetadata: { role },
})
)
);
}
/**
* Get all users with a specific role
*
* @param role - Role to filter by
* @returns Array of users with the specified role
*
* @example
* const admins = await getUsersByRole('admin');
*/
export async function getUsersByRole(role: UserRole) {
const client = await clerkClient();
// Clerk doesn't support filtering by metadata directly, so we fetch all users
// and filter client-side. For large user bases, consider caching or database queries.
const { data: users } = await client.users.getUserList();
return users.filter(
(user) => (user.publicMetadata?.role as UserRole) === role
);
}
/**
* Get user count by role
*
* @returns Object with counts for each role
*
* @example
* const counts = await getUserCountByRole();
* console.log(counts); // { admin: 2, trainer: 5, client: 100 }
*/
export async function getUserCountByRole(): Promise<Record<UserRole, number>> {
const client = await clerkClient();
const { data: users } = await client.users.getUserList();
const counts: Record<UserRole, number> = {
admin: 0,
trainer: 0,
client: 0,
};
users.forEach((user) => {
const role = (user.publicMetadata?.role as UserRole) || 'client';
counts[role]++;
});
return counts;
}
/**
* Sync user role between Clerk and database manually
* Useful for fixing inconsistencies or after manual changes
*
* @param userId - Clerk user ID
* @returns Success status
*
* @example
* await syncUserRole('user_abc123');
*/
export async function syncUserRole(userId: string): Promise<boolean> {
try {
const client = await clerkClient();
const user = await client.users.getUser(userId);
// Trigger a webhook by updating the user (even with same data)
await client.users.updateUser(userId, {
publicMetadata: user.publicMetadata,
});
return true;
} catch (error) {
console.error('Error syncing user role:', error);
return false;
}
}
+37
View File
@@ -0,0 +1,37 @@
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
// Define routes that should be publicly accessible
const isPublicRoute = createRouteMatcher([
"/sign-in(.*)",
"/sign-up(.*)",
"/api/webhooks(.*)",
]);
// Define routes that require authentication
const isProtectedRoute = createRouteMatcher([
"/",
"/users(.*)",
"/analytics(.*)",
"/profile(.*)",
"/api/users(.*)",
"/api/profile(.*)",
"/api/payments(.*)",
"/api/attendance(.*)",
"/api/notifications(.*)",
]);
export default clerkMiddleware(async (auth, req) => {
// Protect all routes except public ones
if (!isPublicRoute(req)) {
await auth.protect();
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};