Cookie尚未存储在计算机上

时间:2018-11-06 01:28:57

标签: python cookies flask redis

我正在尝试建立一个网站,我希望在该网站上存储一些数据。该项目基于Flask并使用Redis数据库。我已经登录并注册了表格,(几乎)除了保存cookie外,其他一切都正常。

这意味着注册后我可以登录我的帐户,但是每次更改网页(例如,选择工具栏上的一个按钮),都会将我重定向到登录页面或显示有关未登录信息的信息应用。

@app.route('/slyko/signin',  methods=['GET', 'POST'])
def signin():
    username = username_from_cookie(request.cookies.get('userID'))
    if username:
        return redirect(url_for('homepage'))

    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'], request.form['password']):
        return log_the_user_in(request.form['username'])
    else:
        error = 'Invalid username or password'
        flash('Invalid username or password')
    return render_template('signin.html', error=error)


@app.route('/slyko/signup', methods=['GET', 'POST'])
def signup():
    username = username_from_cookie(request.cookies.get('userID'))
    if username:
        return redirect(url_for('homepage'))

    error = None
    if request.method == 'POST':
        if register_user(request.form['username'], request.form['password']):
            return redirect(url_for('signin'))
        else:
            error = "Username exists in app already"
            flash(error)
    return render_template('signup.html', error=error)


def register_user(username, password):
    if redis.get('slyko:user:' + username + ':password'):
        return False
    password = generate_password_hash(password, method='pbkdf2:sha256', salt_length=16)
    redis.set('slyko:user:' + username + ':password', password)
    return True

def valid_login(username, password):
    redis_password = redis.get('slyko:user:' + username + ':password')
    if not redis_password:
        return False
    hashed_password = generate_password_hash(password, method='pbkdf2:sha256', salt_length=16)
    if check_password_hash(hashed_password, password):
        return True
    return False


def log_the_user_in(username):
    import datetime
    expire_date = datetime.datetime.now() + datetime.timedelta(days=1)
    cookie = insert_user_token(username)
    resp = make_response(render_template('main.html', TOPIC_DICT=TOPIC_DICT))
    resp.set_cookie('userID', cookie, expires=expire_date, secure=True, httponly=True)
    return resp


def insert_user_token(username):
    token = token_generate()
    redis.set('slyko:token:' + token + ':username', username)
    return token

有什么建议吗?

0 个答案:

没有答案