📦 EqualifyEverything / equalify-reflow

📄 LoginPage.tsx · 163 lines
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163import { useState, type FormEvent, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'

import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'

import { apiFetch } from './apiFetch'
import { useAuth } from './AuthContext'
import type { Identity } from './types'

export function LoginPage() {
  const { config, identity, setIdentity } = useAuth()
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const next = searchParams.get('next') || '/'

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  // Already logged in → bounce to next.
  useEffect(() => {
    if (identity) {
      navigate(next, { replace: true })
    }
  }, [identity, next, navigate])

  // AUTH_MODE=none → there's nothing to log into; send the user home.
  useEffect(() => {
    if (config && config.mode === 'none') {
      navigate('/', { replace: true })
    }
  }, [config, navigate])

  // OIDC with a single provider → auto-redirect to its login_url.
  useEffect(() => {
    if (config && config.mode === 'oidc' && config.providers.length === 1) {
      const url = new URL(config.providers[0].login_url, window.location.origin)
      url.searchParams.set('next', next)
      window.location.href = url.toString()
    }
  }, [config, next])

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (submitting) return
    setError(null)
    setSubmitting(true)
    try {
      const res = await apiFetch('/api/v1/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
      })
      if (!res.ok) {
        setError(res.status === 401 ? 'Invalid username or password.' : 'Login failed.')
        return
      }
      const id = (await res.json()) as Identity
      setIdentity(id)
      navigate(next, { replace: true })
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setSubmitting(false)
    }
  }

  if (!config) {
    return (
      <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
        Loading…
      </div>
    )
  }

  if (config.mode === 'oidc') {
    return (
      <main className="flex min-h-screen items-center justify-center bg-background px-4">
        <section className="w-full max-w-sm space-y-6 rounded-lg border border-border bg-card p-8 shadow-lg">
          <header>
            <h1 className="text-2xl font-bold">Sign in</h1>
            <p className="mt-1 text-sm text-muted-foreground">
              Choose a sign-in method to continue.
            </p>
          </header>
          <ul className="space-y-3">
            {config.providers.map((provider) => {
              const url = new URL(provider.login_url, window.location.origin)
              url.searchParams.set('next', next)
              return (
                <li key={provider.id}>
                  <Button
                    asChild
                    variant="primary"
                    size="lg"
                    className="w-full"
                  >
                    <a href={url.toString()}>{provider.display_name}</a>
                  </Button>
                </li>
              )
            })}
          </ul>
        </section>
      </main>
    )
  }

  // Basic mode form.
  return (
    <main className="flex min-h-screen items-center justify-center bg-background px-4">
      <section className="w-full max-w-sm space-y-6 rounded-lg border border-border bg-card p-8 shadow-lg">
        <header>
          <h1 className="text-2xl font-bold">Sign in</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Enter your username and password to continue.
          </p>
        </header>
        <form className="space-y-4" onSubmit={handleSubmit} noValidate>
          <label className="block space-y-1">
            <span className="text-sm font-medium">Username</span>
            <Input
              type="text"
              autoComplete="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              disabled={submitting}
            />
          </label>
          <label className="block space-y-1">
            <span className="text-sm font-medium">Password</span>
            <Input
              type="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              disabled={submitting}
            />
          </label>
          {error && (
            <p role="alert" className="text-sm text-destructive">
              {error}
            </p>
          )}
          <Button
            type="submit"
            variant="primary"
            size="lg"
            className="w-full"
            disabled={submitting || !username || !password}
          >
            {submitting ? 'Signing in…' : 'Sign in'}
          </Button>
        </form>
      </section>
    </main>
  )
}