test9 / src /lib /auth.ts
simikkk's picture
Upload 82 files
35420f5 verified
Raw
History Blame Contribute Delete
3.23 kB
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import { db } from '@/lib/db';
import type { User } from '@prisma/client';
// ─── Password Hashing ─────────────────────────────────────────────────────────
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, 12);
}
export async function verifyPassword(
password: string,
hash: string
): Promise<boolean> {
return bcrypt.compare(password, hash);
}
// ─── Session Management ───────────────────────────────────────────────────────
export function generateSessionToken(): string {
return crypto.randomBytes(32).toString('hex');
}
export async function createSession(userId: string): Promise<string> {
const token = generateSessionToken();
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days
await db.session.create({
data: {
token,
userId,
expiresAt,
},
});
return token;
}
export async function getSessionUser(token: string): Promise<User | null> {
if (!token) return null;
const session = await db.session.findUnique({
where: { token },
include: { user: true },
});
if (!session) return null;
if (new Date() > session.expiresAt) {
await db.session.delete({ where: { id: session.id } });
return null;
}
return session.user;
}
export async function deleteSession(token: string): Promise<void> {
if (!token) return;
await db.session.deleteMany({ where: { token } });
}
// ─── Cookie Helpers ───────────────────────────────────────────────────────────
const SESSION_COOKIE_NAME = 'op_session';
export function getCookieToken(request: Request): string | null {
const cookieHeader = request.headers.get('cookie');
if (!cookieHeader) return null;
const match = cookieHeader.match(
new RegExp(`(?:^|;\\s*)${SESSION_COOKIE_NAME}=([^;]*)`)
);
return match ? decodeURIComponent(match[1]) : null;
}
export { SESSION_COOKIE_NAME };
// ─── API Key Generation ───────────────────────────────────────────────────────
export function generateApiKey(): string {
const randomHex = crypto.randomBytes(24).toString('hex');
return `op_live_${randomHex}`;
}
// ─── Plan Constants ───────────────────────────────────────────────────────────
export const PLAN_LIMITS: Record<string, number> = {
free: 20,
basic: 200,
pro: 2000,
enterprise: Infinity,
};
export const PLAN_LABELS: Record<string, string> = {
free: 'Free',
basic: 'Basic',
pro: 'Pro',
enterprise: 'Enterprise',
};
export const PLAN_PRICES: Record<string, number> = {
free: 0,
basic: 29,
pro: 129,
enterprise: 499,
};