0

I run a webpage on heroku using flask. It has registration form. After reg I generare session_id and add it to db and session. Then flask redirects me to homepage. This is code for home:

@app.route('/home')
def home():
    if 'session_id' in session:
        user = db.users.find_one({'session_id':session['session_id']})
        if user:
            return render_template("home.html", signin=True, username=user['login'], db=db)
        else:
            return "Didn't find user document"
    else:
        return redirect(url_for('login'))

Then when i start reloading page, it randomly shows home page or login page. I also have a redirection from login page to home if session_ids match. Btw, it never shows "Didn't find user document". The problem is in session.

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        login = request.form['login']
        passhash = request.form['hash']
        user = db.users.find_one({'login':login})
        if user:
            if bcrypt.check_password_hash(user['hash'], hashlib.sha512((passhash+user['salt']).encode()).hexdigest().encode()):
                if user['session_id']:
                    # if alredy logged in on another device
                    session['session_id']=user['session_id']
                else:   
                    session_id = binascii.hexlify(os.urandom(32)).decode()
                    session['session_id']=session_id
                    db.users.update_one({'login':user['login']},{'$set': {'session_id':session_id}})
                return "True"
        return "Wrong login/password"

    if 'session_id' in session:
        if db.users.find_one({'session_id':session['session_id']}):
            return redirect(url_for('home'))

return render_template('login.html', title="Sign in")

This func runs using onsubmit="return encrypt()"

function encrypt(){
      var password = $("#inputPassword").val();
      var hash = CryptoJS.SHA512(password, { outputLength: 256 }).toString(CryptoJS.enc.Hex);
      $.post("/login", ({"login":$('#inputLogin').val(),"hash":hash}), function(data){
        if(data === 'True'){
          window.location = "/home"
        }else{
          $(".error").html('<div class="alert alert-danger" role="alert">'+data+'</div>')
          $("input").val('')
        }
      });
      return false;
    }
Kirill Losev
  • 125
  • 6

1 Answers1

0

The problem was that the secret key was using os.urandom(24). After I set up static secret key with heroku config vars.

Kirill Losev
  • 125
  • 6