Spaces:
Configuration error
Configuration error
File size: 1,136 Bytes
bcce530 | 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 | import "server-only"
import { stackServerApp } from "./stack-server"
export interface AuthUser {
id: string
email: string
displayName: string | null
}
/**
* Get the current authenticated user from the Stack Auth session.
* Returns null if not authenticated.
* Use this in API routes instead of trusting client-sent userId.
*/
export async function getAuthUser(): Promise<AuthUser | null> {
try {
const user = await stackServerApp.getUser()
if (!user) return null
return {
id: user.id,
email: user.primaryEmail ?? "",
displayName: user.displayName,
}
} catch {
return null
}
}
/**
* Require authentication. Throws a Response with 401 if not authenticated.
* Use in API routes that require a logged-in user.
*/
export async function requireAuth(): Promise<AuthUser> {
const user = await getAuthUser()
if (!user) {
throw new Response(
JSON.stringify({ error: "Authentication required" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
)
}
return user
}
|