Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getCsrf(){
- fetch("http://localhost:8000/csrf/", {
- credentials: "include",
- })
- .then((res) => {
- let csrfToken = res.headers.get("X-CSRFToken");
- setCsrf({csrf: csrfToken});
- })
- .catch((err) => {
- console.log(err);
- })
- }
- const login = (event) => {
- event.preventDefault();
- setIsLoading(true)
- fetch("http://localhost:8000/login/", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-CSRFToken": csrf.csrf,
- },
- credentials: "include",
- body: JSON.stringify({username: username, password: password}),
- })
- .then(isResponseOk)
- .then((data) => {
- console.log(data);
- setIsAuthenticated(true)
- localStorage.setItem("authenticated", true);
- setUsername('')
- setPassword('')
- setIsLoading(false)
- // this.setState({isAuthenticated: true, username: "", password: ""});
- })
- .catch((err) => {
- console.log('inside login catch')
- console.log(csrf.csrf, 'catch')
- console.log(err);
- });
- }
- const isResponseOk = (response) =>{
- if (response.status >= 200 && response.status <= 299) {
- return response.json();
- } else {
- console.log(response)
- throw Error(response.statusText);
- }
- }
- useEffect(() => {
- //getSessions
- setIsLoading(true)
- fetch("http://localhost:8000/session/", {
- credentials: "include",
- })
- .then((res) => res.json())
- .then((data) => {
- // console.log(data);
- if (data.isAuthenticated) {
- setIsAuthenticated(true)
- console.log(data)
- } else {
- // test()
- setIsAuthenticated(false)
- console.log(data)
- getCsrf()
- }
- setIsLoading(false)
- })
- .catch((err) => {
- console.log(err);
- });
- }, [])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement