Files
accounted/app/(auth)/account/set-password/page.tsx
T
Jakob WennbergandClaude Opus 4.7 cc351158f8 Invoicing & account-security polish bundle (#550)
* feat: invoicing & account-security polish bundle

Five independent improvements bundled to ship together:

- BankID/password lockout fix: BankID-only users could enroll MFA and
  brick themselves (Supabase requires AAL2 to change password or unenroll
  MFA, and AAL2 needs a password sign-in). New app_metadata.has_password
  flag tracks this; middleware gates /mfa/enroll behind it, /account/set-
  password is the unlock path, SecuritySettings shows a banner, and
  /api/account/password is the single write path that flips the flag.
  Backfill script for existing users.

- Swish invoice payment method: company_settings.swish + invoice_show_swish
  columns, validation in lib/api/schemas.ts (accepts 123XXXXXXX företag or
  07XXXXXXXX mobile, strips whitespace/hyphens), rendered on invoice PDFs.

- Send-reminders kill switch: per-company company_settings.send_invoice_
  reminders toggle in PdfPrintSettings/Automatisering. Reminder processor
  also tightened: positive status allowlist (sent + overdue) so terminal
  statuses can never match; skip when customer already responded via
  reminder link; race-window re-check before send.

- First-invoice logo prompt: one-shot dialog when creating the first
  invoice without a logo (issue #520). Self-limits via head-only count.

- SIE export opening-balance fallback: route IB through getOpeningBalances
  so the compute_prior_opening_balances RPC supplies #IB after multi-year
  imports where opening_balance_entry_id is intentionally NULL. Previously
  #IB silently went to zero and #UB collapsed to current-period movements.

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

* fix(account-polish): address PR review feedback

- BankID-link path (extensions/general/tic/index.ts): read-merge-write
  app_metadata instead of passing { bankid_linked: true } alone.
  updateUserById REPLACES app_metadata wholesale, so the previous code
  would have wiped has_password for any user who later linked BankID,
  causing the set-password banner to (incorrectly) reappear and blocking
  the standard MFA enrollment button. The comment is now corrected.

- Middleware (lib/supabase/middleware.ts): thread inner returnTo through
  the /mfa/enroll → /account/set-password redirect so the user lands on
  their original destination after the full chain completes, not on /.

- safeReturnTo helper (lib/auth/safe-return-to.ts): replace the
  starts-with-/-but-not-// guard on mfa/enroll and set-password pages.
  The previous guard let /\evil.com and /@evil.com through. The new
  helper parses against a synthetic base origin and verifies it matches.

- set-password page (app/(auth)/account/set-password/page.tsx): remove
  CLAUDE.md design system violations — bg-gradient-to-b on page bg,
  inline shadow-md style on the card, space-y-5, font-medium on the h1,
  rounded-xl on the card. Flat surface, hairline border, font-display
  h1 per the design tokens.

- Swish dedup (lib/payments/swish.ts): extract normaliseSwish() and
  isValidSwish() helpers and use them in lib/api/schemas.ts,
  components/settings/BankDetailsForm.tsx, and the invoicing settings
  page. Single source of truth for the regex.

- Password route (app/api/account/password/route.ts): emit a structured
  success log so the audit pipeline can detect password-set events, not
  just failures.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 16:44:09 +02:00

188 lines
5.7 KiB
TypeScript

'use client'
import { useState, useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, KeyRound } from 'lucide-react'
import { userHasPassword } from '@/lib/auth/has-password'
import { safeReturnTo } from '@/lib/auth/safe-return-to'
export default function SetPasswordPage() {
return (
<Suspense>
<SetPasswordContent />
</Suspense>
)
}
function SetPasswordContent() {
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [isLoading, setIsLoading] = useState(false)
const { toast } = useToast()
const router = useRouter()
const searchParams = useSearchParams()
const supabase = createClient()
const returnTo = safeReturnTo(searchParams.get('returnTo'), '/settings/account')
// Users who already have a password don't belong here — bounce them away.
useEffect(() => {
let cancelled = false
;(async () => {
const {
data: { user },
} = await supabase.auth.getUser()
if (cancelled) return
if (!user) {
router.replace('/login')
return
}
if (userHasPassword(user)) {
router.replace(returnTo)
}
})()
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const handleSetPassword = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
setIsLoading(true)
const strong =
password.length >= 8 &&
/[a-z]/.test(password) &&
/[A-Z]/.test(password) &&
/[0-9]/.test(password) &&
/[^a-zA-Z0-9]/.test(password)
if (!strong) {
toast({
title: 'Lösenordet är för svagt',
description:
'Lösenordet måste vara minst 8 tecken och innehålla versaler, gemener, siffror och specialtecken.',
variant: 'destructive',
})
setIsLoading(false)
return
}
if (password !== confirmPassword) {
toast({
title: 'Lösenorden matchar inte',
description: 'Kontrollera att du skrev samma lösenord i båda fälten.',
variant: 'destructive',
})
setIsLoading(false)
return
}
try {
const res = await fetch('/api/account/password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
})
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string }
toast({
title: 'Kunde inte spara lösenord',
description: body.error || 'Försök igen senare.',
variant: 'destructive',
})
return
}
toast({
title: 'Lösenord sparat',
description: 'Du kan nu aktivera tvåfaktorsautentisering.',
})
router.push(returnTo)
router.refresh()
} catch {
toast({
title: 'Något gick fel',
description: 'Försök igen senare.',
variant: 'destructive',
})
} finally {
setIsLoading(false)
}
}
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-background p-4">
<div className="w-full max-w-sm animate-slide-up">
<div className="text-center mb-10">
<div className="flex justify-center mb-4">
<div className="h-14 w-14 rounded-lg bg-secondary flex items-center justify-center">
<KeyRound className="h-7 w-7 text-primary" />
</div>
</div>
<h1 className="font-display text-3xl tracking-tight">
Sätt ett lösenord
</h1>
<p className="text-muted-foreground text-sm mt-2">
Du loggade in med BankID. För att aktivera tvåfaktorsautentisering
eller logga in med e-post behöver du först sätta ett lösenord.
</p>
</div>
<div className="rounded-lg border border-border bg-card p-6">
<form onSubmit={handleSetPassword} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="password">Lösenord</Label>
<Input
id="password"
type="password"
autoComplete="new-password"
placeholder="Minst 8 tecken, Aa1!"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
disabled={isLoading}
className="h-11"
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirm_password">Bekräfta lösenord</Label>
<Input
id="confirm_password"
type="password"
autoComplete="new-password"
placeholder="Upprepa lösenordet"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
minLength={8}
disabled={isLoading}
className="h-11"
/>
</div>
<Button type="submit" className="w-full h-11" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Sparar...
</>
) : (
'Spara lösenord'
)}
</Button>
</form>
</div>
</div>
</div>
)
}