- Login: RUT-based (SAM auth) instead of email - API client: updated all endpoints to /api/helpdesk/* - Types: match SAM response format (nombre, apPaterno, perfil) - Dashboard: uses new DashboardStats with dailyCounts - Tickets: title instead of subject, requesterName/assigneeName - KB: categoryName/authorName instead of nested objects - Removed register page (SAM manages users)
64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
"use client";
|
|
|
|
import React, { createContext, useContext, useState, useEffect, useCallback } from "react";
|
|
import { getMe, login as apiLogin, type User } from "./api";
|
|
|
|
interface AuthContextType {
|
|
user: User | null;
|
|
login: (rut: string, password: string) => Promise<void>;
|
|
logout: () => void;
|
|
isAuthenticated: boolean;
|
|
isLoading: boolean;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType>({
|
|
user: null,
|
|
login: async () => {},
|
|
logout: () => {},
|
|
isAuthenticated: false,
|
|
isLoading: true,
|
|
});
|
|
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
const token = localStorage.getItem("helpdesk_token");
|
|
if (token) {
|
|
getMe()
|
|
.then((u) => setUser(u))
|
|
.catch(() => localStorage.removeItem("helpdesk_token"))
|
|
.finally(() => setIsLoading(false));
|
|
} else {
|
|
setIsLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
const login = useCallback(async (rut: string, password: string) => {
|
|
const result = await apiLogin(rut, password);
|
|
if (!result.success || !result.token) {
|
|
throw new Error(result.message || "Credenciales inválidas");
|
|
}
|
|
localStorage.setItem("helpdesk_token", result.token);
|
|
if (result.user) setUser(result.user);
|
|
}, []);
|
|
|
|
const logout = useCallback(() => {
|
|
localStorage.removeItem("helpdesk_token");
|
|
setUser(null);
|
|
}, []);
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{ user, login, logout, isAuthenticated: !!user, isLoading }}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useAuth() {
|
|
return useContext(AuthContext);
|
|
}
|