test login

This commit is contained in:
2024-01-23 22:56:17 +01:00
parent ca7790bfdf
commit 9066a51025
8 changed files with 144 additions and 108 deletions

View File

@@ -2,7 +2,7 @@ import LogoIcon from '../assets/FFSSAF-bord-blanc-fond-transparent.webp'
import './Nav.css'
import {NavLink} from "react-router-dom";
import {useAuth, useAuthDispatch} from "../hooks/useAuth.jsx";
import {logout, redirect_auth_page} from "../utils/auth.js";
import {login, logout} from "../utils/auth.js";
export function Nav() {
@@ -55,7 +55,7 @@ function LoginMenu() {
return <li className="nav-item">
{!is_authenticated ? (
<div className="nav-link" onClick={() => redirect_auth_page()}>Connexion</div>
<div className="nav-link" onClick={() => login()}>Connexion</div>
) : (
<div className="nav-link" onClick={() => {
logout(token, refresh).then(() => dispatch({type: 'invalidate'}))

View File

@@ -1,4 +1,4 @@
import {sendTokenRequestPart2} from "../utils/auth.js";
import {login_redirect} from "../utils/auth.js";
import {useEffect, useRef} from "react";
export const AuthCallback = () => {
@@ -8,8 +8,7 @@ export const AuthCallback = () => {
if (isInit.current)
return;
isInit.current = true
const params = new URLSearchParams(window.location.search);
sendTokenRequestPart2(params.get('code'), params.get('state'));
login_redirect();
}, []);

View File

@@ -1,5 +1,4 @@
import {createContext, useContext, useEffect, useReducer} from "react";
import {sendTokenRequest} from "../utils/auth.js";
const AuthContext = createContext(undefined);
const AuthDispatchContext = createContext(null);
@@ -15,23 +14,6 @@ export function useAuthDispatch() {
export function KeycloakContextProvider({children}) {
const [auth, dispatch] = useReducer(authReducer, initialAuth);
useEffect(() => {
if (auth.token === undefined || !auth.is_authenticated)
return;
const jwt = JSON.parse(atob(auth.token.split('.')[1]));
const ref = setTimeout(() => {
if (auth.refresh !== undefined && auth.refresh !== null)
sendTokenRequest(auth.refresh).then(data => dispatch({
type: 'update',
token: data.access_token,
refresh: data.refresh_token,
})
).catch(() => dispatch({type: 'invalidate'}));
}, jwt.exp * 1000 - new Date().getTime() - 1000)
return () => clearTimeout(ref);
}, [auth])
return <AuthContext.Provider value={auth}>
<AuthDispatchContext.Provider value={dispatch}>
{children}
@@ -61,8 +43,6 @@ function authReducer(auth, action) {
case 'invalidate': {
return {
...auth,
token: undefined,
refresh: undefined,
is_authenticated: false
}
}
@@ -73,8 +53,6 @@ function authReducer(auth, action) {
}
const initialAuth = {
token: undefined,
refresh: undefined,
is_authenticated: undefined,
data: undefined,
}

View File

@@ -4,93 +4,30 @@ const auth_url = import.meta.env.VITE_AUTH_URL;
const vite_url = import.meta.env.VITE_URL;
const client_id = import.meta.env.VITE_CLIENT_ID;
const api_url = import.meta.env.VITE_API_URL;
export function check_validity(online_callback = () => {
}) {
const token = localStorage.getItem("access_token")
if (token !== undefined && token !== null) {
const jwt = JSON.parse(atob(token.split('.')[1]));
if (jwt.exp < new Date().getTime() / 1000 + 1)
if (online_callback) online_callback(false); else return false;
if (online_callback) {
return axios.get(`${auth_url}/userinfo`, {
headers: {
Authorization: `Bearer ${token}`
}
}).then(() => {
online_callback(true);
}).catch(() => {
online_callback(false);
})
}
if (online_callback) online_callback(true); else return true;
}
if (online_callback) online_callback(false); else return false;
}
export function sendTokenRequest(refresh) {
return axios.post(`${auth_url}/token`, {
client_id: client_id,
redirect_uri: `${vite_url}/complete/auth/`,
grant_type: 'refresh_token',
refresh_token: refresh
}, {
headers: {
"Accept": "*/*",
"Content-Type": "application/x-www-form-urlencoded",
}
}).then(data => {
localStorage.setItem("access_token", data.data.access_token);
localStorage.setItem("refresh_token", data.data.refresh_token);
return data.data;
}).catch(err => {
console.log(err)
alert("Failed get token from refresh");
return axios.get(`${api_url}/auth`).then(data => {
console.log(data.data)
online_callback(data.data);
}).catch(() => {
online_callback(false);
})
}
export function sendTokenRequestPart2(code, state) {
axios.post(`${auth_url}/token`, {
client_id: client_id,
redirect_uri: `${vite_url}/complete/auth/`,
code: code,
grant_type: 'authorization_code',
}, {
headers: {
"Accept": "application/x-www-form-urlencoded",
"Content-Type": "application/x-www-form-urlencoded",
}
}).then(data => {
localStorage.setItem("access_token", data.data.access_token);
localStorage.setItem("refresh_token", data.data.refresh_token);
const next = localStorage.getItem("cb_" + state)
if (next) {
clearNext()
window.location.href = next
} else {
window.location.href = import.meta.env.VITE_URL
}
}).catch((err) => {
console.log(err)
// redirect_auth_page()
})
export function login() {
sessionStorage.setItem("next", window.location.href)
window.location.href = `${api_url}/auth/login`;
}
function clearNext() {
const arr = []; // Array to hold the keys
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).substring(0, 3) === 'cb_') {
arr.push(localStorage.key(i));
}
}
for (let i = 0; i < arr.length; i++) {
localStorage.removeItem(arr[i]);
export function login_redirect() {
const next = sessionStorage.getItem("next")
if (next) {
sessionStorage.removeItem("next")
window.location.href = next
} else {
window.location.href = import.meta.env.VITE_URL
}
}