Getting Started
Retrieve a session
import { getSession, getUserSession } from '@repo/auth/server'
// May return undefined if no session exists
const session = getSession()
// Throws 401 if no authenticated user -- use when you need a guaranteed user
const userSession = getUserSession()
Create a basic gate
Gates are functions that receive a session and return true, false, or a GateResult.
import type { Gate } from '@repo/auth'
import { createGateResult } from '@repo/auth'
const isAdmin: Gate = (session) => {
if (!session?.user?.id) {
return createGateResult(false, 401)
}
return hasPermission(session.entity.permissions, '*', ['*'])
}
Protect a route
Wrap validateAccessInSvelte per-app so you can customize redirect behavior:
import type { Gate } from '@repo/auth'
import { validateAccessInSvelte } from '@repo/auth/server'
import { getRequestEvent } from '$app/server'
import { redirect } from '@sveltejs/kit'
export async function validateSession(gates?: Gate[]) {
await validateAccessInSvelte({
gates,
onUnauthenticated: () => {
const request = getRequestEvent()
const redirectTarget = encodeURIComponent(request.url.pathname + request.url.search)
redirect(307, `/login?redirect=${redirectTarget}`)
},
onUnauthorized: () => {
redirect(307, '/dashboard')
},
})
}
Then use it in any server context:
import { isAuthenticatedGate, permissionGate } from '@repo/auth'
await validateSession([isAuthenticatedGate, permissionGate('invoices', ['read'])])