feat: implementar autenticação com token e refatorar serviços de métricas
parent
cb01415dfa
commit
5dfe4570e6
|
|
@ -1,12 +1,10 @@
|
|||
import { Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { LoginSlide } from './views/components/login-slide';
|
||||
import { RetrospectiveSlides } from './views/components/retrospective-slides';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/" element={<LoginSlide />} />
|
||||
<Route path="/retrospectiva" element={<RetrospectiveSlides />} />
|
||||
<Route path="/:token" element={<RetrospectiveSlides />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
export const localStorageKeys = {
|
||||
ACCESS_TOKEN: '@review:token',
|
||||
};
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { api } from '@/app/services';
|
||||
import { createContext, useCallback, useContext, useState } from 'react';
|
||||
import { localStorageKeys } from '../config/local-storage-keys';
|
||||
|
||||
type AuthState = {
|
||||
token: string;
|
||||
};
|
||||
|
||||
type AuthContextValue = {
|
||||
signedIn: boolean;
|
||||
authenticate(token: string): void;
|
||||
signOut(): void;
|
||||
};
|
||||
|
||||
export const AuthContext = createContext({} as AuthContextValue);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [isSignedIn, setIsSignedIn] = useState<boolean>(false);
|
||||
|
||||
const [, setAuthState] = useState<AuthState>(() => {
|
||||
const token = localStorage.getItem(localStorageKeys.ACCESS_TOKEN);
|
||||
|
||||
if (token) {
|
||||
api.defaults.headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
setIsSignedIn(true);
|
||||
return { token };
|
||||
}
|
||||
|
||||
return {} as AuthState;
|
||||
});
|
||||
|
||||
const authenticate = useCallback((token: string) => {
|
||||
try {
|
||||
localStorage.setItem(localStorageKeys.ACCESS_TOKEN, token);
|
||||
|
||||
api.defaults.headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
setIsSignedIn(true);
|
||||
setAuthState({ token });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const signOut = useCallback(() => {
|
||||
localStorage.removeItem(localStorageKeys.ACCESS_TOKEN);
|
||||
|
||||
setIsSignedIn(false);
|
||||
|
||||
setAuthState({} as AuthState);
|
||||
|
||||
api.defaults.headers.Authorization = '';
|
||||
api.defaults.headers['Cache-Control'] = 'no-cache';
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
signedIn: isSignedIn,
|
||||
authenticate,
|
||||
signOut,
|
||||
}}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
|
@ -1,18 +1,18 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { metricsService } from '../services/metrics';
|
||||
|
||||
export function useMetricsByPortal(cpf: string, ano: number) {
|
||||
export function useMetricsByPortal(ano: number) {
|
||||
return useQuery({
|
||||
queryKey: ['metricsByPortal', cpf, ano],
|
||||
queryFn: () => metricsService.getMetricsByPortal({ cpf, ano }),
|
||||
enabled: !!cpf && !!ano,
|
||||
queryKey: ['metricsByPortal', ano],
|
||||
queryFn: () => metricsService.getMetricsByPortal({ ano }),
|
||||
enabled: !!ano,
|
||||
});
|
||||
}
|
||||
|
||||
export function useMetricsBySystems(cpf: string, ano: number) {
|
||||
export function useMetricsBySystems(ano: number) {
|
||||
return useQuery({
|
||||
queryKey: ['metricsBySystems', cpf, ano],
|
||||
queryFn: () => metricsService.getMetricsBySystems({ cpf, ano }),
|
||||
enabled: !!cpf && !!ano,
|
||||
queryKey: ['metricsBySystems', ano],
|
||||
queryFn: () => metricsService.getMetricsBySystems({ ano }),
|
||||
enabled: !!ano,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,10 +6,12 @@ const api = axios.create({
|
|||
baseURL: import.meta.env.VITE_API_URL,
|
||||
});
|
||||
|
||||
// Adicionar token temporariamente aos headers
|
||||
const token = import.meta.env.VITE_API_TOKEN || '';
|
||||
if (token) {
|
||||
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||
export function setAuthToken(newToken: string | null) {
|
||||
if (newToken) {
|
||||
api.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
|
||||
} else {
|
||||
delete api.defaults.headers.common['Authorization'];
|
||||
}
|
||||
}
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
|
|
|
|||
|
|
@ -8,15 +8,13 @@ type MetricsByPortalProps = {
|
|||
|
||||
type GetMetricsByPortalParams = {
|
||||
ano: number;
|
||||
cpf: string;
|
||||
};
|
||||
|
||||
export async function getMetricsByPortal({
|
||||
ano,
|
||||
cpf,
|
||||
}: GetMetricsByPortalParams): Promise<MetricsByPortalProps[]> {
|
||||
const { data } = await api.get(
|
||||
`/userAccessMetricsByPortal?ano=${ano}&cpf=${cpf}`,
|
||||
`/userAccessMetricsByPortal?ano=${ano}`,
|
||||
);
|
||||
|
||||
return data;
|
||||
|
|
|
|||
|
|
@ -8,16 +8,12 @@ type MetricsBySystemsProps = {
|
|||
|
||||
type GetMetricsBySystemsParams = {
|
||||
ano: number;
|
||||
cpf: string;
|
||||
};
|
||||
|
||||
export async function getMetricsBySystems({
|
||||
ano,
|
||||
cpf,
|
||||
}: GetMetricsBySystemsParams): Promise<MetricsBySystemsProps[]> {
|
||||
const { data } = await api.get(
|
||||
`/userAccessMetricsBySystem?ano=${ano}&cpf=${cpf}`,
|
||||
);
|
||||
const { data } = await api.get(`/userAccessMetricsBySystem?ano=${ano}`);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,13 +14,16 @@ import { ptBR } from 'date-fns/locale';
|
|||
setDefaultOptions({ locale: ptBR });
|
||||
|
||||
import '@/styles/index.css';
|
||||
import { AuthProvider } from './app/hooks/use-auth';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<BrowserRouter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
<AuthProvider>
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
</AuthProvider>
|
||||
</QueryClientProvider>
|
||||
</BrowserRouter>,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
/* eslint-disable react-hooks/rules-of-hooks */
|
||||
import { useAuth } from '@/app/hooks/use-auth';
|
||||
import {
|
||||
useMetricsByPortal,
|
||||
useMetricsBySystems,
|
||||
|
|
@ -6,28 +8,50 @@ import logoAImg from '@/assets/images/a-agape.png';
|
|||
import logoImg from '@/assets/images/agape-logo.png';
|
||||
import { ChartLineUpIcon, SpinnerIcon } from '@phosphor-icons/react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useEffect } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import ProfileCard from './ProfileCard';
|
||||
import { StorySlide } from './story-slide';
|
||||
|
||||
export function RetrospectiveSlides() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const cpf = searchParams.get('cpf') || '';
|
||||
const ano = searchParams.get('ano')
|
||||
? parseInt(searchParams.get('ano')!)
|
||||
: new Date().getFullYear();
|
||||
const { token } = useParams();
|
||||
const { authenticate } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
authenticate(token);
|
||||
}
|
||||
}, [token, authenticate]);
|
||||
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
if (!token) {
|
||||
return (
|
||||
<div className="h-screen w-full bg-black flex items-center justify-center">
|
||||
<div className="text-center space-y-4 max-w-md">
|
||||
<p className="text-white text-lg font-semibold">
|
||||
Token inválido ou ausente
|
||||
</p>
|
||||
<p className="text-white/70">
|
||||
Esta aplicação deve ser acessada com o parâmetro <code>token</code>{' '}
|
||||
na URL. Exemplo: <code>?token=SEU_TOKEN&cpf=00000000000</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
data: metricsPortal,
|
||||
isLoading: isLoadingPortal,
|
||||
error: errorPortal,
|
||||
} = useMetricsByPortal(cpf, ano);
|
||||
} = useMetricsByPortal(year);
|
||||
|
||||
const {
|
||||
data: metricsSystems,
|
||||
isLoading: isLoadingSystems,
|
||||
error: errorSystems,
|
||||
} = useMetricsBySystems(cpf, ano);
|
||||
} = useMetricsBySystems(year);
|
||||
|
||||
const slides: number[] = [];
|
||||
slides.push(0);
|
||||
|
|
@ -108,7 +132,7 @@ export function RetrospectiveSlides() {
|
|||
transition={{ duration: 0.6, delay: 0.2 }}>
|
||||
Sua Retrospectiva
|
||||
<br />
|
||||
Ágape {ano}
|
||||
Ágape {year}
|
||||
</motion.h1>
|
||||
|
||||
<motion.p
|
||||
|
|
@ -139,12 +163,7 @@ export function RetrospectiveSlides() {
|
|||
|
||||
{metricsPortal && metricsPortal.length > 0 && (
|
||||
<>
|
||||
<StorySlide className="bg-white text-gray-900 overflow-hidden relative">
|
||||
<div className="absolute inset-0 overflow-hidden">
|
||||
<div className="absolute -top-24 -right-24 w-96 h-96 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-full opacity-70"></div>
|
||||
<div className="absolute -bottom-32 -left-32 w-80 h-80 bg-gradient-to-tr from-blue-50 to-cyan-50 rounded-full opacity-60"></div>
|
||||
</div>
|
||||
|
||||
<StorySlide className="bg-linear-to-br from-slate-50 to-blue-50">
|
||||
<div className="max-w-7xl mx-auto w-full h-full px-6 py-8 md:py-16 relative z-10">
|
||||
<div className="flex flex-col lg:flex-row items-center justify-between h-full">
|
||||
<motion.div
|
||||
|
|
@ -201,7 +220,7 @@ export function RetrospectiveSlides() {
|
|||
|
||||
<div className="flex flex-col">
|
||||
<span className="text-lg md:text-xl text-muted-foreground">
|
||||
Acessos em {ano}
|
||||
Acessos em {year}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -301,7 +320,8 @@ export function RetrospectiveSlides() {
|
|||
}}>
|
||||
<p className="text-xl md:text-2xl font-bold text-yellow-300 mb-1">
|
||||
{(
|
||||
(item.totalAcessos / (totalAcessos || 1)) *
|
||||
(item.totalAcessos /
|
||||
(totalAcessos || 1)) *
|
||||
100
|
||||
).toFixed(0)}
|
||||
%
|
||||
|
|
@ -349,7 +369,7 @@ export function RetrospectiveSlides() {
|
|||
</motion.div>
|
||||
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-[#0e233d]">
|
||||
A Ágape deseja a você um {ano + 1} repleto de sucesso!
|
||||
{'<'} O futuro é programado aqui! Feliz {year + 1}! {'/>'}
|
||||
</h2>
|
||||
|
||||
<p className="text-xl text-muted-foreground max-w-xl">
|
||||
|
|
@ -365,7 +385,7 @@ export function RetrospectiveSlides() {
|
|||
whileInView={{ opacity: 1 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.6, delay: 0.4 }}>
|
||||
<p>© {ano} Ágape Sistemas e Tecnologia</p>
|
||||
<p>© {year} Ágape Sistemas e Tecnologia</p>
|
||||
<p className="mt-2">
|
||||
O Futuro da Gestão Pública começa aqui!
|
||||
</p>
|
||||
|
|
|
|||
Loading…
Reference in New Issue