0

i am developing my first flask web app that involves some logins, sessions and of course redirects. It is a webapp where schools can log in and view bulying reports from their students. On localhost everything works fine but in the heroku server after loggin in it goes back to the general index instead of going to the "schools index" .

Maybe this is caused because somehow Heroku fails to recognise the sessions[]?? I also have an index.html with and if and if user logs in it shows a part of it and not all and maybe this is causing the problem. But i dont think it can be that because it works well on localhost.

The problem is that sometimes it goes beyond the login succesfully but when i redirect once more it just forgets the session and goes back to index.

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

Here i will add the main redirects of my app.py and my index.html:

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

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("/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)

        # Query database for username
        # rows = db.session.query(db.exists().where(Usuarios.username == username)).scalar()
        #rowpass = db.session.query.filter_by(Usuarios.username = username).all()
        rows = Usuarios.query.filter_by(username=username).first()
    #    rowpass = db.session.query(Usuarios.filter_by(Usuarios.username == username)).first()
#       rows = db.execute("SELECT * FROM usuarios WHERE username = :username",
#                         username=request.form.get("username").upper())

        # Ensure username exists and password is correct
        #if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):

        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("/")



@app.route("/tablavictimas")
@login_required
def tablavictimas():
    #acordate que aca cambiaste sessionuser_id por sessionnombrescuela y fijate si sirve si no volve al sessionuser_id
    escuela = session["nombrescuela"].upper()
    hechos = Victimas.query.filter_by(escuela=escuela).all()
    hay = db.session.query(db.exists().where(Victimas.escuela == escuela)).scalar()
    hechitos = Victimas.query.filter_by(escuela=escuela).order_by(Victimas.curso).all()
    #hechos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela", escuela=session["nombrescuela"])
    #hechitos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela GROUP BY curso", escuela=session["nombrescuela"])
    if not hay:
        return apology("No se han recibido reportes aún.")
    return render_template("tablavictimas.html", hechos=hechos, hechitos=hechitos)

@app.route("/tablatestigos", methods=["GET", "POST"])
@login_required
def tablatestigos():
    escuela = session["nombrescuela"].upper()
    hechos = Testigos.query.filter_by(escuela=escuela).all()
    hay = db.session.query(db.exists().where(Testigos.escuela == escuela)).scalar()
    hechitos = Testigos.query.filter_by(escuela=escuela).order_by(Testigos.curso).all()
    #hechos = db.execute("SELECT * FROM testigos WHERE escuela = :escuela", escuela=session["nombrescuela"])
    #hechitos = db.execute("SELECT * FROM testigos WHERE escuela = :escuela GROUP BY curso", escuela=session["nombrescuela"])
    if not hay:
        return apology("No se han recibido reportes aún.")
    return render_template("tablatestigos.html", hechos=hechos, hechitos=hechitos)

Index.html just extends a layout that says this:

{% if session.user_id %}
                  <a href="/">   <img src="https://i.ibb.co/2kV28jg/palabraslogofinal.png" alt="logo" id="palabraslogo"> </a>
                    <a class="navbar-brand" href="/" class="escuelastitulo"> <b> <span class="blue" style="position: relative; top: -8px; font-size: 40px;">Escuelas</span> </b> </a>
                    <ul class="navbar-nav mr-auto mt-2">

                        <li class="nav-item"><a class="nav-link" href="/reportesrecibidos" style="color:#000000; position: relative; top: -8px; font-size:18px;">Reportes Recibidos</a></li>
                    </ul>

                    <ul class="navbar-nav ml-auto mt-2">
                        <li class="nav-item"><a class="nav-link" href="/logout">Cerrar Sesión</a></li>
                    </ul>
                {% else %}
          <!--      <a class="navbar-brand" href="/"><span class="blue">B</span><span class="red">u</span><span class="yellow">l</span><span class="green">l</span><span class="red">yng</span></a> -->
            <a href="/">   <img src="https://i.ibb.co/2kV28jg/palabraslogofinal.png" alt="logo" id="palabraslogo"> </a>
                <ul class="navbar-nav mr-auto mt-2">
                <ul class="navbar-nav mr-auto mt-2">

                    <li class="nav-item"><a class="nav-link" href="/logreg" style="color:#000000; font-size:18px;">Escuela</a></li>
                    <li class="nav-item"><a class="nav-link" href="/elegi" style="color:#000000; font-size:18px;">Estudiante</a></li>
                    <li class="nav-item"><a class="nav-link" href="/psicologo" style="color:#000000; font-size:18px;">Hablar gratis con un psicologo</a></li>
                    <li class="nav-item"><a class="nav-link" href="/argentina" style="color:#000000; font-size:18px;">Bullying en Argentina</a></li>


                </ul>
                {% endif %}

Here are the errors i get on logs: First a 302:

"POST /login HTTP/1.1" 302 209 "https://pure-harbor-99831.herokuapp.com/login" 

Then an error:

http_error="Invalid HTTP status line" at=error code=H17 desc="Poorly formatted HTTP response" method=GET path="/tablatestigos" host=pure-harbor-99831.herokuapp.com request_id=d32a433d-0607-4c59-bebe-76856c2eea99 fwd="190.55.52.184" dyno=web.1 connect=1ms service=17ms status=503 bytes=325 protocol=https

Any clues? Thanks :)

deloco
  • 43
  • 8
  • Why are you rolling your own user management instead of using Flask-Security and/or Flask-Login? That will give you solid, well-tested user management and login code and avoid issues like this. – Nick K9 Aug 26 '19 at 17:45
  • This is part of the final project of Harvard CS50 and this is how they taught us how to deal with these. They gave us a layout to work in the final project and there is a part where they "from flask_security import Security, login_required" – deloco Aug 26 '19 at 19:04
  • Alright, so it sounds like you ARE using Flask-Security. So why are you implementing your own login_required and login? – Nick K9 Aug 26 '19 at 19:52
  • Yeah, it seems to be a problem in that ``` def login_required(f): ``` becuase it redirects to /login every time because of that ``` if session.get("user_id") is None: ``` It seems that it is not recognising porperly the userid maybe your way with flasksecutirity is better. What you suggest changing? sorry if it is a noob question but i am just starting coding – deloco Aug 26 '19 at 20:13

0 Answers0