mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
feat: init auth across the app
This commit is contained in:
parent
9479a4b127
commit
3b85a73ec1
12 changed files with 204 additions and 29 deletions
47
front/components/security/AuthProvider.tsx
Normal file
47
front/components/security/AuthProvider.tsx
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import React, { useEffect } from "react";
|
||||
import { getRefreshToken, getUserInfo } from "../../services/auth/auth";
|
||||
|
||||
export const AuthContext: any = React.createContext({});
|
||||
|
||||
export interface Auth {
|
||||
access_token: string;
|
||||
isAuthenticated: boolean;
|
||||
userInfo: {};
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
const AuthProvider = (props: any) => {
|
||||
const [auth, setAuth] = React.useState<Auth>({ access_token: "", isAuthenticated: false, userInfo: {}, isLoading: true });
|
||||
|
||||
async function checkRefreshToken() {
|
||||
let data = await getRefreshToken();
|
||||
return data.access_token;
|
||||
}
|
||||
|
||||
async function checkAuth() {
|
||||
let access_token = await checkRefreshToken();
|
||||
let isAuthenticated = false;
|
||||
let userInfo = {};
|
||||
let isLoading = false;
|
||||
|
||||
if (access_token) {
|
||||
userInfo = await getUserInfo(access_token);
|
||||
isAuthenticated = true;
|
||||
setAuth({ access_token, isAuthenticated, userInfo, isLoading });
|
||||
} else if (!access_token) {
|
||||
isAuthenticated = false;
|
||||
setAuth({ access_token, isAuthenticated, userInfo, isLoading });
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(mvp) : fix performance issues > no need to check auth on every render
|
||||
useEffect(() => {
|
||||
if (!auth.isAuthenticated) {
|
||||
checkAuth();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return <AuthContext.Provider value={auth}>{props.children}</AuthContext.Provider>;
|
||||
};
|
||||
|
||||
export default AuthProvider;
|
||||
Loading…
Add table
Add a link
Reference in a new issue