Skip to content

Commit

Permalink
Merge pull request #44 from fga-eps-mds/feat/ENH005
Browse files Browse the repository at this point in the history
Feat/enh005
  • Loading branch information
muriloschiler authored Sep 16, 2024
2 parents 4d13aab + 70ed132 commit e6a4328
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 13 deletions.
52 changes: 43 additions & 9 deletions src/shared/contexts/Auth/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const AuthContext = createContext<authContextType>(authContextDefaultValu
export const AuthProvider = ({ children }: { children: JSX.Element }) => {
const [loading, setLoading] = useState<'loading' | 'loaded'>('loading');
const router = useRouter();
const hasExecuted = useRef(false)
const hasExecuted = useRef(false);
const {
storedValue: session,
setValue: setSession,
Expand All @@ -38,7 +38,6 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
removeValue: removeProvider
} = useLocalStorage<Providers>('provider', 'credentials');


const removeAuthStorage = useCallback(async () => {
removeSession();
removeToken();
Expand Down Expand Up @@ -73,7 +72,6 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {

const signInWithGithub = useCallback(
async (code: string): Promise<Result<User>> => {

const response = await signInGithub(code);

if (response.type === 'success' && response?.value?.key) {
Expand All @@ -90,7 +88,7 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
email: '',
avatar_url: '',
repos_url: '',
organizations_url: '',
organizations_url: ''
}
};
}
Expand All @@ -106,7 +104,6 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
[removeAuthStorage, setToken]
);


const signInWithCredentials = useCallback(
async (data: LoginFormData): Promise<Result<User>> => {
setProvider('credentials');
Expand All @@ -117,7 +114,8 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
toast.success('Login realizado com sucesso!');
await router.push('/home');
return response;
} if (response.type === 'error') {
}
if (response.type === 'error') {
toast.error(`Erro ao realizar login: ${response.error.message === 'Request failed with status code 400' ? 'Erro nas credenciais' : response.error.message || 'Erro desconhecido'}`);
return response;
}
Expand All @@ -127,12 +125,48 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
[router, setProvider, setToken]
);

// Função para monitorar inatividade
const INACTIVITY_TIME = 3 * 60 * 1000;

useEffect(() => {
let logoutTimer: NodeJS.Timeout;

const resetLogoutTimer = () => {
if (logoutTimer) {
clearTimeout(logoutTimer);
}

logoutTimer = setTimeout(() => {
console.log(session);
console.log(token);
if (session != null || token != null) {
logout();
toast.warning('Você foi desconectado por inatividade.');
}
}, INACTIVITY_TIME);
};

const activityEvents = ['mousemove', 'keydown', 'mousedown', 'touchstart'];

activityEvents.forEach((event) =>
window.addEventListener(event, resetLogoutTimer)
);

resetLogoutTimer(); // Inicia o timer ao montar o componente

return () => {
activityEvents.forEach((event) =>
window.removeEventListener(event, resetLogoutTimer)
);
clearTimeout(logoutTimer); // Limpa o timer quando o componente é desmontado
};
}, [logout]);

useEffect(() => {
const params = new URLSearchParams(window.location.search)
const code = params.get('code')
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
if (code && provider === 'github' && !token && !hasExecuted.current) {
hasExecuted.current = true
hasExecuted.current = true;
signInWithGithub(code as string);
}
}, [provider, token, signInWithGithub]);
Expand Down
9 changes: 5 additions & 4 deletions src/shared/hooks/useLocalStorage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,22 +46,23 @@ export function useLocalStorage<T>(
}
};

/* eslint consistent-return: off */
// Function to remove value from local storage and update state
const removeValue = () => {
if (typeof window === 'undefined') {
return initialValue;
return;
}

localStorage.removeItem(key);
setStoredValue(initialValue); // Update state to initial value
window.dispatchEvent(new Event('local-storage'));
};

useEffect(() => {
try {
const item = window.localStorage.getItem(key);
setStoredValue(item ? JSON.parse(item) : initialValue);
} catch (error) {

return setStoredValue(initialValue);
setStoredValue(initialValue);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Expand Down

0 comments on commit e6a4328

Please sign in to comment.