23 lines
861 B
JavaScript
23 lines
861 B
JavaScript
import { getCookie } from 'h3'
|
|
import { getDb } from '../utils/db.js'
|
|
import { skipAuth } from '../utils/authSkipPaths.js'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
if (skipAuth(event.path)) return
|
|
const sid = getCookie(event, 'session_id')
|
|
if (!sid) return
|
|
try {
|
|
const { get } = await getDb()
|
|
const session = await get('SELECT user_id, expires_at FROM sessions WHERE id = ?', [sid])
|
|
if (!session || new Date(session.expires_at) < new Date()) return
|
|
const user = await get('SELECT id, identifier, role, auth_provider FROM users WHERE id = ?', [session.user_id])
|
|
if (user) {
|
|
const authProvider = user.auth_provider ?? 'local'
|
|
event.context.user = { id: user.id, identifier: user.identifier, role: user.role, auth_provider: authProvider }
|
|
}
|
|
}
|
|
catch {
|
|
// ignore db errors; context stays unset
|
|
}
|
|
})
|