[bc20307] | 1 | import axios from 'axios';
|
---|
| 2 | import { useEffect, useState } from 'react';
|
---|
| 3 | import { useLocation } from 'react-router-dom';
|
---|
| 4 | import jwt from 'jwt-decode';
|
---|
| 5 |
|
---|
| 6 | const useFindUser = ({ setAlert }) => {
|
---|
| 7 | const [user, setUser] = useState(null);
|
---|
| 8 | const [isLoading, setIsLoading] = useState(true);
|
---|
| 9 | const location = useLocation();
|
---|
| 10 | const findUser = async () => {
|
---|
| 11 | let token = localStorage.getItem('token');
|
---|
| 12 | try {
|
---|
| 13 | if (!token) throw Error();
|
---|
| 14 | token = JSON.parse(token);
|
---|
| 15 | } catch (err) {
|
---|
| 16 | if (
|
---|
| 17 | location.state === undefined &&
|
---|
| 18 | location.pathname !== '/' &&
|
---|
| 19 | location.pathname !== '/login-guest' &&
|
---|
| 20 | location.pathname !== '/login' &&
|
---|
| 21 | location.pathname !== '/register'
|
---|
| 22 | ) {
|
---|
| 23 | setAlert({
|
---|
| 24 | type: 'error',
|
---|
| 25 | msg: 'Не Сте Логирани!', // TODO change msg to err.message
|
---|
| 26 | });
|
---|
| 27 | }
|
---|
| 28 | setIsLoading(false);
|
---|
| 29 | return;
|
---|
| 30 | }
|
---|
| 31 | axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
---|
| 32 |
|
---|
| 33 | await axios
|
---|
| 34 | .get(`/testToken`)
|
---|
| 35 | .then((res) => {
|
---|
| 36 | if(res.status !== 200) throw new Error('Invalid token!');
|
---|
| 37 | const user = jwt(token);
|
---|
| 38 | setUser({
|
---|
| 39 | firstName: user.fullName.split(' ')[0] ?? '',
|
---|
| 40 | lastName: user.fullName.split(' ')[1] ?? '',
|
---|
| 41 | role: user.roles[0] ?? '',
|
---|
| 42 | id: user.id,
|
---|
| 43 | });
|
---|
| 44 | })
|
---|
| 45 | .catch((err) => {
|
---|
| 46 | localStorage.clear();
|
---|
| 47 | if (
|
---|
| 48 | location.state === undefined &&
|
---|
| 49 | location.pathname !== '/' &&
|
---|
| 50 | location.pathname !== '/login-guest' &&
|
---|
| 51 | location.pathname !== '/register'
|
---|
| 52 | ) {
|
---|
| 53 | setAlert({
|
---|
| 54 | type: 'error',
|
---|
| 55 | msg: 'Не Сте Логирани!', // TODO change msg to err.message
|
---|
| 56 | });
|
---|
| 57 | }
|
---|
| 58 | })
|
---|
| 59 | .finally(() => {
|
---|
| 60 | setIsLoading(false);
|
---|
| 61 | });
|
---|
| 62 | };
|
---|
| 63 | useEffect(() => {
|
---|
| 64 | findUser();
|
---|
| 65 | }, []);
|
---|
| 66 |
|
---|
| 67 | return {
|
---|
| 68 | user,
|
---|
| 69 | setUser,
|
---|
| 70 | isLoading,
|
---|
| 71 | };
|
---|
| 72 | };
|
---|
| 73 |
|
---|
| 74 | export default useFindUser;
|
---|