feat: complete Phases 2 to 5 inclusive - Access Core, Web Cockpit, Hardware enqueuing, Optical Scanner and QA (v0.5.0-beta)
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
// ==============================================================================
|
||||
// Contexto de Autenticación y Sesión de Operador
|
||||
// ==============================================================================
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import { UserSession } from '../types';
|
||||
import { authApi } from '../api/authApi';
|
||||
|
||||
interface AuthContextType {
|
||||
user: UserSession | null;
|
||||
workstation: string;
|
||||
setWorkstation: (name: string) => void;
|
||||
isAuthenticated: boolean;
|
||||
loading: boolean;
|
||||
login: (username: string, password: string, workstationName?: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [user, setUser] = useState<UserSession | null>(null);
|
||||
const [workstation, setWorkstationState] = useState<string>(() => {
|
||||
return localStorage.getItem('on_ever_workstation') || 'CFT-DESK';
|
||||
});
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
|
||||
const setWorkstation = (name: string) => {
|
||||
setWorkstationState(name);
|
||||
localStorage.setItem('on_ever_workstation', name);
|
||||
};
|
||||
|
||||
const checkSession = useCallback(async () => {
|
||||
try {
|
||||
const me = await authApi.getMe();
|
||||
setUser(me);
|
||||
} catch {
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkSession();
|
||||
}, [checkSession]);
|
||||
|
||||
const login = async (username: string, password: string, workstationName?: string) => {
|
||||
const targetWks = workstationName || workstation;
|
||||
const res = await authApi.login(username, password, targetWks);
|
||||
setUser(res.user);
|
||||
if (res.workstation) {
|
||||
setWorkstation(res.workstation);
|
||||
}
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await authApi.logout();
|
||||
} finally {
|
||||
setUser(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
workstation,
|
||||
setWorkstation,
|
||||
isAuthenticated: !!user,
|
||||
loading,
|
||||
login,
|
||||
logout,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user