Advertisement
Guest User

Untitled

a guest
Oct 10th, 2022
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. function getCsrf(){
  2. fetch("http://localhost:8000/csrf/", {
  3. credentials: "include",
  4. })
  5. .then((res) => {
  6. let csrfToken = res.headers.get("X-CSRFToken");
  7. setCsrf({csrf: csrfToken});
  8.  
  9. })
  10. .catch((err) => {
  11. console.log(err);
  12. })
  13.  
  14. }
  15.  
  16. const login = (event) => {
  17. event.preventDefault();
  18. setIsLoading(true)
  19. fetch("http://localhost:8000/login/", {
  20. method: "POST",
  21. headers: {
  22. "Content-Type": "application/json",
  23. "X-CSRFToken": csrf.csrf,
  24. },
  25. credentials: "include",
  26. body: JSON.stringify({username: username, password: password}),
  27. })
  28. .then(isResponseOk)
  29. .then((data) => {
  30. console.log(data);
  31. setIsAuthenticated(true)
  32. localStorage.setItem("authenticated", true);
  33. setUsername('')
  34. setPassword('')
  35. setIsLoading(false)
  36. // this.setState({isAuthenticated: true, username: "", password: ""});
  37. })
  38. .catch((err) => {
  39. console.log('inside login catch')
  40. console.log(csrf.csrf, 'catch')
  41. console.log(err);
  42. });
  43.  
  44. }
  45.  
  46. const isResponseOk = (response) =>{
  47. if (response.status >= 200 && response.status <= 299) {
  48. return response.json();
  49. } else {
  50. console.log(response)
  51. throw Error(response.statusText);
  52. }
  53. }
  54. useEffect(() => {
  55. //getSessions
  56. setIsLoading(true)
  57. fetch("http://localhost:8000/session/", {
  58. credentials: "include",
  59. })
  60. .then((res) => res.json())
  61. .then((data) => {
  62. // console.log(data);
  63. if (data.isAuthenticated) {
  64. setIsAuthenticated(true)
  65.  
  66. console.log(data)
  67. } else {
  68. // test()
  69. setIsAuthenticated(false)
  70. console.log(data)
  71.  
  72. getCsrf()
  73. }
  74. setIsLoading(false)
  75. })
  76. .catch((err) => {
  77. console.log(err);
  78. });
  79.  
  80.  
  81. }, [])
  82.  
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement