Files
nuzlocke-tracker/frontend/src/contexts/AuthContext.tsx
Julian Tabel e8ded9184b
All checks were successful
CI / backend-tests (push) Successful in 32s
CI / frontend-tests (push) Successful in 29s
feat: auth-aware UI and role-based access control (#67)
## Summary

- Add `is_admin` column to users table with Alembic migration and a `require_admin` FastAPI dependency that protects all admin-facing write endpoints (games, pokemon, evolutions, bosses, routes CRUD)
- Expose admin status to frontend via user API and update AuthContext to fetch/store `isAdmin` after login
- Make navigation menu auth-aware (different links for logged-out, logged-in, and admin users) and protect frontend routes with `ProtectedRoute` and `AdminRoute` components, preserving deep-linking through redirects
- Fix test reliability: `drop_all` before `create_all` to clear stale PostgreSQL enums from interrupted test runs
- Fix test auth: add `admin_client` fixture and use valid UUID for mock user so tests pass with new admin-protected endpoints

## Test plan

- [x] All 252 backend tests pass
- [ ] Verify non-admin users cannot access admin write endpoints (games, pokemon, evolutions, bosses CRUD)
- [ ] Verify admin users can access admin endpoints normally
- [ ] Verify navigation shows correct links for logged-out, logged-in, and admin states
- [ ] Verify `/admin/*` routes redirect non-admin users with a toast
- [ ] Verify `/runs/new` and `/genlockes/new` redirect unauthenticated users to login, then back after auth

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #67
Co-authored-by: Julian Tabel <juliantabel.jt@gmail.com>
Co-committed-by: Julian Tabel <juliantabel.jt@gmail.com>
2026-03-21 11:44:05 +01:00

116 lines
3.3 KiB
TypeScript

import { createContext, useContext, useEffect, useState, useCallback, useMemo } from 'react'
import type { User, Session, AuthError } from '@supabase/supabase-js'
import { supabase } from '../lib/supabase'
import { api } from '../api/client'
interface UserProfile {
id: string
email: string
displayName: string | null
isAdmin: boolean
}
interface AuthState {
user: User | null
session: Session | null
loading: boolean
isAdmin: boolean
}
interface AuthContextValue extends AuthState {
signInWithEmail: (email: string, password: string) => Promise<{ error: AuthError | null }>
signUpWithEmail: (email: string, password: string) => Promise<{ error: AuthError | null }>
signInWithGoogle: () => Promise<{ error: AuthError | null }>
signInWithDiscord: () => Promise<{ error: AuthError | null }>
signOut: () => Promise<void>
}
const AuthContext = createContext<AuthContextValue | null>(null)
async function syncUserProfile(session: Session | null): Promise<boolean> {
if (!session) return false
try {
const profile = await api.post<UserProfile>('/users/me', {})
return profile.isAdmin
} catch {
return false
}
}
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState<AuthState>({
user: null,
session: null,
loading: true,
isAdmin: false,
})
useEffect(() => {
supabase.auth.getSession().then(async ({ data: { session } }) => {
const isAdmin = await syncUserProfile(session)
setState({ user: session?.user ?? null, session, loading: false, isAdmin })
})
const {
data: { subscription },
} = supabase.auth.onAuthStateChange(async (_event, session) => {
const isAdmin = await syncUserProfile(session)
setState({ user: session?.user ?? null, session, loading: false, isAdmin })
})
return () => subscription.unsubscribe()
}, [])
const signInWithEmail = useCallback(async (email: string, password: string) => {
const { error } = await supabase.auth.signInWithPassword({ email, password })
return { error }
}, [])
const signUpWithEmail = useCallback(async (email: string, password: string) => {
const { error } = await supabase.auth.signUp({ email, password })
return { error }
}, [])
const signInWithGoogle = useCallback(async () => {
const { error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: { redirectTo: `${window.location.origin}/auth/callback` },
})
return { error }
}, [])
const signInWithDiscord = useCallback(async () => {
const { error } = await supabase.auth.signInWithOAuth({
provider: 'discord',
options: { redirectTo: `${window.location.origin}/auth/callback` },
})
return { error }
}, [])
const signOut = useCallback(async () => {
await supabase.auth.signOut()
}, [])
const value = useMemo(
() => ({
...state,
signInWithEmail,
signUpWithEmail,
signInWithGoogle,
signInWithDiscord,
signOut,
}),
[state, signInWithEmail, signUpWithEmail, signInWithGoogle, signInWithDiscord, signOut]
)
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export function useAuth() {
const context = useContext(AuthContext)
if (!context) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}