Files
riseup_squad_03/src/hooks/useAuth.js
letvb20-dot bb5200664a modified: src/App.jsx
modified:   src/components/AppShell.jsx
new file:   src/config/permissions.js
new file:   src/hooks/useAuth.js
new file:   src/pages/UsersPage.jsx
new file:   src/repositories/userRepository.js
2026-05-05 22:49:20 -03:00

56 lines
1.6 KiB
JavaScript

import { useEffect, useState } from 'react'
import { getAuthSession, saveAuthSession } from '../config/api.js'
import { authRepository } from '../repositories/authRepository.js'
export function useAuth() {
const [state, setState] = useState(() => {
const session = getAuthSession()
return {
user: session?.user ?? null,
role: session?.role ?? null,
profile: session?.profile ?? null,
isAuthenticated: !!session?.access_token,
loading: !!session?.access_token && !session?.role,
}
})
useEffect(() => {
// Se não está autenticado ou já tem role salvo, não busca
if (!state.isAuthenticated || state.role) {
setState((s) => ({ ...s, loading: false }))
return
}
let cancelled = false
authRepository
.getUser()
.then((data) => {
if (cancelled || !data) return
// Suporta diferentes formatos de resposta da API
const role =
Array.isArray(data.roles) ? data.roles[0]
: (data.role ?? data.user_metadata?.role ?? data.app_metadata?.role ?? null)
const profile = data.profile ?? null
const user = data.user ?? data ?? null
// Persiste na sessão para evitar nova busca a cada reload
const session = getAuthSession()
saveAuthSession({ ...session, role, profile, user: user || session?.user })
setState((s) => ({ ...s, role, profile, user: user || s.user, loading: false }))
})
.catch(() => {
if (!cancelled) setState((s) => ({ ...s, loading: false }))
})
return () => {
cancelled = true
}
}, [state.isAuthenticated, state.role])
return state
}