mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 15:12:09 +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:
88
lib/api-auth.ts
Normal file
88
lib/api-auth.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
export interface ApiSession {
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
companyId: string;
|
||||
company: string;
|
||||
};
|
||||
}
|
||||
|
||||
export async function getApiSession(req: NextApiRequest, res: NextApiResponse): Promise<ApiSession | null> {
|
||||
try {
|
||||
// Get session by making internal request to session endpoint
|
||||
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
|
||||
const host = req.headers.host || 'localhost:3000';
|
||||
const sessionUrl = `${protocol}://${host}/api/auth/session`;
|
||||
|
||||
// Forward all relevant headers including cookies
|
||||
const headers: Record<string, string> = {};
|
||||
if (req.headers.cookie) {
|
||||
headers['Cookie'] = Array.isArray(req.headers.cookie) ? req.headers.cookie.join('; ') : req.headers.cookie;
|
||||
}
|
||||
if (req.headers['user-agent']) {
|
||||
headers['User-Agent'] = Array.isArray(req.headers['user-agent']) ? req.headers['user-agent'][0] : req.headers['user-agent'];
|
||||
}
|
||||
if (req.headers['x-forwarded-for']) {
|
||||
headers['X-Forwarded-For'] = Array.isArray(req.headers['x-forwarded-for']) ? req.headers['x-forwarded-for'][0] : req.headers['x-forwarded-for'];
|
||||
}
|
||||
if (req.headers['x-forwarded-proto']) {
|
||||
headers['X-Forwarded-Proto'] = Array.isArray(req.headers['x-forwarded-proto']) ? req.headers['x-forwarded-proto'][0] : req.headers['x-forwarded-proto'];
|
||||
}
|
||||
|
||||
console.log('Requesting session from:', sessionUrl);
|
||||
console.log('With headers:', Object.keys(headers));
|
||||
|
||||
const sessionResponse = await fetch(sessionUrl, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
// Use agent to handle localhost properly
|
||||
...(host.includes('localhost') && {
|
||||
// No special agent needed for localhost in Node.js
|
||||
})
|
||||
});
|
||||
|
||||
if (!sessionResponse.ok) {
|
||||
console.log('Session response not ok:', sessionResponse.status, sessionResponse.statusText);
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionData: any = await sessionResponse.json();
|
||||
console.log('Session data received:', sessionData);
|
||||
|
||||
if (!sessionData?.user?.email) {
|
||||
console.log('No user email in session data');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get user data from database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: sessionData.user.email },
|
||||
include: { company: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
console.log('User not found in database:', sessionData.user.email);
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log('Successfully got user:', user.email);
|
||||
return {
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
companyId: user.companyId,
|
||||
company: user.company.name,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error getting API session:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
88
lib/auth-options.ts
Normal file
88
lib/auth-options.ts
Normal file
@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Auth.js v5 compatibility layer for Pages Router API routes
|
||||
* This provides the authOptions object for backward compatibility
|
||||
* with getServerSession from next-auth/next
|
||||
*/
|
||||
|
||||
import { NextAuthOptions } from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { prisma } from "../../../lib/prisma";
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
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 {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: credentials.email as string },
|
||||
include: { company: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(
|
||||
credentials.password as string,
|
||||
user.password
|
||||
);
|
||||
|
||||
if (!isPasswordValid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.email,
|
||||
role: user.role,
|
||||
companyId: user.companyId,
|
||||
company: user.company.name,
|
||||
};
|
||||
} 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,
|
||||
};
|
||||
@ -11,22 +11,22 @@ declare const global: {
|
||||
};
|
||||
|
||||
// Check if we're running in Cloudflare Workers environment
|
||||
const isCloudflareWorker = typeof globalThis.DB !== 'undefined';
|
||||
const isCloudflareWorker = typeof globalThis.DB !== "undefined";
|
||||
|
||||
// Initialize Prisma Client
|
||||
let prisma: PrismaClient;
|
||||
|
||||
if (isCloudflareWorker) {
|
||||
// In Cloudflare Workers, use D1 adapter
|
||||
const adapter = new PrismaD1(globalThis.DB);
|
||||
prisma = new PrismaClient({ adapter });
|
||||
// In Cloudflare Workers, use D1 adapter
|
||||
const adapter = new PrismaD1(globalThis.DB);
|
||||
prisma = new PrismaClient({ adapter });
|
||||
} else {
|
||||
// In Next.js/Node.js, use regular SQLite
|
||||
prisma = global.prisma || new PrismaClient();
|
||||
// In Next.js/Node.js, use regular SQLite
|
||||
prisma = global.prisma || new PrismaClient();
|
||||
|
||||
// Save in global if we're in development
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
global.prisma = prisma;
|
||||
// Save in global if we're in development
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
global.prisma = prisma;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
12
lib/types.ts
12
lib/types.ts
@ -1,15 +1,7 @@
|
||||
import { Session as NextAuthSession } from "next-auth";
|
||||
|
||||
export interface UserSession extends NextAuthSession {
|
||||
user: {
|
||||
id?: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
image?: string;
|
||||
companyId: string;
|
||||
role: string;
|
||||
};
|
||||
}
|
||||
// Use the NextAuth Session directly as it now includes our extended types
|
||||
export type UserSession = NextAuthSession;
|
||||
|
||||
export interface Company {
|
||||
id: string;
|
||||
|
||||
Reference in New Issue
Block a user