Issue with Flask Login

42 Views Asked by At

I have a script with two users, physician and patient. The patient login works as intended but the physician only opens briefly then redirects me to the login page:

Physician script that does'nt work as intended

        document.getElementById('physicianLoginForm').addEventListener('submit', function(e) {
            e.preventDefault();

            // Get the email and password from the form
            var email = document.getElementById('physician_username').value;
            var password = document.getElementById('physician_password').value;

            // Send the login data to the Flask backend
            fetch('/handle_physician_login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    email: email,
                    password: password
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Redirect to the physician dashboard if login is successful
                    window.location.href = data.redirect;
                } else {
                    // Display error message if login failed
                    document.getElementById('errorMessage').textContent = data.message;
                }
            })
            .catch(error => console.error('Error:', error));
        });

    </script>
</body>
class Physician(UserMixin):
    def __init__(self, id, email):
        self.id = id
        self.email = email

@login_manager.user_loader
def load_physician(user_email):
    conn = get_db_connection()
    if conn is None:
        return None
    try:
        cursor = conn.cursor()
        # Make sure to query the email column since user_email is an email
        cursor.execute("SELECT PhysicianId, WorkEmail FROM physicians WHERE WorkEmail=?", user_email)
        user_data = cursor.fetchone()
        if user_data:
        # Create the user object with the PhysicianId and Email
            return Physician(id=user_data.PhysicianId, email=user_data.WorkEmail)
        return None
    finally:
        conn.close()

@app.route('/handle_physician_login', methods=['POST'])
@limiter.limit("5 per minute")
def handle_physician_login():
    data = request.get_json()
    email = data['email']
    password = data['password']

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': 'Database connection failed'}), 500

    try:
        cursor = conn.cursor()
        cursor.execute("EXEC AuthenticatePhysician @Email=?", email)
        physician = cursor.fetchone()
        if physician and check_password_hash(physician.Password, password):
            user = Physician(physician.PhysicianId, email)
            login_user(user)
            return jsonify({'success': True, 'redirect': url_for('physician_dashboard')})

        else:
            return jsonify({'success': False, 'message': 'Invalid login credentials'}), 401
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500
    finally:
        conn.close()

Below is the correctly working script for patient login

<script>
        document.getElementById('patientLoginForm').addEventListener('submit', function(e) {
            e.preventDefault();

            // Get the email and password from the form
            var email = document.getElementById('Email').value;
            var password = document.getElementById('Password').value;

            // Send the login data to the Flask backend
            fetch('/handle_patient_login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    email: email,
                    password: password
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Redirect to the patient dashboard if login is successful
                    window.location.href = data.redirect;
                } else {
                    // Display error message if login failed
                    document.getElementById('registrationMessage').textContent = data.message;
                }
            })
            .catch(error => console.error('Error:', error));
        });
    </script>
class Patient(UserMixin):
    def __init__(self, id, email):
        self.id = id
        self.email = email


@login_manager.user_loader
def load_user(user_email):
    conn = get_db_connection()
    if conn is None:
        return None
    try:
        cursor = conn.cursor()
        # Make sure to query the email column since user_email is an email
        cursor.execute("SELECT PatientID, Email FROM patients WHERE Email=?", user_email)
        user_data = cursor.fetchone()
        if user_data:
            # Create the user object with the PatientID and Email
            return Patient(id=user_data.PatientID, email=user_data.Email)
        return None
    finally:
        conn.close()


@app.route('/handle_patient_login', methods=['POST'])
@limiter.limit("5 per minute")
def handle_patient_login():
    data = request.get_json()
    email = data['email']
    password = data['password']

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': 'Database connection failed'}), 500

    try:
        cursor = conn.cursor()
        cursor.execute("EXEC AuthenticatePatient @Email=?", email)
        patient = cursor.fetchone()
        if patient and check_password_hash(patient.Password, password):
            user = Patient(patient.PatientID, email)
            login_user(user)
            return jsonify({'success': True, 'redirect': url_for('patient_dashboard')})
        else:
            return jsonify({'success': False, 'message': 'Invalid login credentials'}), 401
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500
    finally:
        conn.close()

I have tried to make it such that the physician login matches the patient login with minor changes to the html and pyhthon script but i still have the issue

0

There are 0 best solutions below