feat: add authentication, user management, and admin features

Added comprehensive authentication and authorization system:

Authentication System:
- Better Auth integration with session management
- Login/logout pages and API routes
- Middleware for route protection
- Auth utilities and client libraries

User Management:
- User list, detail, and invite pages
- User API endpoints (CRUD operations)
- Session management for users
- Profile settings page

Role-Based Access Control:
- Role management pages (list, create, edit)
- Permission system with granular controls
- Role assignment to users
- Role API endpoints

Admin Features:
- Audit log page for tracking system events
- Admin settings page
- Audit service for logging user actions

Additional Features:
- Quotes management pages and components
- SalesBldr API integration
- Email service for notifications

Configuration & Documentation:
- Updated docker-compose.yml
- MCP server configuration (mcp.json)
- CVE-2025-55182 security review documentation
- Standards guide and PRD documents
- Re-enabling authentication documentation

Database Migrations:
- 012: Auth tables (users, sessions, accounts, verifications)
- 013: Role tables (roles, permissions, role_permissions, user_roles)
- 014: Admin settings table

UI Updates:
- Updated dashboard layout
- Enhanced app layout with auth integration
This commit is contained in:
root 2026-01-31 12:43:14 -05:00
parent d8e6931b85
commit 9f912aed24
68 changed files with 7651 additions and 3 deletions

View file

@ -0,0 +1,43 @@
"use client";
import { createContext, useContext, ReactNode } from "react";
import { authClient, useSession } from "@/lib/auth-client";
type AuthContextType = {
session: ReturnType<typeof useSession>["data"];
isPending: boolean;
error: ReturnType<typeof useSession>["error"];
signOut: () => Promise<void>;
};
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const { data: session, isPending, error } = useSession();
const handleSignOut = async () => {
await authClient.signOut();
window.location.href = "/auth/sign-in";
};
return (
<AuthContext.Provider
value={{
session,
isPending,
error,
signOut: handleSignOut,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}

View file

@ -0,0 +1,134 @@
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Mail, Loader2, CheckCircle } from "lucide-react";
import { toast } from "sonner";
import { authClient } from "@/lib/auth-client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
const formSchema = z.object({
email: z.string().email("Please enter a valid email address"),
});
type FormData = z.infer<typeof formSchema>;
export function MagicLinkForm() {
const [isLoading, setIsLoading] = useState(false);
const [emailSent, setEmailSent] = useState(false);
const [sentEmail, setSentEmail] = useState("");
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
},
});
async function onSubmit(data: FormData) {
setIsLoading(true);
try {
const result = await authClient.signIn.magicLink({
email: data.email,
callbackURL: "/",
});
if (result.error) {
toast.error(result.error.message || "Failed to send magic link");
return;
}
setEmailSent(true);
setSentEmail(data.email);
toast.success("Magic link sent! Check your email.");
} catch (error) {
toast.error("An unexpected error occurred");
console.error("Magic link error:", error);
} finally {
setIsLoading(false);
}
}
if (emailSent) {
return (
<div className="text-center space-y-4 py-4">
<div className="flex justify-center">
<div className="h-16 w-16 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
<CheckCircle className="h-8 w-8 text-green-600 dark:text-green-400" />
</div>
</div>
<div className="space-y-2">
<h3 className="text-lg font-semibold">Check your email</h3>
<p className="text-sm text-muted-foreground">
We sent a magic link to <strong>{sentEmail}</strong>
</p>
<p className="text-xs text-muted-foreground">
Click the link in the email to sign in. The link expires in 5 minutes.
</p>
</div>
<Button
variant="ghost"
className="text-sm"
onClick={() => {
setEmailSent(false);
form.reset();
}}
>
Use a different email
</Button>
</div>
);
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="you@example.com"
className="pl-10"
{...field}
disabled={isLoading}
/>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Sending magic link...
</>
) : (
<>
<Mail className="mr-2 h-4 w-4" />
Send magic link
</>
)}
</Button>
</form>
</Form>
);
}

View file

