From 81b46581ab79f8f5e9e132e00e5d1b8e9182dd46 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sun, 15 Nov 2020 04:07:33 +0300 Subject: feat: implement authentication --- src/hooks/APIClient.ts | 8 +++-- src/hooks/useAuth.tsx | 70 ++++++++++++++++++++++++++++++++++++++++++++ src/hooks/useLocalStorage.ts | 20 +++++++++++++ 3 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 src/hooks/useAuth.tsx create mode 100644 src/hooks/useLocalStorage.ts (limited to 'src/hooks') diff --git a/src/hooks/APIClient.ts b/src/hooks/APIClient.ts index d3c4542..015191c 100644 --- a/src/hooks/APIClient.ts +++ b/src/hooks/APIClient.ts @@ -6,9 +6,11 @@ type Response = responseInterface; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); - -export const useUser = (id: string): Response => { - return useSWR(id && `/users/${id}`, fetcher); +export const useUser = (username: string | null): Response => { + return useSWR( + username && `/users?username=${username}`, + (url: string) => get(url).then(response => response.data[0]) + ); }; export const useEvents = (): Response => { diff --git a/src/hooks/useAuth.tsx b/src/hooks/useAuth.tsx new file mode 100644 index 0000000..39351ae --- /dev/null +++ b/src/hooks/useAuth.tsx @@ -0,0 +1,70 @@ +import React, { + useEffect, useCallback, useMemo, useContext, createContext +} from 'react'; +import { User } from '../types'; +import { post } from '../requests'; +import { useUser } from './APIClient'; +import useLocalStorage from './useLocalStorage'; + + +interface ContextType { + user: User | undefined, + login: (username: string, password: string, remember?: boolean) => Promise; + logout: () => void; + isAuthenticated: boolean; +} + +const authContext = createContext({ + user: undefined, + login: async () => false, + logout: () => {}, + isAuthenticated: false +}); + +const useProvideAuth = () => { + const [remember, setRemember] = useLocalStorage('remember'); + const [username, setUsername] = useLocalStorage('username'); + const [token, setToken] = useLocalStorage('token'); + const { data: user } = useUser(username); + + const isAuthenticated = useMemo(() => Boolean(username), [username]); + + const logout = useCallback(() => { + setToken(null); + setUsername(null); + }, [setToken, setUsername]); + + useEffect(() => { + // If should not remember, logout + if (!remember) logout(); + }, [remember, logout]); + + + const login: ContextType['login'] = (name, password, shouldRemember = true) => { + return post('/authentication', { + strategy: 'local', + username: name, + password + }).then(response => { + setToken(response.data.accessToken); + setUsername(name); + setRemember(shouldRemember ? 'true' : null); + return true; + }).catch(() => false); + }; + + return { + user, login, logout, token, isAuthenticated + }; +}; + +export const AuthProvider: React.FC = ({ children }) => { + const auth = useProvideAuth(); + const { Provider } = authContext; + return {children}; +}; + +export const useAuth = (): ContextType => { + return useContext(authContext); +}; + diff --git a/src/hooks/useLocalStorage.ts b/src/hooks/useLocalStorage.ts new file mode 100644 index 0000000..a604ebe --- /dev/null +++ b/src/hooks/useLocalStorage.ts @@ -0,0 +1,20 @@ +import { useState, useCallback } from 'react'; + +type Value = string | null; +type Setter = (value: Value) => void; + +const useLocalStorage = (key: string): [Value, Setter] => { + const [state, setState] = useState(() => localStorage.getItem(key) || null); + + const update: Setter = useCallback(value => { + if (value) localStorage.setItem(key, value); + else localStorage.removeItem(key); + setState(value); + }, [key]); + + return [state, update]; +}; + + +export default useLocalStorage; + -- cgit v1.2.3