HifiPlanet-Website/hifi-src/src/context/AuthContext.jsx
Maaxxs ec84b438ca PageSpeed/Lighthouse fixes: caching, images, touch targets, console noise
Based on a Lighthouse audit of the live site (95 performance / 91
accessibility / 96 best-practices / 100 SEO), addressing everything
except the flagged color-contrast issues (kept as-is, reversible
color changes need a separate decision):

- Cache-Control headers for hashed/immutable static assets via
  mod_headers (no mod_expires dependency, since that's not enabled
  everywhere) - ~1.1MB saved on repeat visits
- Converted the code-bundled homepage photos to WebP (skipped
  DB-managed/admin-uploaded images - those are content, not code) and
  added explicit width/height so the browser can reserve space before
  images load
- Bumped footer/contact-sidebar phone and email links to a 24px+
  touch target via padding
- /auth/me now returns 200 + {authenticated:false} instead of 401 for
  logged-out visitors - it's called on every public page load to
  check session state, so "not logged in" is the normal case, not an
  error; the 401 was showing up as a console error on literally every
  page view

Left unchanged: the lucide-react bundle splitting (a previous,
deliberate tradeoff - splitting per-icon created ~1600 tiny chunk
files that failed to upload on shared hosting) and video preload
(no concrete issue found in the audit).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-07 02:40:57 +02:00

54 lines
1.5 KiB
JavaScript

import { createContext, useContext, useEffect, useState } from 'react';
import { api } from '../api/client.js';
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
api
.get('/auth/me')
.then((data) => setUser(data.authenticated === false ? null : data))
.catch(() => setUser(null))
.finally(() => setLoading(false));
}, []);
const login = async (username, password) => {
const data = await api.post('/auth/login', { username, password });
if (data.requires_2fa) {
return { requires2fa: true };
}
setUser(data);
return { requires2fa: false };
};
const verifyTwoFactor = async (code) => {
const data = await api.post('/auth/verify-2fa', { code });
setUser(data);
};
const logout = async () => {
await api.post('/auth/logout', {});
setUser(null);
};
const refreshUser = async () => {
const data = await api.get('/auth/me');
setUser(data.authenticated === false ? null : data);
};
const hasPermission = (permission) =>
!!user && (user.is_super_admin || user.permissions?.includes(permission));
return (
<AuthContext.Provider value={{ user, loading, login, verifyTwoFactor, logout, refreshUser, hasPermission }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
return useContext(AuthContext);
}