So, I have this flask application and I have used flask_login and flask forms to set up an authentication for my webpage. When I run it on a local development server, it works completely fine and upon putting right username and password, I am able to go to the main page which resides on /main route.
Now, I had to transfer this flask application to an ubuntu server and I worked around on getting apache2 to serve this flask application through wsgi. The problem is, authentication has stopped working all of a sudden now.
When I prompt username and password and click login the page keeps loading and never takes me to the main page with route /main. I have tried some options like setting WSGIPassAuthorization on in my apache conf. file but it has not really work.
I also have a register page that takes username and password and registers them. When I prompt a new username and password, same thing happens and that same page keeps loading on the tab.
My flask authentication code is down below:
from cgitb import reset import tempfile from numpy import column_stack from ast import Str import requests #from requests import request from flask import request import ssl import json import ast from flask import Flask, jsonify, redirect, render_template, request import pandas as pd import os import js2py import sys from flask import Flask, redirect, render_template from os import path import paramiko from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Length, ValidationError from flask_bcrypt import Bcrypt from flask import url_for from flask import flash, session from functools import wraps app = Flask(__name__) app.config['TESTING'] = True #For hashing password bcrypt = Bcrypt(app) db = SQLAlchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' app.config['SECRET_KEY'] = 'thisisasecretkey' login_manager= LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False, unique=True) password = db.Column(db.String(30), nullable=False) class RegisterForm(FlaskForm): username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField(validators=[InputRequired(), length(min=4, max=20)], render_kw={"placeholder": "Password"}) submit = SubmitField("Register") def validate_username(self, username): existing_user_name = User.query.filter_by( username=username.data).first() if existing_user_name: raise ValidationError( "That username already exists. Please choose a different one." ) class LoginForm(FlaskForm): username = StringField(validators=[InputRequired(), length(min=4, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField(validators=[InputRequired(), length(min=4, max=20)], render_kw={"placeholder": "Password"}) submit = SubmitField("Login") @app.route('/', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() # flask.session["user"] = user if user: if bcrypt.check_password_hash(user.password, form.password.data): login_user(user) return redirect(url_for('main_page')) return render_template('login.html', form=form) @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data) new_user = User(username=form.username.data, password=hashed_password) db.session.add(new_user) db.session.commit() return redirect(url_for('login')) return render_template('register.html', form=form) @app.route('/logout', methods=['GET', 'POST']) def logout(): logout_user() return redirect('/') @app.route('/main', methods=['GET', 'POST'] @login_required def main_page(): return render_template('index.html)
And I also have login.html and register.html templates that basically creates the form and takes username and password.
My apache2 conf file is below:
<VirtualHost *:80> ServerName flaskapp.com ServerAdmin webmaster@localhost WSGIPassAuthorization on WSGIScriptAlias / /var/www/FlaskApp/FlaskApp/main.wsgi <Directory /var/www/FlaskApp/FlaskApp/> Order allow,deny Allow from all </Directory> WSGIScriptAlias /main /var/www/FlaskApp/FlaskApp/main.wsgi <Directory /var/www/FlaskApp/FlaskApp/> Order allow,deny Allow from all </Directory> Alias /static /var/www/FlaskApp/FlaskApp/static <Directory /var/www/FlaskApp/FlaskApp/static/> Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log Loglevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
My main.wsgi is down below:
#!/usr/bin/python import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/FlaskApp/") from FlaskApp import app as application application.secret_key = 'thisismysecretkey'
My login.html code:
<!DOCTYPE html> <html> <head> <title>Log in Page</title> <link rel="stylesheet" href="static/login.css"> {% with messages = get_flashed_messages() %} {% if messages %} <ul class="flashes"> {% for message in messages %} <li>{{message}}</li> </ul> {% endfor %} {% endif %} {% endwith %} </head> <body> <div class="sign-up-form"> <img src="static/icon.jpg"> <h1> Welcome to checkout app!</h1> <form method="POST" action=""> {{ form.hidden_tag() }} {{ form.username(class_="input-box")}} {{ form.password(class_="input-box") }} {{ form.submit(class_="submit-button") }} </form> <hr> <p class="or">OR</p> <a href="{{ url_for('register')}}"><button type="button" class="sign-btn">Register yourself</button></a> <p>@test</p> </div> </body>
So, I believe all the routes are defined fine, when I run apache2 I can see my login page since that is the / route. When I prompt username and password and click login, the login page keeps loading but never takes me to the main page. Same thing with register page. When I go to register url and put new username and password to register, then register page keeps loading but never take me back to login page. Not sure if this is a database problem or routing problem.
Again, this works fine on a local development server with visual studio. Its giving me problem with this linux server only
Has anyone faced this problem before!
Any help will be highly appreciated!
Advertisement
Answer
So, apparently I found the solution. The problem was with the import numpy in my python file. I had not really used the numpy so I removed it and the warnings for numpy went away and authentication started working again. The warnings I got from deprecated numpy probably caused some timeout issues (couldnot redirect to the main url because of timeout). So, removing or updating the numpy to latest version was the fix! Thanks!