auth
This commit is contained in:
parent
9b3381bfe6
commit
a0797c7e59
|
|
@ -2,22 +2,33 @@ import { BrowserRouter, Navigate, Outlet, Route, Routes } from 'react-router-dom
|
||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
import Login from './routes/login';
|
import Login from './routes/login';
|
||||||
import Home from './routes/home';
|
import Home from './routes/home';
|
||||||
import { checkAuth } from './controllers/Auth';
|
import { ProvideAuth } from './controllers/Auth';
|
||||||
import { CookiesProvider } from 'react-cookie';
|
import { Cookies, CookiesProvider, useCookies } from 'react-cookie';
|
||||||
|
import Signup from './routes/signup';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
// Create a client
|
// Create a client
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
export default () => {
|
export default () => {
|
||||||
|
const [auth, setAuth] = useState(false);
|
||||||
|
const [cookies, setCookie, removeCookie] = useCookies(['token']);
|
||||||
|
useEffect(() => {
|
||||||
|
if (cookies.token) {
|
||||||
|
setAuth(true);
|
||||||
|
}
|
||||||
|
}, [cookies.token]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<CookiesProvider>
|
<CookiesProvider>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={checkAuth() ? <Navigate to="/home" /> : <Login />} />
|
<Route path="/login" element={auth ? <Navigate to="/home" /> : <Login />} />
|
||||||
<Route path="/home" element={!checkAuth() ? <Navigate to="/login" /> : <Home />} />
|
<Route path="/signup" element={auth ? <Navigate to="/home" /> : <Signup />} />
|
||||||
</Routes>
|
<Route path="/home" element={!auth ? <Navigate to="/login" /> : <Home />} />
|
||||||
<Outlet />
|
</Routes>
|
||||||
|
<Outlet />
|
||||||
</CookiesProvider>
|
</CookiesProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import logo from '@assets/images/logo.svg';
|
import logo from '@assets/images/logo.svg';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { useEffect, useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { Cookies, withCookies } from 'react-cookie';
|
import { Cookies, withCookies, useCookies } from 'react-cookie';
|
||||||
import { Navigate, useNavigate } from 'react-router-dom';
|
import { Navigate } from 'react-router-dom';
|
||||||
|
|
||||||
const getMeInfo = async () => {
|
const getMeInfo = async () => {
|
||||||
const token = new Cookies().get('token');
|
const token = new Cookies().get('token');
|
||||||
|
|
@ -26,36 +26,40 @@ const AppHeader = () => {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const [cookies, setCookie, removeCookie] = useCookies(['token']);
|
||||||
|
|
||||||
const logOut = async () => {
|
const logOut = async () => {
|
||||||
new Cookies().remove('token');
|
console.log(cookies);
|
||||||
window.location.reload();
|
removeCookie('token');
|
||||||
|
window.location.href = '/login';
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-80 flex items-center justify-between bg-grey-dark p-2">
|
<>
|
||||||
<div className="app-header__logo">
|
<div className="min-h-80 flex items-center justify-between bg-grey-dark p-2">
|
||||||
<img src={logo} alt="logo" />
|
<div className="app-header__logo">
|
||||||
</div>
|
<img src={logo} alt="logo" />
|
||||||
<div className="right">
|
</div>
|
||||||
<div className="flex items-center space-x-6">
|
<div className="right">
|
||||||
<div className="rounded-full w-24 overflow-hidden">
|
<div className="flex items-center space-x-6">
|
||||||
<img src="https://randomuser.me/api/portraits/women/72.jpg" alt="avatar" />
|
<div className="rounded-full w-24 overflow-hidden">
|
||||||
|
<img src="https://randomuser.me/api/portraits/women/72.jpg" alt="avatar" />
|
||||||
|
</div>
|
||||||
|
<div className="app-header__user__name">
|
||||||
|
<span className="text-white">
|
||||||
|
{meInfo.isLoading ? '' : meInfo.data ? meInfo.data.firstName + ' ' + meInfo.data.lastName : ''}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
className="group relative flex w-auto justify-center rounded-md border border-red bg-red py-2 px-2 text-sm font-medium text-white hover:bg-white hover:text-red focus:outline-none focus:ring-2 focus:ring-red focus:ring-offset-2"
|
||||||
|
onClick={() => logOut()}
|
||||||
|
>
|
||||||
|
Deonnexion
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="app-header__user__name">
|
|
||||||
<span className="text-white">
|
|
||||||
{meInfo.isLoading ? '' : meInfo.data ? meInfo.data.firstName + ' ' + meInfo.data.lastName : ''}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
className="group relative flex w-auto justify-center rounded-md border border-red bg-red py-2 px-2 text-sm font-medium text-white hover:bg-white hover:text-red focus:outline-none focus:ring-2 focus:ring-red focus:ring-offset-2"
|
|
||||||
onClick={() => logOut()}
|
|
||||||
>
|
|
||||||
Deonnexion
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
import { Cookies } from "react-cookie";
|
|
||||||
|
|
||||||
const checkAuth = () => {
|
|
||||||
const token = new Cookies().get("token");
|
|
||||||
if (token && token !== '') {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
export { checkAuth };
|
|
||||||
|
|
@ -0,0 +1,145 @@
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { createContext, useCallback, useContext, useEffect, useReducer, useState } from "react";
|
||||||
|
import { Cookies, useCookies } from "react-cookie";
|
||||||
|
import { Token } from "../types";
|
||||||
|
|
||||||
|
// const checkAuth = () => {
|
||||||
|
// const [cookies, setCookie, removeCookie] = useCookies(["token"]);
|
||||||
|
// useEffect(() => {
|
||||||
|
// if (cookies.token) {
|
||||||
|
// console.log("token exists");
|
||||||
|
// } else {
|
||||||
|
// console.log("token does not exist");
|
||||||
|
// }
|
||||||
|
// }, [cookies.token]);
|
||||||
|
|
||||||
|
// if (cookies.token && cookies.token !== '') {
|
||||||
|
// return true;
|
||||||
|
// }
|
||||||
|
// return false;
|
||||||
|
// };
|
||||||
|
|
||||||
|
// const reducer = (state: any, action: any) => {
|
||||||
|
// switch (action.type) {
|
||||||
|
// case "LOGIN":
|
||||||
|
// return {
|
||||||
|
// token: action.token,
|
||||||
|
// expires: action.expires,
|
||||||
|
// isAuthenticated: true,
|
||||||
|
// };
|
||||||
|
// case "LOGOUT":
|
||||||
|
// return {
|
||||||
|
// token: null,
|
||||||
|
// expires: null,
|
||||||
|
// isAuthenticated: false,
|
||||||
|
// };
|
||||||
|
// default:
|
||||||
|
// return state;
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
|
|
||||||
|
// // create auth hook
|
||||||
|
// const useAuth = () => {
|
||||||
|
// const [cookies, setCookie, removeCookie] = useCookies(["token"]);
|
||||||
|
|
||||||
|
// const [auth, dispatch] = useReducer(reducer, {
|
||||||
|
// token: cookies.token,
|
||||||
|
// isAuthenticated: false,
|
||||||
|
// });
|
||||||
|
|
||||||
|
// const login = (token: string, expires: string) => {
|
||||||
|
// setCookie("token", token, { path: "/", expires: new Date(expires) });
|
||||||
|
// dispatch({ type: "LOGIN", token: token, expires: expires });
|
||||||
|
// };
|
||||||
|
|
||||||
|
// const logout = () => {
|
||||||
|
// removeCookie("token", { path: "/" });
|
||||||
|
// dispatch({ type: "LOGOUT" });
|
||||||
|
// };
|
||||||
|
|
||||||
|
// return [ auth, login, logout ];
|
||||||
|
// };
|
||||||
|
|
||||||
|
// export { checkAuth, useAuth };
|
||||||
|
|
||||||
|
const authContext = createContext({});
|
||||||
|
|
||||||
|
export function ProvideAuth({ children } : any) {
|
||||||
|
const auth = useProvideAuth();
|
||||||
|
return <authContext.Provider value={auth}>{children}</authContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAuth = () => {
|
||||||
|
return useContext(authContext);
|
||||||
|
};
|
||||||
|
|
||||||
|
const loginQuery = (email: string, password: string) => {
|
||||||
|
return useQuery(
|
||||||
|
['login'],
|
||||||
|
async () => {
|
||||||
|
const response = await fetch('/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
mode: 'cors',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return response.json();
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: (data: Token) => {
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error(error);
|
||||||
|
},
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useProvideAuth() {
|
||||||
|
const [user, setUser] = useState({});
|
||||||
|
const [cookies, setCookie, removeCookie] = useCookies(["token"]);
|
||||||
|
|
||||||
|
// Wrap any Firebase methods we want to use making sure ...
|
||||||
|
// ... to save the user to state.
|
||||||
|
const login = (email: string, password: string) => {
|
||||||
|
const { data, error, isLoading } = loginQuery(email, password);
|
||||||
|
if (data) {
|
||||||
|
setUser(data);
|
||||||
|
setCookie("token", data.token, { path: "/", expires: new Date(data.expiresAt) });
|
||||||
|
}
|
||||||
|
if (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
if (isLoading) {
|
||||||
|
console.log('loading');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Subscribe to user on mount
|
||||||
|
// Because this sets state in the callback it will cause any ...
|
||||||
|
// ... component that utilizes this hook to re-render with the ...
|
||||||
|
// ... latest auth object.
|
||||||
|
useEffect(() => {
|
||||||
|
const unsubscribe = () => {
|
||||||
|
if (user) {
|
||||||
|
setUser(user);
|
||||||
|
} else {
|
||||||
|
setUser({});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cleanup subscription on unmount
|
||||||
|
return () => unsubscribe();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Return the user object and auth methods
|
||||||
|
return {
|
||||||
|
user,
|
||||||
|
login,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -1,14 +1,15 @@
|
||||||
import { Link, Navigate, useNavigate } from 'react-router-dom';
|
import { Link, Navigate, useNavigate } from 'react-router-dom';
|
||||||
import logo from '@assets/images/logo.svg';
|
import logo from '@assets/images/logo.svg';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useCookies } from 'react-cookie';
|
import { useCookies } from 'react-cookie';
|
||||||
import type { Token } from '../types';
|
import type { Token } from '../types';
|
||||||
|
import { useAuth } from '../controllers/Auth';
|
||||||
|
|
||||||
const Login = () => {
|
const Login = () => {
|
||||||
const [cookie, setCookie] = useCookies(['token']);
|
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
|
const [cookies, setCookie, removeCookie] = useCookies(['token']);
|
||||||
|
|
||||||
const { refetch } = useQuery(
|
const { refetch } = useQuery(
|
||||||
['login'],
|
['login'],
|
||||||
|
|
@ -25,8 +26,9 @@ const Login = () => {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
onSuccess: (data: Token) => {
|
onSuccess: (data: Token) => {
|
||||||
setCookie('token', data.token, { path: '/', expires: new Date(data.expiresAt), sameSite: 'strict' });
|
console.log(data);
|
||||||
window.location.reload();
|
setCookie('token', data.token, { path: '/', expires: new Date(data.expiresAt) });
|
||||||
|
window.location.href = '/home';
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue