This commit is contained in:
root
2025-12-20 19:00:42 +01:00
parent 9871289bfb
commit e1a0966dee
23 changed files with 1878 additions and 48 deletions

68
lib/auth.ts Normal file
View File

@@ -0,0 +1,68 @@
import { cookies } from 'next/headers'
import pool from './db'
export interface User {
id: number
username: string
email: string
}
// Get the current user from session cookie
export async function getCurrentUser(): Promise<User | null> {
try {
const cookieStore = await cookies()
const buyerId = cookieStore.get('buyer_id')?.value
if (!buyerId) {
return null
}
const [rows] = await pool.execute(
'SELECT id, username, email FROM buyers WHERE id = ?',
[buyerId]
)
const buyers = rows as any[]
if (buyers.length === 0) {
return null
}
return {
id: buyers[0].id,
username: buyers[0].username,
email: buyers[0].email,
}
} catch (error) {
console.error('Error getting current user:', error)
return null
}
}
// Get buyer ID from request cookies (for API routes)
export async function getBuyerIdFromRequest(
request: Request
): Promise<number | null> {
try {
const cookieHeader = request.headers.get('cookie')
if (!cookieHeader) {
return null
}
const cookies = cookieHeader.split(';').reduce((acc, cookie) => {
const [key, value] = cookie.trim().split('=')
acc[key] = value
return acc
}, {} as Record<string, string>)
const buyerId = cookies['buyer_id']
if (!buyerId) {
return null
}
return parseInt(buyerId, 10)
} catch (error) {
console.error('Error getting buyer ID from request:', error)
return null
}
}