aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/useAuth.tsx
diff options
context:
space:
mode:
authoreug-vs <eug-vs@keemail.me>2020-06-29 23:59:15 +0300
committereug-vs <eug-vs@keemail.me>2020-06-29 23:59:15 +0300
commit1f646377c35b65b97d6eeebb1e88f6d8307e1ef0 (patch)
tree56fbda6b594350656891644734d0bf740bfcbb0d /src/hooks/useAuth.tsx
parentb301bf24c5037403a1e5fc32fc8c10794941b528 (diff)
downloadwhich-ui-1f646377c35b65b97d6eeebb1e88f6d8307e1ef0.tar.gz
feat!: create useAuth hook
Diffstat (limited to 'src/hooks/useAuth.tsx')
-rw-r--r--src/hooks/useAuth.tsx75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/hooks/useAuth.tsx b/src/hooks/useAuth.tsx
new file mode 100644
index 0000000..4f76593
--- /dev/null
+++ b/src/hooks/useAuth.tsx
@@ -0,0 +1,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);
+}
+