Commit f97e3826 authored by Markus Mößler's avatar Markus Mößler
Browse files

added login and registration component with sending of xsrf token

parent 20d0ff20
Loading
Loading
Loading
Loading
+109 −0
Original line number Diff line number Diff line
// ./frontend/src/components/Login.js

import React, { useEffect, useState } from 'react';
import Cookies from 'js-cookie';

function Login() {

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  
  // useEffect(() => {

  //   const checkUser = async () => {
  //     try {
  //       const responseData = await protectedFetch(`${Config.backendBaseUrl}` + '/login');
  //       if (!responseData.user_exists) {
  //         alert('No user exists!')
  //         window.location.href = `${Config.frontendBaseUrl}` + '/register'; // Redirect to register page 
  //       }
  //     } catch (error) {
  //       console.error('Error fetching data:', error);
  //     } finally {
  //     }
  //   };

  //   checkUser();
  // }, []);

  // Function for login of external users
  const handleLogin = async (e) => {
    e.preventDefault();
    try {

      // Define data for request
      const data = {
        email,
        password,
      };
      console.log('logging of data: ', data);
      
      // Define headers for request
      const headers = {
        'Content-Type': 'application/json',
      };
      // Retrieve the CSRF token from the cookie
      const csrfToken = Cookies.get('_xsrf');
      console.log('CSRF Token:', csrfToken);
      if (csrfToken) {
        headers['X-XSRFToken'] = csrfToken; // Add the CSRF token to the headers
      }

      // Make fetch request
      const response = await fetch(`/tornado-backend/login`, {
        method: "POST",
        body: JSON.stringify(data),
        headers: headers,
        credentials: 'include', // Include cookies in the request
      });

      console.log('logging of response status: ', response.ok);
      if (response.ok) {
        window.location.href = '/'; // Redirect to home page
      }      
    } catch (error) {
      alert('Login failed!')
      console.error('There was an error!', error);
    }
  };

  return (
      <div>
      <h2>Login</h2>
      <hr />
      <form onSubmit={handleLogin}>
      <div className="mb-3 mt-3">
        <label htmlFor="email" className="form-label">Email:</label>
        <input
          type="email"
          className="form-control"
          id="email"
          placeholder="Enter email"
          name="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
      </div>
      <div className="mb-3">
        <label htmlFor="pwd" className="form-label">Password:</label>
        <input
          type="password"
          className="form-control"
          id="pwd"
          placeholder="Enter password"
          name="pswd"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />
      </div>
      {/* <hr /> */}
      <button type="submit" className="btn btn-hoh-blue btn-sm">Login</button>
      </form>
      </div>
      
  );
}

export default Login
 No newline at end of file
+103 −0
Original line number Diff line number Diff line
// ./frontend/src/components/Register.js

import React, { useState } from 'react';
import Cookies from 'js-cookie';

function Register() {
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [password, setPassword] = useState('');

  const handleRegister = async (e) => {
    e.preventDefault();
    try {

      // Define data for request
      const data = {
        email,
        name,
        password,
      };

      // Define headers for request
      const headers = {
        'Content-Type': 'application/json',
      };

      // Retrieve the CSRF token from the cookie
      const csrfToken = Cookies.get('_xsrf');
      console.log('Logging of Csrf token', csrfToken)
      // console.log('CSRF Token:', csrfToken);
      if (csrfToken) {
        headers['X-XSRFToken'] = csrfToken;
      }
      console.log('Headers sent from registration', headers)

      const response = await fetch(`/tornado-backend/register`, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: headers,
        credentials: 'include', // Include cookies in the request
      });
      console.log('logging of response status: ', response.ok);
      if (response.ok) {
        window.location.href = '/login'; // Redirect to home page
      }      
    } catch (error) {
      alert('Registering failed!')
      console.error('There was an error!', error);
    }
  };

  return (
    <div>
        <h2>Register</h2>
        <hr />
        <form onSubmit={handleRegister}>
            <div className="mb-3">
                <label htmlFor="name" className="form-label">Name:</label>
                <input
                    type="text"
                    className="form-control"
                    id="name"
                    placeholder="Enter name"
                    name="name" 
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    required                   
                />
            </div>
            <div className="mb-3">
                <label htmlFor="email" className="form-label">Email:</label>
                <input
                    type="email"
                    className="form-control"
                    id="email"
                    placeholder="Enter email"
                    name="email" 
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required                   
                />
            </div>
            <div className="mb-3">
                <label htmlFor="pwd" className="form-label">Password:</label>
                <input
                    type="password"
                    className="form-control"
                    id="pwd"
                    placeholder="Enter password"
                    name="pswd" 
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required                   
                />
            </div>
            <hr />
            <button type="submit" className="btn btn-hoh-blue">Register</button>
      </form>
    </div>
  );
}

export default Register
 No newline at end of file