71 lines
1.6 KiB
TypeScript
71 lines
1.6 KiB
TypeScript
import { cookies } from 'next/headers'
|
|
import pool from './db'
|
|
|
|
export interface User {
|
|
id: number
|
|
username: string
|
|
email: string
|
|
referral_points?: number
|
|
}
|
|
|
|
// 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, referral_points 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,
|
|
referral_points: parseFloat(buyers[0].referral_points) || 0,
|
|
}
|
|
} 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
|
|
}
|
|
}
|
|
|