登录后,flask-login用户设置为匿名 [英] flask-login user is set to anonymous after login

查看:89
本文介绍了登录后,flask-login用户设置为匿名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是flask和flask-login的新手,我已经为此苦苦挣扎了几天.

im new to flask and flask-login and ive been struggling with this for days.

我正在尝试这样登录用户:

Im trying to log a user in like this:

from creds import auth_username, auth_password, pgsql_dbuser, pgsql_dbpassword, pgsql_db1name
from flask import Flask, render_template, request, Response, redirect, url_for
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, login_required, login_user, current_user, logout_user
import logging
import psycopg2
import uuid
import datetime

app = Flask(__name__)
app.secret_key = str(uuid.uuid4()) # <- required by login_manager.init_app(app)

bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'index'


@app.route('/', methods=['GET','POST'])
def index():
        page_name = '/'
        if request.method == 'POST':
                email = request.form['email']
                candidate_password = request.form['password']
                user = finduserindbbyemail(email)
                if user != None:
                        password_hash = checkuserpasswordindb(email)
                        if bcrypt.check_password_hash(password_hash, candidate_password):
                                user_object = User(user)
                                result = login_user(user_object) # <- here for successful login
                                return redirect(url_for('loggedin', user_object=type(user_object), user=user, result=result, current_user=current_user))
                        else:
                                user_object = User(user)
                                error_message = "The password you entered is incorrect"
                                return render_template('index.html', error_message=error_message)
                else:
                        error_message = "The email address you entered does not match any we have in our records"
                        return render_template('index.html', error_message=error_message)

        if request.method == 'GET':
                return render_template('index.html')

我有一个User类和一个用户回调:

I have a User class and a user callback:

class User():

        def __init__(self, user):
                self.user = user

        def is_authenticated(self):
                return True

        def is_active(self):
                return True

        def is_anonymous(self):
                return False

        def get_id(self):
                return unicode(self.user)

@login_manager.user_loader
def load_user(user):
        con = psycopg2.connect(database=pgsql_db1name, user=pgsql_dbuser, password=pgsql_dbpassword, host='localhost')
        uuid = "'"+user+"'"
        cur = con.cursor()
        cur.execute("SELECT uuid FROM users WHERE uuid = "+ uuid)
        uuid = cur.fetchone()
        con.close()
        if uuid != None:
                user = unicode(uuid[0])
                return User.get_id(user)
        else:
                return None

身份验证成功后(显然吗?),用户将被重定向到具有 @login_required 装饰器的登录页面.但是,该应用程序没有加载登录页面,而是将用户重定向到登录页面,告诉我该用户没有登录?如果尝试将值发送到页面,并且我删除了 @login_required 装饰器,以便可以看到页面,则这是我在登录"后在浏览器中看到的内容:

After authentication is successful (apparently?), the user is redirected to a loggedin page which has a @login_required decorator. But instead of loading the loggedin page, the app redirects the user to the login page, telling me the user isnt being logged in? If try to send values to the page and i remove the @login_required decorator so i can see the page, this is what i see in the browser after 'logging in':

current_user.is_authenticated() = False
current_user.is_active() = False
current_user.is_anonymous() = True
current_user.get_id() = None
user_object = <type 'instance'>
user = 2ca1296c-374d-43b4-bb7b-94b8c8fe7e44
login_user = True
current_user = <flask_login.AnonymousUserMixin object at 0x7f2aec80f190> Logout

好像我的用户尚未登录,并被视为匿名用户?谁能看到我做错了吗?我在理解它应该如何工作时遇到了很多麻烦.

It looks like my user hasn't been logged and is being treated as anonymous? Can anyone see what I've done wrong? I'm having a lot of trouble understanding how this is supposed to work.

推荐答案

通过登录表单后,您可能无法登录用户或current_user的另一个原因是匿名的:在用户上设置了active = false标志在数据库中.此行为已在文档中确认:

Another reason you might not be able to log a user in or current_user is Anonymous after going through your login form: The active=false flag is set on the user in the db. This behavior is confirmed in the docs:

flask_login.login_user(用户,记住= False,持续时间=无,强制= False,新鲜= True)[源代码]登录用户.您应该将实际的用户对象传递给该用户.如果用户的is_active属性为False,则除非强制为True,否则他们将不会登录.

flask_login.login_user(user, remember=False, duration=None, force=False, fresh=True)[source] Logs a user in. You should pass the actual user object to this. If the user’s is_active property is False, they will not be logged in unless force is True.

如果登录尝试成功,它将返回True;否则,将返回False(即,由于用户处于非活动状态).

This will return True if the log in attempt succeeds, and False if it fails (i.e. because the user is inactive).

因此,当您调用login_user时,您可以执行以下操作: login_user(用户,记住= form.remember_me.data,force = True),如果要允许不活动的用户登录.

So, when you call login_user, you can do this: login_user(user, remember=form.remember_me.data, force=True), if you want to allow inactive users to log in.

这篇关于登录后,flask-login用户设置为匿名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