| 2611 |
stevensc |
1 |
import React, { useEffect, useState } from 'react'
|
|
|
2 |
import { useDispatch, useSelector } from 'react-redux'
|
|
|
3 |
|
|
|
4 |
import { axios } from './utils'
|
| 2776 |
stevensc |
5 |
import { useFetch } from '@hooks'
|
| 2611 |
stevensc |
6 |
import { labelsAdapter } from './utils/labels'
|
|
|
7 |
import { setIntlLabels } from './redux/intl/intl.action'
|
|
|
8 |
import { logout, setPermissions } from './redux/auth/auth.actions'
|
|
|
9 |
|
|
|
10 |
import AppRoutes from './routes/routes'
|
|
|
11 |
import Spinner from './components/UI/Spinner'
|
|
|
12 |
import ErrorPage from './pages/error/error-page'
|
|
|
13 |
|
|
|
14 |
import './styles/globals.scss'
|
|
|
15 |
|
|
|
16 |
export default function App() {
|
|
|
17 |
const [loading, setLoading] = useState(true)
|
|
|
18 |
const [credentialsError, setCredentialsError] = useState(false)
|
|
|
19 |
const { data: labels } = useFetch('/language')
|
| 2803 |
stevensc |
20 |
const { isAuth } = useSelector(({ auth }) => auth)
|
| 2611 |
stevensc |
21 |
const dispatch = useDispatch()
|
|
|
22 |
|
|
|
23 |
const getCredentials = async () => {
|
|
|
24 |
const response = await axios.get('/signin')
|
|
|
25 |
const { data, success } = response.data
|
|
|
26 |
if (!success) throw new Error(data)
|
|
|
27 |
return data
|
|
|
28 |
}
|
|
|
29 |
|
|
|
30 |
const getUserCredentials = async () => {
|
|
|
31 |
setLoading(true)
|
|
|
32 |
getCredentials()
|
|
|
33 |
.then((credentials) => {
|
|
|
34 |
const localAes = window.localStorage.getItem('aes')
|
|
|
35 |
const localJwt = window.localStorage.getItem('jwt')
|
|
|
36 |
const permissions = structuredClone(credentials)
|
|
|
37 |
permissions.isAuth = credentials.is_logged_in
|
|
|
38 |
|
|
|
39 |
if (localAes) {
|
|
|
40 |
permissions.aes = localAes
|
|
|
41 |
} else {
|
|
|
42 |
permissions.aes = credentials.aes
|
|
|
43 |
window.localStorage.setItem('aes', credentials.aes)
|
|
|
44 |
}
|
|
|
45 |
|
|
|
46 |
if (localJwt) {
|
|
|
47 |
permissions.jwt = localJwt
|
|
|
48 |
} else {
|
|
|
49 |
permissions.jwt = credentials.jwt
|
|
|
50 |
window.localStorage.setItem('jwt', credentials.jwt)
|
|
|
51 |
}
|
|
|
52 |
|
|
|
53 |
dispatch(setPermissions(permissions))
|
|
|
54 |
})
|
|
|
55 |
.catch((error) => {
|
|
|
56 |
if (error.message.includes('sesión')) {
|
|
|
57 |
dispatch(logout())
|
|
|
58 |
getUserCredentials()
|
|
|
59 |
} else {
|
|
|
60 |
setCredentialsError(true)
|
|
|
61 |
}
|
|
|
62 |
})
|
|
|
63 |
.finally(() => setLoading(false))
|
|
|
64 |
}
|
|
|
65 |
|
|
|
66 |
useEffect(() => {
|
|
|
67 |
getUserCredentials()
|
|
|
68 |
}, [isAuth])
|
|
|
69 |
|
|
|
70 |
useEffect(() => {
|
|
|
71 |
dispatch(setIntlLabels(labelsAdapter(labels)))
|
|
|
72 |
}, [labels])
|
|
|
73 |
|
|
|
74 |
if (loading) {
|
|
|
75 |
return <Spinner />
|
|
|
76 |
}
|
|
|
77 |
|
|
|
78 |
if (credentialsError) {
|
|
|
79 |
return <ErrorPage />
|
|
|
80 |
}
|
|
|
81 |
|
| 2803 |
stevensc |
82 |
return <AppRoutes />
|
| 2611 |
stevensc |
83 |
}
|