- Rename frontend workspaces: whm/ → nixserver/, cpanel/ → nixclient/ - Rename server route dirs: routes/whm/ → routes/nixserver/, routes/cpanel/ → routes/nixclient/ - Update all API prefixes: /api/whm → /api/nixserver, /api/cpanel → /api/nixclient - Rename env vars: WHM_PORT → NIXSERVER_PORT, CPANEL_PORT → NIXCLIENT_PORT - Update config properties: whmPort → nixserverPort, cpanelPort → nixclientPort - Update all UI labels, login pages, sidebar branding, and error messages - Update installer and update scripts to match new names - Add cpanel email route (missing from initial scaffold) - Add .gitattributes to enforce LF line endings - Bump version to 0.2.0 across all package.json files
73 lines
2.1 KiB
TypeScript
73 lines
2.1 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
|
import { api } from '../api/client'
|
|
|
|
interface User {
|
|
id: number
|
|
username: string
|
|
email: string
|
|
role: 'admin' | 'reseller'
|
|
}
|
|
|
|
interface AuthContextValue {
|
|
user: User | null
|
|
loading: boolean
|
|
login: (username: string, password: string) => Promise<void>
|
|
logout: () => Promise<void>
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextValue | null>(null)
|
|
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
const [user, setUser] = useState<User | null>(null)
|
|
const [loading, setLoading] = useState(true)
|
|
|
|
const fetchMe = useCallback(async () => {
|
|
const token = localStorage.getItem('access_token')
|
|
if (!token) { setLoading(false); return }
|
|
try {
|
|
const { data } = await api.get('/auth/me')
|
|
if (data.data.role !== 'admin' && data.data.role !== 'reseller') {
|
|
localStorage.clear()
|
|
setLoading(false)
|
|
return
|
|
}
|
|
setUser(data.data)
|
|
} catch {
|
|
localStorage.clear()
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}, [])
|
|
|
|
useEffect(() => { fetchMe() }, [fetchMe])
|
|
|
|
const login = async (username: string, password: string) => {
|
|
const { data } = await api.post('/auth/login', { username, password })
|
|
if (data.data.role !== 'admin' && data.data.role !== 'reseller') {
|
|
throw new Error('Access denied — NixServer is for administrators and resellers only')
|
|
}
|
|
localStorage.setItem('access_token', data.data.accessToken)
|
|
localStorage.setItem('refresh_token', data.data.refreshToken)
|
|
setUser(data.data.user)
|
|
}
|
|
|
|
const logout = async () => {
|
|
const refreshToken = localStorage.getItem('refresh_token')
|
|
try { await api.post('/auth/logout', { refreshToken }) } catch {}
|
|
localStorage.clear()
|
|
setUser(null)
|
|
}
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useAuth() {
|
|
const ctx = useContext(AuthContext)
|
|
if (!ctx) throw new Error('useAuth must be used inside AuthProvider')
|
|
return ctx
|
|
}
|