mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 15:52:10 +01:00
feat: Add authentication and session management with NextAuth.js and Prisma [broken]
- Implemented API session retrieval in `lib/api-auth.ts` to manage user sessions. - Created authentication options in `lib/auth-options.ts` using NextAuth.js with credentials provider. - Added migration scripts to create necessary tables for authentication in `migrations/0002_create_auth_tables.sql` and `prisma/migrations/20250601033219_add_nextauth_tables/migration.sql`. - Configured ESLint with Next.js and TypeScript support in `eslint.config.mjs`. - Updated Next.js configuration in `next.config.ts` for Cloudflare compatibility. - Defined Cloudflare Worker configuration in `open-next.config.ts` and `wrangler.jsonc`. - Enhanced type definitions for authentication in `types/auth.d.ts`. - Created a Cloudflare Worker entry point in `src/index.ts.backup` to handle API requests and responses.
This commit is contained in:
115
app/api/auth/[...nextauth]/route.ts
Normal file
115
app/api/auth/[...nextauth]/route.ts
Normal file
@ -0,0 +1,115 @@
|
||||
import NextAuth, { NextAuthConfig } from "next-auth";
|
||||
import { D1Adapter } from "@auth/d1-adapter";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { PrismaD1 } from "@prisma/adapter-d1";
|
||||
|
||||
// Check if we're in a Cloudflare Workers environment
|
||||
const isCloudflareWorker =
|
||||
typeof globalThis.caches !== "undefined" &&
|
||||
typeof (globalThis as any).WebSocketPair !== "undefined";
|
||||
|
||||
const config: NextAuthConfig = {
|
||||
providers: [
|
||||
Credentials({
|
||||
name: "credentials",
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
authorize: async (credentials) => {
|
||||
if (!credentials?.email || !credentials?.password) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
let prisma: PrismaClient;
|
||||
|
||||
// Initialize Prisma based on environment
|
||||
if (isCloudflareWorker) {
|
||||
// In Cloudflare Workers, get DB from bindings
|
||||
const adapter = new PrismaD1((globalThis as any).DB);
|
||||
prisma = new PrismaClient({ adapter });
|
||||
} else {
|
||||
// In local development, use standard Prisma
|
||||
prisma = new PrismaClient();
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: credentials.email as string },
|
||||
include: { company: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
await prisma.$disconnect();
|
||||
return null;
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(
|
||||
credentials.password as string,
|
||||
user.password
|
||||
);
|
||||
|
||||
if (!valid) {
|
||||
await prisma.$disconnect();
|
||||
return null;
|
||||
}
|
||||
|
||||
const result = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.email, // Use email as name
|
||||
role: user.role,
|
||||
companyId: user.companyId,
|
||||
company: user.company.name,
|
||||
};
|
||||
|
||||
await prisma.$disconnect();
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error("Authentication error:", error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
jwt: async ({ token, user }: any) => {
|
||||
if (user) {
|
||||
token.role = user.role;
|
||||
token.companyId = user.companyId;
|
||||
token.company = user.company;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
session: async ({ session, token }: any) => {
|
||||
if (token && session.user) {
|
||||
session.user.id = token.sub;
|
||||
session.user.role = token.role;
|
||||
session.user.companyId = token.companyId;
|
||||
session.user.company = token.company;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
error: "/login",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
maxAge: 30 * 24 * 60 * 60, // 30 days
|
||||
},
|
||||
secret: process.env.AUTH_SECRET,
|
||||
trustHost: true,
|
||||
};
|
||||
|
||||
// Add D1 adapter only in Cloudflare Workers environment
|
||||
if (isCloudflareWorker && (globalThis as any).DB) {
|
||||
(config as any).adapter = D1Adapter((globalThis as any).DB);
|
||||
}
|
||||
|
||||
const { handlers } = NextAuth(config);
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
@ -5,7 +5,7 @@ import { useSession } from "next-auth/react";
|
||||
import { Company } from "../../../lib/types";
|
||||
|
||||
interface CompanyConfigResponse {
|
||||
company: Company;
|
||||
company: Company;
|
||||
}
|
||||
|
||||
export default function CompanySettingsPage() {
|
||||
@ -26,7 +26,7 @@ export default function CompanySettingsPage() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch("/api/dashboard/config");
|
||||
const data = (await res.json()) as CompanyConfigResponse;
|
||||
const data = (await res.json()) as CompanyConfigResponse;
|
||||
setCompany(data.company);
|
||||
setCsvUrl(data.company.csvUrl || "");
|
||||
setCsvUsername(data.company.csvUsername || "");
|
||||
@ -62,10 +62,10 @@ export default function CompanySettingsPage() {
|
||||
if (res.ok) {
|
||||
setMessage("Settings saved successfully!");
|
||||
// Update local state if needed
|
||||
const data = (await res.json()) as CompanyConfigResponse;
|
||||
const data = (await res.json()) as CompanyConfigResponse;
|
||||
setCompany(data.company);
|
||||
} else {
|
||||
const error = (await res.json()) as { message?: string; };
|
||||
const error = (await res.json()) as { message?: string };
|
||||
setMessage(
|
||||
`Failed to save settings: ${error.message || "Unknown error"}`
|
||||
);
|
||||
|
||||
@ -18,8 +18,8 @@ import ResponseTimeDistribution from "../../../components/ResponseTimeDistributi
|
||||
import WelcomeBanner from "../../../components/WelcomeBanner";
|
||||
|
||||
interface MetricsApiResponse {
|
||||
metrics: MetricsResult;
|
||||
company: Company;
|
||||
metrics: MetricsResult;
|
||||
company: Company;
|
||||
}
|
||||
|
||||
// Safely wrapped component with useSession
|
||||
@ -45,7 +45,7 @@ function DashboardContent() {
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
const res = await fetch("/api/dashboard/metrics");
|
||||
const data = (await res.json()) as MetricsApiResponse;
|
||||
const data = (await res.json()) as MetricsApiResponse;
|
||||
console.log("Metrics from API:", {
|
||||
avgSessionLength: data.metrics.avgSessionLength,
|
||||
avgSessionTimeTrend: data.metrics.avgSessionTimeTrend,
|
||||
@ -81,10 +81,10 @@ function DashboardContent() {
|
||||
if (res.ok) {
|
||||
// Refetch metrics
|
||||
const metricsRes = await fetch("/api/dashboard/metrics");
|
||||
const data = (await metricsRes.json()) as MetricsApiResponse;
|
||||
const data = (await metricsRes.json()) as MetricsApiResponse;
|
||||
setMetrics(data.metrics);
|
||||
} else {
|
||||
const errorData = (await res.json()) as { error: string; };
|
||||
const errorData = (await res.json()) as { error: string };
|
||||
alert(`Failed to refresh sessions: ${errorData.error}`);
|
||||
}
|
||||
} finally {
|
||||
|
||||
@ -9,7 +9,7 @@ import { ChatSession } from "../../../../lib/types";
|
||||
import Link from "next/link";
|
||||
|
||||
interface SessionApiResponse {
|
||||
session: ChatSession;
|
||||
session: ChatSession;
|
||||
}
|
||||
|
||||
export default function SessionViewPage() {
|
||||
@ -34,13 +34,13 @@ export default function SessionViewPage() {
|
||||
try {
|
||||
const response = await fetch(`/api/dashboard/session/${id}`);
|
||||
if (!response.ok) {
|
||||
const errorData = (await response.json()) as { error: string; };
|
||||
const errorData = (await response.json()) as { error: string };
|
||||
throw new Error(
|
||||
errorData.error ||
|
||||
`Failed to fetch session: ${response.statusText}`
|
||||
);
|
||||
}
|
||||
const data = (await response.json()) as SessionApiResponse;
|
||||
const data = (await response.json()) as SessionApiResponse;
|
||||
setSession(data.session);
|
||||
} catch (err) {
|
||||
setError(
|
||||
@ -154,17 +154,17 @@ export default function SessionViewPage() {
|
||||
<p className="text-gray-600">
|
||||
No transcript content available for this session.
|
||||
</p>
|
||||
{session.fullTranscriptUrl &&
|
||||
process.env.NODE_ENV !== "production" && (
|
||||
<a
|
||||
href={session.fullTranscriptUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sky-600 hover:underline mt-2 inline-block"
|
||||
>
|
||||
View Source Transcript URL
|
||||
</a>
|
||||
)}
|
||||
{session.fullTranscriptUrl &&
|
||||
process.env.NODE_ENV !== "production" && (
|
||||
<a
|
||||
href={session.fullTranscriptUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sky-600 hover:underline mt-2 inline-block"
|
||||
>
|
||||
View Source Transcript URL
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -15,8 +15,8 @@ interface FilterOptions {
|
||||
}
|
||||
|
||||
interface SessionsApiResponse {
|
||||
sessions: ChatSession[];
|
||||
totalSessions: number;
|
||||
sessions: ChatSession[];
|
||||
totalSessions: number;
|
||||
}
|
||||
|
||||
export default function SessionsPage() {
|
||||
@ -63,7 +63,7 @@ export default function SessionsPage() {
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch filter options");
|
||||
}
|
||||
const data = (await response.json()) as FilterOptions;
|
||||
const data = (await response.json()) as FilterOptions;
|
||||
setFilterOptions(data);
|
||||
} catch (err) {
|
||||
setError(
|
||||
@ -93,7 +93,7 @@ export default function SessionsPage() {
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch sessions: ${response.statusText}`);
|
||||
}
|
||||
const data = (await response.json()) as SessionsApiResponse;
|
||||
const data = (await response.json()) as SessionsApiResponse;
|
||||
setSessions(data.sessions || []);
|
||||
setTotalPages(Math.ceil((data.totalSessions || 0) / pageSize));
|
||||
} catch (err) {
|
||||
|
||||
@ -13,7 +13,7 @@ interface UserManagementProps {
|
||||
}
|
||||
|
||||
interface UsersApiResponse {
|
||||
users: UserItem[];
|
||||
users: UserItem[];
|
||||
}
|
||||
|
||||
export default function UserManagement({ session }: UserManagementProps) {
|
||||
@ -25,7 +25,7 @@ export default function UserManagement({ session }: UserManagementProps) {
|
||||
useEffect(() => {
|
||||
fetch("/api/dashboard/users")
|
||||
.then((r) => r.json())
|
||||
.then((data) => setUsers((data as UsersApiResponse).users));
|
||||
.then((data) => setUsers((data as UsersApiResponse).users));
|
||||
}, []);
|
||||
|
||||
async function inviteUser() {
|
||||
|
||||
@ -31,11 +31,28 @@ export default function UserManagementPage() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch("/api/dashboard/users");
|
||||
const data = (await res.json()) as UsersApiResponse;
|
||||
setUsers(data.users);
|
||||
const data = await res.json() as UsersApiResponse | { error: string; };
|
||||
|
||||
if (res.ok && 'users' in data) {
|
||||
setUsers(data.users);
|
||||
} else {
|
||||
const errorMessage = 'error' in data ? data.error : "Unknown error";
|
||||
console.error("Failed to fetch users:", errorMessage);
|
||||
|
||||
if (errorMessage === "Admin access required") {
|
||||
setMessage("You need admin privileges to manage users.");
|
||||
} else if (errorMessage === "Not logged in") {
|
||||
setMessage("Please log in to access this page.");
|
||||
} else {
|
||||
setMessage(`Failed to load users: ${errorMessage}`);
|
||||
}
|
||||
|
||||
setUsers([]); // Set empty array to prevent undefined errors
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch users:", error);
|
||||
setMessage("Failed to load users.");
|
||||
setUsers([]); // Set empty array to prevent undefined errors
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@ -169,13 +186,22 @@ export default function UserManagementPage() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{users.length === 0 ? (
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={3}
|
||||
className="px-6 py-4 text-center text-sm text-gray-500"
|
||||
>
|
||||
Loading users...
|
||||
</td>
|
||||
</tr>
|
||||
) : users.length === 0 ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={3}
|
||||
className="px-6 py-4 text-center text-sm text-gray-500"
|
||||
>
|
||||
No users found
|
||||
{message || "No users found"}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { getServerSession } from "next-auth";
|
||||
import { auth } from "../auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { authOptions } from "../pages/api/auth/[...nextauth]";
|
||||
|
||||
export default async function HomePage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
const session = await auth();
|
||||
if (session?.user) redirect("/dashboard");
|
||||
else redirect("/login");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user