Files
accounted/lib/auth/require-auth.ts
T
Jakob Wennberg 6d75b9a1bf feat: BankID authentication via TIC Identity API (#192)
* feat: add BankID authentication via TIC Identity API

Integrate BankID as a login/signup method using the TIC Identity API.
Users can authenticate with BankID QR codes (desktop) or deep links (mobile),
link BankID to existing accounts, and skip TOTP MFA when BankID is linked.
Removes Step 0 (role choice) from onboarding for all users. Adds enrichment
data support for pre-filling company details from Bolagsverket during signup.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review — server-side rate limit, unlink clears MFA bypass

- Add per-IP rate limit (5s cooldown) on /bankid/start to prevent
  unbounded billable TIC sessions from unauthenticated callers
- Add /bankid/unlink endpoint that deletes bankid_identities AND clears
  app_metadata.bankid_linked so MFA enforcement resumes after unlink
- Update BankIdSettings to call server-side unlink instead of client-side delete

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: move rate limiter to module scope, add BankID logo and year-end skill

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 13:44:14 +02:00

41 lines
1.2 KiB
TypeScript

import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { shouldEnforceMfa } from './mfa'
import type { User, SupabaseClient } from '@supabase/supabase-js'
type AuthResult =
| { user: User; supabase: SupabaseClient; error: null }
| { user: null; supabase: SupabaseClient; error: NextResponse }
/**
* Auth + MFA guard for API routes.
*
* Returns the authenticated user and Supabase client, or a JSON error response.
* When MFA is required (hosted deployment), verifies AAL2 assurance level.
*/
export async function requireAuth(): Promise<AuthResult> {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return {
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
}
}
if (shouldEnforceMfa(user)) {
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
if (aal?.nextLevel === 'aal2' && aal?.currentLevel !== 'aal2') {
return {
user: null,
supabase,
error: NextResponse.json({ error: 'MFA verification required' }, { status: 403 }),
}
}
}
return { user, supabase, error: null }
}