moving to docker
This commit is contained in:
97
react/app/src/context/AuthContext.jsx
Normal file
97
react/app/src/context/AuthContext.jsx
Normal file
@ -0,0 +1,97 @@
|
||||
import { createContext, useState, useEffect } from "react";
|
||||
import jwt_decode from "jwt-decode";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
const AuthContext = createContext("");
|
||||
|
||||
export default AuthContext;
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [authTokens, setAuthTokens] = useState(() =>
|
||||
localStorage.getItem("authTokens")
|
||||
? JSON.parse(localStorage.getItem("authTokens"))
|
||||
: null
|
||||
);
|
||||
const [user, setUser] = useState(() =>
|
||||
localStorage.getItem("authTokens")
|
||||
? jwt_decode(localStorage.getItem("authTokens"))
|
||||
: null
|
||||
);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const history = useNavigate();
|
||||
|
||||
const loginUser = async (username, password) => {
|
||||
const response = await fetch("http://127.0.0.1:8000/api/auth/token/", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password
|
||||
})
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (response.status === 200) {
|
||||
console.log(response, data)
|
||||
setAuthTokens(data);
|
||||
setUser(jwt_decode(data.access));
|
||||
localStorage.setItem("authTokens", JSON.stringify(data));
|
||||
history.push("/");
|
||||
} else {
|
||||
alert("Something went wrong!");
|
||||
}
|
||||
};
|
||||
|
||||
const registerUser = async (username, password) => {
|
||||
const response = await fetch("http://127.0.0.1:8000/api/auth/register/", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password
|
||||
})
|
||||
});
|
||||
if (response.status === 201) {
|
||||
history.push("/login");
|
||||
} else {
|
||||
alert("Something went wrong!");
|
||||
}
|
||||
};
|
||||
|
||||
const logoutUser = () => {
|
||||
setAuthTokens(null);
|
||||
setUser(null);
|
||||
localStorage.removeItem("authTokens");
|
||||
history.push("/");
|
||||
};
|
||||
|
||||
const contextData = {
|
||||
user,
|
||||
setUser,
|
||||
authTokens,
|
||||
setAuthTokens,
|
||||
registerUser,
|
||||
loginUser,
|
||||
logoutUser
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (authTokens) {
|
||||
setUser(jwt_decode(authTokens.access));
|
||||
}
|
||||
setLoading(false);
|
||||
}, [authTokens, loading]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={contextData}>
|
||||
{loading ? null : children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user