feature/oidc-login #12

Merged
hzhang merged 5 commits from feature/oidc-login into main 2026-05-17 21:27:55 +00:00
9 changed files with 312 additions and 34 deletions
Showing only changes of commit 8f8d6d5465 - Show all commits

View File

@@ -12,5 +12,10 @@ RUN npm install -g serve@14
WORKDIR /app
COPY --from=build /app ./
ENV FRONTEND_DEV_MODE=0
# OIDC-only mode flag. The SPA's effective behavior is driven at runtime by
# the backend's public GET /auth/config (single source of truth); this
# build/runtime arg is declared so the frontend image carries the same knob.
ARG HARBORFORGE_OIDC_ONLY=false
ENV HARBORFORGE_OIDC_ONLY=${HARBORFORGE_OIDC_ONLY}
EXPOSE 3000
CMD ["sh", "-c", "if [ \"$FRONTEND_DEV_MODE\" = \"1\" ]; then npm run dev -- --host 0.0.0.0 --port 3000 --strictPort; else serve -s dist -l 3000; fi"]

View File

@@ -20,6 +20,7 @@ import UsersPage from '@/pages/UsersPage'
import CalendarPage from '@/pages/CalendarPage'
import SupportDetailPage from '@/pages/SupportDetailPage'
import MeetingDetailPage from '@/pages/MeetingDetailPage'
import OidcCallbackPage from '@/pages/OidcCallbackPage'
import axios from 'axios'
const getStoredWizardPort = (): number | null => {
@@ -35,7 +36,7 @@ type AppState = 'checking' | 'setup' | 'ready'
export default function App() {
const [appState, setAppState] = useState<AppState>('checking')
const { user, loading, login, logout } = useAuth()
const { user, loading, login, loginWithToken, logout } = useAuth()
useEffect(() => {
checkInitialized()
@@ -100,6 +101,7 @@ export default function App() {
<Route path="/users" element={<UsersPage />} />
<Route path="/monitor" element={<MonitorPage />} />
<Route path="/login" element={<LoginPage onLogin={login} />} />
<Route path="/oidc/callback" element={<OidcCallbackPage onToken={loginWithToken} />} />
<Route path="*" element={<Navigate to="/monitor" />} />
</Routes>
</main>
@@ -133,6 +135,7 @@ export default function App() {
<Route path="/roles" element={<RoleEditorPage />} />
<Route path="/users" element={<UsersPage />} />
<Route path="/monitor" element={<MonitorPage />} />
<Route path="/oidc/callback" element={<OidcCallbackPage onToken={loginWithToken} />} />
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</main>

View File

@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import api from '@/services/api'
import { useAuthConfig, oidcLinkHref } from '@/hooks/useAuthConfig'
import type { User } from '@/types'
interface Props {
@@ -11,6 +12,7 @@ interface Props {
export default function Sidebar({ user, onLogout }: Props) {
const { pathname } = useLocation()
const navigate = useNavigate()
const { config: authCfg } = useAuthConfig()
const [unreadCount, setUnreadCount] = useState(0)
useEffect(() => {
@@ -64,6 +66,11 @@ export default function Sidebar({ user, onLogout }: Props) {
<button onClick={() => navigate('/login')}>Log in</button>
)}
</div>
{user && authCfg.oidcEnabled && !authCfg.oidcOnly && (
<div className="sidebar-footer" style={{ borderTop: 'none', paddingTop: 0 }}>
<a href={oidcLinkHref()} title="Link your account to an OIDC identity">🔗 Link OIDC account</a>
</div>
)}
</nav>
)
}

View File

@@ -44,10 +44,16 @@ export function useAuth() {
await fetchUser()
}
const loginWithToken = async (token: string) => {
localStorage.setItem('token', token)
setState((s) => ({ ...s, token }))
await fetchUser()
}
const logout = () => {
localStorage.removeItem('token')
setState({ user: null, token: null, loading: false })
}
return { ...state, login, logout }
return { ...state, login, loginWithToken, logout }
}

View File

@@ -0,0 +1,76 @@
import { useState, useEffect } from 'react'
import api from '@/services/api'
export interface AuthConfig {
oidcEnabled: boolean
oidcOnly: boolean
passwordLogin: boolean
oidcLoginUrl: string
}
const DEFAULT: AuthConfig = {
oidcEnabled: false,
oidcOnly: false,
passwordLogin: true,
oidcLoginUrl: '/auth/oidc/login',
}
let cache: AuthConfig | null = null
let inflight: Promise<AuthConfig> | null = null
async function load(): Promise<AuthConfig> {
if (cache) return cache
if (inflight) return inflight
inflight = api
.get('/auth/config')
.then(({ data }) => {
cache = {
oidcEnabled: !!data.oidc_enabled,
oidcOnly: !!data.oidc_only,
passwordLogin: data.password_login !== false,
oidcLoginUrl: data.oidc_login_url || '/auth/oidc/login',
}
return cache
})
.catch(() => {
// Backend unreachable / old backend without /auth/config:
// fall back to password-only so login is never fully blocked.
cache = { ...DEFAULT }
return cache
})
.finally(() => {
inflight = null
})
return inflight
}
/** Absolute backend URL for full-page OIDC redirects. */
export function oidcLoginHref(cfg: AuthConfig): string {
const base = localStorage.getItem('HF_BACKEND_BASE_URL') ?? ''
return `${base}${cfg.oidcLoginUrl}`
}
export function oidcLinkHref(): string {
const base = localStorage.getItem('HF_BACKEND_BASE_URL') ?? ''
return `${base}/auth/oidc/link`
}
export function useAuthConfig() {
const [config, setConfig] = useState<AuthConfig | null>(cache)
const [loading, setLoading] = useState(!cache)
useEffect(() => {
let alive = true
load().then((c) => {
if (alive) {
setConfig(c)
setLoading(false)
}
})
return () => {
alive = false
}
}, [])
return { config: config ?? DEFAULT, loading }
}

View File

@@ -1,15 +1,30 @@
import React, { useState } from 'react'
import { useAuthConfig, oidcLoginHref } from '@/hooks/useAuthConfig'
interface Props {
onLogin: (username: string, password: string) => Promise<void>
}
const OIDC_ERRORS: Record<string, string> = {
not_linked: 'This OIDC account is not linked to any HarborForge user. Ask an administrator to bind it first.',
exchange_failed: 'OIDC sign-in failed during token exchange. Please try again.',
no_subject: 'The identity provider did not return a subject. Sign-in aborted.',
token_rejected: 'The issued session token was rejected. Please try again.',
missing_token: 'No session token was returned. Please try again.',
link_not_allowed: 'Account linking is not allowed in this mode.',
already_bound: 'That OIDC identity is already bound to another user.',
}
export default function LoginPage({ onLogin }: Props) {
const { config, loading: cfgLoading } = useAuthConfig()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const urlError = new URLSearchParams(window.location.search).get('oidc_error')
const oidcError = urlError ? (OIDC_ERRORS[urlError] || `OIDC error: ${urlError}`) : ''
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
@@ -23,31 +38,58 @@ export default function LoginPage({ onLogin }: Props) {
}
}
const showPassword = !cfgLoading && config.passwordLogin && !config.oidcOnly
const showOidc = !cfgLoading && config.oidcEnabled
return (
<div className="login-page">
<div className="login-card">
<h1> HarborForge</h1>
<p className="subtitle">Agent/Human collaborative task management platform</p>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
{error && <p className="error">{error}</p>}
<button type="submit" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
{oidcError && <p className="error" style={{ marginBottom: 14 }}>{oidcError}</p>}
{showPassword && (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
{error && <p className="error">{error}</p>}
<button type="submit" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
)}
{showPassword && showOidc && (
<p className="text-dim" style={{ textAlign: 'center', margin: '14px 0' }}> or </p>
)}
{showOidc && (
<a
className="btn-primary"
style={{ display: 'block', textAlign: 'center', textDecoration: 'none' }}
href={oidcLoginHref(config)}
>
Sign in with SSO
</a>
)}
{cfgLoading && <p className="subtitle">Loading sign-in options</p>}
{!cfgLoading && !showPassword && !showOidc && (
<p className="error">No sign-in method is available. Check server configuration.</p>
)}
</div>
</div>
)

View File

@@ -0,0 +1,55 @@
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
interface Props {
onToken: (token: string) => Promise<void>
}
/**
* Lands here after the backend OIDC callback redirect.
* - sign-in: URL fragment `#token=<jwt>` → apply token, go to dashboard
* - self-link: query `?oidc_linked=1` → success notice, go to /users
* - failure: query `?oidc_error=<code>` → back to /login with the code
*/
export default function OidcCallbackPage({ onToken }: Props) {
const navigate = useNavigate()
const [msg, setMsg] = useState('Completing sign-in…')
const ran = useRef(false)
useEffect(() => {
if (ran.current) return
ran.current = true
const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''))
const query = new URLSearchParams(window.location.search)
const token = hash.get('token')
const oidcError = query.get('oidc_error')
const linked = query.get('oidc_linked')
if (oidcError) {
navigate(`/login?oidc_error=${encodeURIComponent(oidcError)}`, { replace: true })
return
}
if (linked) {
setMsg('OIDC account linked. Redirecting…')
const t = setTimeout(() => navigate('/users', { replace: true }), 1200)
return () => clearTimeout(t)
}
if (token) {
onToken(token)
.then(() => navigate('/', { replace: true }))
.catch(() => navigate('/login?oidc_error=token_rejected', { replace: true }))
return
}
navigate('/login?oidc_error=missing_token', { replace: true })
}, [navigate, onToken])
return (
<div className="login-page">
<div className="login-card">
<h1> HarborForge</h1>
<p className="subtitle">{msg}</p>
</div>
</div>
)
}

View File

@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from 'react'
import api from '@/services/api'
import { useAuth } from '@/hooks/useAuth'
import { useAuthConfig } from '@/hooks/useAuthConfig'
import type { User } from '@/types'
interface RoleOption {
@@ -16,8 +17,13 @@ interface ApiKeyPerms {
export default function UsersPage() {
const { user } = useAuth()
const { config: authCfg } = useAuthConfig()
const oidcOnly = authCfg.oidcOnly
const oidcEnabled = authCfg.oidcEnabled
const isAdmin = user?.is_admin === true
const [bindForm, setBindForm] = useState({ issuer: '', subject: '' })
const [users, setUsers] = useState<User[]>([])
const [roles, setRoles] = useState<RoleOption[]>([])
const [loading, setLoading] = useState(true)
@@ -105,17 +111,20 @@ export default function UsersPage() {
}
const handleCreateUser = async () => {
if (!createForm.username.trim() || !createForm.email.trim() || !createForm.password.trim()) return
if (!createForm.username.trim() || !createForm.email.trim()) return
if (!oidcOnly && !createForm.password.trim()) return
setSaving(true)
setMessage('')
try {
const payload = {
const payload: Record<string, any> = {
username: createForm.username.trim(),
email: createForm.email.trim(),
full_name: createForm.full_name.trim() || null,
password: createForm.password,
role_id: createForm.role_id ? Number(createForm.role_id) : undefined,
}
if (!oidcOnly) {
payload.password = createForm.password
}
const { data } = await api.post<User>('/users', payload)
const guestRole = roles.find((r) => r.name === 'guest') ?? roles[0]
setCreateForm({
@@ -201,6 +210,42 @@ export default function UsersPage() {
}
}
const handleBindOidc = async () => {
if (!selectedUser) return
if (!bindForm.issuer.trim() || !bindForm.subject.trim()) return
setSaving(true)
setMessage('')
try {
await api.put(`/users/${selectedUser.id}/oidc-binding`, {
issuer: bindForm.issuer.trim(),
subject: bindForm.subject.trim(),
})
setBindForm({ issuer: '', subject: '' })
setMessage('OIDC identity bound successfully')
await fetchData()
} catch (err: any) {
setMessage(err.response?.data?.detail || 'Failed to bind OIDC identity')
} finally {
setSaving(false)
}
}
const handleUnbindOidc = async () => {
if (!selectedUser) return
if (!confirm(`Remove the OIDC binding for ${selectedUser.username}?`)) return
setSaving(true)
setMessage('')
try {
await api.delete(`/users/${selectedUser.id}/oidc-binding`)
setMessage('OIDC binding removed')
await fetchData()
} catch (err: any) {
setMessage(err.response?.data?.detail || 'Failed to remove OIDC binding')
} finally {
setSaving(false)
}
}
if (loading) return <div className="loading">Loading users...</div>
if (!isAdmin) {
@@ -251,10 +296,15 @@ export default function UsersPage() {
Full Name
<input value={createForm.full_name} onChange={(e) => setCreateForm({ ...createForm, full_name: e.target.value })} />
</label>
<label>
Password
<input type="password" value={createForm.password} onChange={(e) => setCreateForm({ ...createForm, password: e.target.value })} />
</label>
{!oidcOnly && (
<label>
Password
<input type="password" value={createForm.password} onChange={(e) => setCreateForm({ ...createForm, password: e.target.value })} />
</label>
)}
{oidcOnly && (
<p className="text-dim">OIDC-only mode: users are created without a password and sign in via a bound OIDC identity.</p>
)}
<label>
Role
<select value={createForm.role_id} onChange={(e) => setCreateForm({ ...createForm, role_id: e.target.value })}>
@@ -264,7 +314,7 @@ export default function UsersPage() {
))}
</select>
</label>
<button className="btn-primary" disabled={saving || !createForm.username.trim() || !createForm.email.trim() || !createForm.password.trim() || !createForm.role_id} onClick={handleCreateUser}>
<button className="btn-primary" disabled={saving || !createForm.username.trim() || !createForm.email.trim() || (!oidcOnly && !createForm.password.trim()) || !createForm.role_id} onClick={handleCreateUser}>
{saving ? 'Saving...' : 'Create User'}
</button>
</div>
@@ -326,10 +376,12 @@ export default function UsersPage() {
Full Name
<input value={editForm.full_name} onChange={(e) => setEditForm({ ...editForm, full_name: e.target.value })} />
</label>
<label>
Reset Password
<input type="password" placeholder="Leave blank to keep current password" value={editForm.password} onChange={(e) => setEditForm({ ...editForm, password: e.target.value })} />
</label>
{!oidcOnly && (
<label>
Reset Password
<input type="password" placeholder="Leave blank to keep current password" value={editForm.password} onChange={(e) => setEditForm({ ...editForm, password: e.target.value })} />
</label>
)}
<div style={{ marginTop: '8px', padding: '12px', border: '1px solid var(--border)', borderRadius: '8px' }}>
<div style={{ fontWeight: 600, marginBottom: '10px' }}>Role</div>
@@ -381,6 +433,36 @@ export default function UsersPage() {
)}
</div>
)}
{oidcEnabled && (
<div style={{ marginTop: '8px', padding: '12px', border: '1px solid var(--border)', borderRadius: '8px' }}>
<div style={{ fontWeight: 600, marginBottom: '10px' }}>OIDC Binding</div>
{selectedUser.oidc_subject ? (
<div style={{ marginBottom: 10 }}>
<div className="text-dim" style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
issuer: {selectedUser.oidc_issuer || '—'}<br />
subject: {selectedUser.oidc_subject}
</div>
<button className="btn-danger" style={{ marginTop: 10 }} disabled={saving} onClick={handleUnbindOidc}>
Unbind OIDC identity
</button>
</div>
) : (
<div className="text-dim" style={{ marginBottom: 10 }}>No OIDC identity bound.</div>
)}
<label>
Issuer
<input value={bindForm.issuer} placeholder="https://idp.example.com" onChange={(e) => setBindForm({ ...bindForm, issuer: e.target.value })} />
</label>
<label>
Subject (sub)
<input value={bindForm.subject} placeholder="OIDC subject claim" onChange={(e) => setBindForm({ ...bindForm, subject: e.target.value })} />
</label>
<button className="btn-secondary" style={{ marginTop: 10 }} disabled={saving || !bindForm.issuer.trim() || !bindForm.subject.trim()} onClick={handleBindOidc}>
{selectedUser.oidc_subject ? 'Rebind OIDC identity' : 'Bind OIDC identity'}
</button>
</div>
)}
</div>
</>
) : (

View File

@@ -7,6 +7,8 @@ export interface User {
is_active: boolean
role_id: number | null
role_name: string | null
oidc_issuer?: string | null
oidc_subject?: string | null
created_at: string
}