@ -0,0 +1,74 @@
"use client";
import { useState } from "react";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
import { authClient } from "@/lib/auth-client";
import { Button } from "@/components/ui/button";
// Microsoft logo SVG component
function MicrosoftLogo({ className }: { className?: string }) {
return (
<svg
className={className}
viewBox="0 0 21 21"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect x="1" y="1" width="9" height="9" fill="#F25022" />
<rect x="11" y="1" width="9" height="9" fill="#7FBA00" />
<rect x="1" y="11" width="9" height="9" fill="#00A4EF" />
<rect x="11" y="11" width="9" height="9" fill="#FFB900" />
</svg>
);
}
interface MicrosoftButtonProps {
callbackURL?: string;
}
export function MicrosoftButton({ callbackURL = "/" }: MicrosoftButtonProps) {
const [isLoading, setIsLoading] = useState(false);
async function handleMicrosoftSignIn() {
setIsLoading(true);
try {
const result = await authClient.signIn.social({
provider: "microsoft",
callbackURL,
});
if (result.error) {
toast.error(result.error.message || "Failed to sign in with Microsoft");
setIsLoading(false);
}
// If successful, the user will be redirected to Microsoft's OAuth page
} catch (error) {
toast.error("An unexpected error occurred");
console.error("Microsoft sign-in error:", error);
setIsLoading(false);
}
}
return (
<Button
type="button"
variant="outline"
className="w-full"
onClick={handleMicrosoftSignIn}
disabled={isLoading}
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Connecting...
</>
) : (
<>
<MicrosoftLogo className="mr-2 h-4 w-4" />
Continue with Microsoft 365
</>
)}
</Button>
);
}

View file

@ -0,0 +1,29 @@
"use client";
import { MagicLinkForm } from "./magic-link-form";
import { MicrosoftButton } from "./microsoft-button";
import { Separator } from "@/components/ui/separator";
export function SignInForm() {
return (
<div className="space-y-6">
{/* Microsoft OAuth */}
<MicrosoftButton />
{/* Divider */}
<div className="relative">
<div className="absolute inset-0 flex items-center">
<Separator className="w-full" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-white dark:bg-slate-900 px-2 text-muted-foreground">
Or continue with email
</span>
</div>
</div>
{/* Magic Link */}
<MagicLinkForm />
</div>
);
}

View file

@ -0,0 +1,132 @@
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Loader2, ShieldCheck } from "lucide-react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Checkbox } from "@/components/ui/checkbox";
const formSchema = z.object({
code: z.string().length(6, "Code must be 6 digits").regex(/^\d+$/, "Code must be numeric"),
trustDevice: z.boolean(),
});
type FormData = z.infer<typeof formSchema>;
interface TwoFactorFormProps {
callbackURL?: string;
}
export function TwoFactorForm({ callbackURL = "/" }: TwoFactorFormProps) {
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
code: "",
trustDevice: true,
},
});
async function onSubmit(data: FormData) {
setIsLoading(true);
try {
const result = await authClient.twoFactor.verifyTotp({
code: data.code,
trustDevice: data.trustDevice,
});
if (result.error) {
toast.error(result.error.message || "Invalid verification code");
form.setError("code", { message: "Invalid code" });
return;
}
toast.success("Verified successfully!");
router.push(callbackURL);
} catch (error) {
toast.error("An unexpected error occurred");
console.error("2FA verification error:", error);
} finally {
setIsLoading(false);
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="code"
render={({ field }) => (
<FormItem>
<FormLabel>Verification Code</FormLabel>
<FormControl>
<Input
placeholder="000000"
maxLength={6}
className="text-center text-2xl tracking-widest font-mono"
{...field}
disabled={isLoading}
autoComplete="one-time-code"
inputMode="numeric"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="trustDevice"
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
disabled={isLoading}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel className="text-sm font-normal">
Trust this device for 30 days
</FormLabel>
</div>
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Verifying...
</>
) : (
<>
<ShieldCheck className="mr-2 h-4 w-4" />
Verify
</>
)}
</Button>
</form>
</Form>
);
}