feat: multi-user auth with per-user media isolation
Introduce username/password authentication with admin and user roles.
Each user gets their own media directory under /photos/{username}/ with
isolated photos, folders, heaps, and tags. Admins manage users and
observe the full library from a dedicated Settings page.
Backend:
- User model with bcrypt passwords and JWT access/refresh tokens
- Auth router (login, refresh, setup, change-password, status)
- Admin router (user CRUD with last-admin protection)
- user_id FK added to photos, folders, source_roots, heaps, tags
- All data routers scoped by authenticated user
- Scanner inherits user_id from source root owner
- Thumbnails stored under user-prefixed paths for isolation
- Library endpoints accept ?scope=global for admin cross-user view
- Alembic migration 0009 with data migration for existing installs
- Defensive bootstrap.py handles fresh vs existing DB startup
Frontend:
- AuthContext with token lifecycle, auto-refresh, login/logout
- Login page, first-run setup page, auth gate in App.tsx
- Bearer token interceptor on all API requests
- User identity + logout in left sidebar
- Admin-only Settings page with Library Management and Users tabs
- UserManagement panel (add, edit role, reset password, deactivate)
- Settings shows global stats across all users for admin
- Filter bar, right sidebar, keyboard hints hidden on settings page
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
170
frontend/src/contexts/AuthContext.tsx
Normal file
170
frontend/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,170 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
useRef,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import api from '../services/api'
|
||||
|
||||
export interface AuthUser {
|
||||
id: string
|
||||
username: string
|
||||
email: string | null
|
||||
role: 'admin' | 'user'
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
user: AuthUser | null
|
||||
isAdmin: boolean
|
||||
isLoading: boolean
|
||||
/** True when the backend has no users yet (first-run). */
|
||||
needsSetup: boolean
|
||||
login: (username: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
/** Called after the setup endpoint creates the first admin. */
|
||||
onSetupComplete: (accessToken: string, refreshToken: string) => Promise<void>
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null)
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
|
||||
// ── Token helpers ──────────────────────────────────────────────────────
|
||||
|
||||
function getStoredToken(): string | null {
|
||||
return localStorage.getItem('access_token')
|
||||
}
|
||||
|
||||
function storeToken(token: string) {
|
||||
localStorage.setItem('access_token', token)
|
||||
}
|
||||
|
||||
function clearToken() {
|
||||
localStorage.removeItem('access_token')
|
||||
}
|
||||
|
||||
// ── Provider ───────────────────────────────────────────────────────────
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<AuthUser | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [needsSetup, setNeedsSetup] = useState(false)
|
||||
// Keep refresh token in memory only (not localStorage).
|
||||
const refreshTokenRef = useRef<string | null>(null)
|
||||
const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const isAdmin = user?.role === 'admin'
|
||||
|
||||
// Schedule a token refresh ~5 min before expiry.
|
||||
const scheduleRefresh = useCallback((accessToken: string) => {
|
||||
try {
|
||||
const payload = JSON.parse(atob(accessToken.split('.')[1]))
|
||||
const expiresAt = payload.exp * 1000
|
||||
const refreshIn = Math.max(expiresAt - Date.now() - 5 * 60 * 1000, 10_000)
|
||||
|
||||
if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current)
|
||||
refreshTimerRef.current = setTimeout(async () => {
|
||||
if (!refreshTokenRef.current) return
|
||||
try {
|
||||
const res = await api.post('/auth/refresh', {
|
||||
refresh_token: refreshTokenRef.current,
|
||||
})
|
||||
const { access_token, refresh_token } = res.data
|
||||
storeToken(access_token)
|
||||
refreshTokenRef.current = refresh_token
|
||||
scheduleRefresh(access_token)
|
||||
} catch {
|
||||
// Refresh failed — force re-login.
|
||||
clearToken()
|
||||
refreshTokenRef.current = null
|
||||
setUser(null)
|
||||
}
|
||||
}, refreshIn)
|
||||
} catch {
|
||||
// Malformed token — ignore.
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fetchMe = useCallback(async () => {
|
||||
try {
|
||||
const res = await api.get('/auth/me')
|
||||
setUser(res.data)
|
||||
} catch {
|
||||
clearToken()
|
||||
setUser(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Boot: check if setup is needed, then try to restore session.
|
||||
useEffect(() => {
|
||||
;(async () => {
|
||||
try {
|
||||
const statusRes = await api.get('/auth/status')
|
||||
if (!statusRes.data.setup_completed) {
|
||||
setNeedsSetup(true)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Backend unreachable — fall through to login screen.
|
||||
}
|
||||
|
||||
const token = getStoredToken()
|
||||
if (token) {
|
||||
await fetchMe()
|
||||
scheduleRefresh(token)
|
||||
}
|
||||
setIsLoading(false)
|
||||
})()
|
||||
|
||||
return () => {
|
||||
if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current)
|
||||
}
|
||||
}, [fetchMe, scheduleRefresh])
|
||||
|
||||
const login = useCallback(
|
||||
async (username: string, password: string) => {
|
||||
const res = await api.post('/auth/login', { username, password })
|
||||
const { access_token, refresh_token } = res.data
|
||||
storeToken(access_token)
|
||||
refreshTokenRef.current = refresh_token
|
||||
scheduleRefresh(access_token)
|
||||
await fetchMe()
|
||||
},
|
||||
[fetchMe, scheduleRefresh],
|
||||
)
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearToken()
|
||||
refreshTokenRef.current = null
|
||||
if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current)
|
||||
setUser(null)
|
||||
}, [])
|
||||
|
||||
const onSetupComplete = useCallback(
|
||||
async (accessToken: string, refreshToken: string) => {
|
||||
storeToken(accessToken)
|
||||
refreshTokenRef.current = refreshToken
|
||||
setNeedsSetup(false)
|
||||
scheduleRefresh(accessToken)
|
||||
await fetchMe()
|
||||
},
|
||||
[fetchMe, scheduleRefresh],
|
||||
)
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{ user, isAdmin, isLoading, needsSetup, login, logout, onSetupComplete }}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user