1

i am developing my first flask web app that involves login, sessions and of course redirects. It is a webapp where schools can log in and view bullying reports from their students. On localhost everything works fine but in the heroku server it doesn't. Ihave an index.html with an if statement in jinja:{% if session.user_id %} it shows an index for schools, else it shows a general index The problem is that after loggin in it goes back to the general index or to login again instead of redirecting to the "schools index" .

Maybe this is caused because somehow Heroku fails to recognise the session[user_id]??

Sometimes it goes beyond the login succesfully but when i redirect once more it just forgets the session and goes back to general index or login again. And also sometimes when the register button is pressed it just goes back to index forgetting the session.

Here is the heroku link if you want to try it out: https://pure-harbor-99831.herokuapp.com/

This is my code and below i will enter the errors i get on logs

import os
import time
import datetime
from flask import Flask, flash, jsonify, redirect, render_template, request, session, url_for, session
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError, BadRequest
from werkzeug.security import check_password_hash, generate_password_hash
import sqlite3
from sqlite3 import Error
from flask_security import Security, login_required
from functools import wraps

app = Flask(__name__)
pp.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)
app.config["TEMPLATES_AUTO_RELOAD"] = True

def login_required(f):
    """
    Decorate routes to require login.

    http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get("user_id") is None:
            return redirect("/login")
        return f(*args, **kwargs)
    return decorated_function

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/regescuela", methods=["GET", "POST"])
def register():
    session.clear()
    if request.method == "POST":
        username = request.form.get("username").upper()
        dup_username = db.session.query(db.exists().where(Usuarios.username == username)).scalar()
        nombrescuela = request.form.get("nombrescuela").upper()
        dup_nombrescuela = db.session.query(db.exists().where(Usuarios.nombrescuela == nombrescuela)).scalar()

        if dup_username:
            return apology("Este usuario ya existe! Prueba con otro!")
        if dup_nombrescuela:
            return apology("Esta escuela ya ha sido registrada anteriormente!")
        if not request.form.get("mail"):
            return apology("No ha introducido el correo electrónico!")
        if not (request.form.get("provincia")):
            return apology("No ha introducido provincia.")
        if not request.form.get("nombrescuela"):
            return apology("No ha introducido el nombre de la escuela!")
        if "@" not in request.form.get("mail"):
            return apology("No ha introducido un correo electrónico valido!")
        if not request.form.get("username"):
            return apology("No ha introducido un nombre de usuario!")
        elif not request.form.get("password"):
            return apology("No ha introducido una contraseña!")
        elif request.form.get("password") != request.form.get("confirmation"):
            return apology("Las contraseñas no coinciden.")
    else:
        usumayu = request.form.get("username")
        return render_template("regescuela.html"
    nuevaentrada = Usuarios(nombrescuela = request.form.get("nombrescuela").upper(), username = request.form.get("username").upper(), hash = generate_password_hash(request.form.get("password")), provincia = request.form.get("provincia"), mail = request.form.get("mail"))
    db.session.add(nuevaentrada)
    db.session.commit()

    session["user_id"] = nuevaentrada

    flash("Registrado!")
    return redirect("/")@app.route("/check", methods=["GET"])



@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        username=request.form.get("username").upper()

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("Debe ingresar un nombre de usuario.", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("Debe ingresar una contraseña.", 403)



        # Ensure username exists and password is correct


        if rows is None or not check_password_hash(rows.hash, request.form.get("password")):
            return apology("Usuario o contraseña incorrectos", 403)

        # Remember which user has logged in
        session["user_id"] = rows.username #rows[0]["username"]
        session["nombrescuela"] = rows.nombrescuela


        # Redirect user to home page
        flash("Sesión Iniciada!")
        return redirect("/")


    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")


@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")

Errors:

I get this error when loggin in (localhost):

"POST /login HTTP/1.1" 302 - 

And this one when loggin in in Heroku :

2019-08-28T02:48:12.328933+00:00 heroku[router]: at=info method=POST path="/login" host=pure-harbor-99831.herokuapp.com request_id=5b9187f3-b253-40e5-8f98-d37be12bbc8b fwd="190.55.52.184" dyno=web.1 connect=0ms service=202ms status=302 bytes=583 protocol=https

Maybe i am doing something wrong with the post and get but i dont think so. I think the main problem should be in that "def login_required(f):" that i create at the beginning because it always goes back to /login like if session.get("user_id") was None.

but it is weird because altough in localhost it outputs the error the redirects work fine, but in heroku it outputs the eror and the redirects dont work.

Any clues? Thanks:)

deloco
  • 43
  • 8

1 Answers1

-1

You would generally want to use redirect with url_for. For example in this case instead of saying redirect("/login"), do redirect(url_for('login')). Also, make sure that you import the url_for function from flask.

TarcanGul
  • 24
  • 2