Scaffold full-stack volunteer scheduling application
Go backend with domain-based packages (volunteer, schedule, timeoff, checkin, notification), SQLite storage, JWT auth, and chi router. React TypeScript frontend with routing, auth context, and pages for all core features. Multi-stage Dockerfile and docker-compose included. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
59
web/src/auth.tsx
Normal file
59
web/src/auth.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
|
||||
interface AuthContextValue {
|
||||
token: string | null;
|
||||
role: string | null;
|
||||
volunteerID: number | null;
|
||||
login: (token: string) => void;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
function parseJWT(token: string): { volunteer_id: number; role: string } | null {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
return payload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
|
||||
const [role, setRole] = useState<string | null>(null);
|
||||
const [volunteerID, setVolunteerID] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
const payload = parseJWT(token);
|
||||
setRole(payload?.role ?? null);
|
||||
setVolunteerID(payload?.volunteer_id ?? null);
|
||||
} else {
|
||||
setRole(null);
|
||||
setVolunteerID(null);
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
function login(t: string) {
|
||||
localStorage.setItem('token', t);
|
||||
setToken(t);
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('token');
|
||||
setToken(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ token, role, volunteerID, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
Reference in New Issue
Block a user