aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/useAuth.tsx
blob: 4f76593175005eb529370cda380815fa99eb6edc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import React, { useState, useEffect, useContext, createContext } from 'react';
import { User } from 'which-types';
import { post, get } from '../requests';


interface ContextType {
  user: User | null,
  setUser: (user: User) => void;
  login: (username: string, password: string, remember?: boolean) => Promise<boolean>;
  logout: () => void;
  isAuthenticated: () => boolean;
}

const authContext = createContext<ContextType>({
  user: null,
  setUser: () => {},
  login: async () => false,
  logout: () => {},
  isAuthenticated: () => false
});

const useProvideAuth = () => {
  const [user, setUser] = useState<User | null>(null);

  const login = (username: string, password: string, remember = true): Promise<boolean> => {
    return post('/authentication', {
      strategy: 'local',
      username,
      password
    }).then(response => {
      const me = response.data.user;
      const token = response.data.accessToken;
      setUser(me);
      // navigate('profile', me._id);
      localStorage.setItem('userId', me._id);
      localStorage.setItem('token', token);
      if (!remember) localStorage.setItem('shouldClear', 'true');
      return true;
    }).catch(() => false);
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('userId');
    localStorage.removeItem('token');
    // navigate('auth');
  };

  const isAuthenticated = () => Boolean(user);

  useEffect(() => {
    if (localStorage.getItem('shouldClear')) {
      localStorage.clear();
    }
    const userId = localStorage.getItem('userId');
    if (userId) {
      get(`/users/${userId}`).then(response => {
        setUser(response.data);
      });
    }
  }, []);

  return { user, setUser, login, logout, isAuthenticated };
};

export const AuthProvider: React.FC = ({ children }) => {
  const auth = useProvideAuth();
  const { Provider } = authContext;
  return <Provider value={auth}>{children}</Provider>
};

export const useAuth = () => {
  return useContext(authContext);
}