File size: 3,233 Bytes
eaab0a9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | 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,
}; |