sync
This commit is contained in:
68
lib/auth.ts
Normal file
68
lib/auth.ts
Normal 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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user