open-prompt / src /lib /auth.ts
GitHub Action
Automated sync to Hugging Face
bcce530
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
}