简体   繁体   English

登录正常,但current_user未通过身份验证

[英]Login working but current_user not authenticated

My login is working but a current user is not being created / is not authenticated. 我的登录名有效,但是当前用户未创建/未通过身份验证。

Login manager: 登录管理员:

@login_manager.user_loader
    def load_user(username):
    #users is my mongodb collection
    user = users.find_one({"_id": username})
    if not user:
       return None
    return User(user['_id'])

Login route: 登录路线:

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

  login = LoginForm()

  if current_user.is_authenticated:
    return redirect(url_for('feed'))

  if login.submit.data and login.validate():
      #users is my mongodb collection
      user = users.find_one({"email": login.email.data})
      if user and User.validate_login(user['password'], login.password.data):
        user_obj = User(json_util.dumps(user['_id']))
        login_user(user_obj, remember=login.remember.data)
        flash(f'Login Successful, welcome {user["name"]}.', 'success')
        return redirect(url_for('feed'))
      else:
        flash('Login Unsuccessful. Please check email and password', 'warning')

  return render_template(
    'login.html',
    login=login
  )

User class: 用户类别:

class User():

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

def is_authenticated(self):
    return True

def is_active(self):
    return True

def is_anonymous(self):
    return False

def get_id(self):
    return self.username

@staticmethod
def validate_login(password_hash, password):
    return bcrypt.check_password_hash(password_hash, password)

Feed route: 送料路线:

@app.route("/feed")
def feed():

  if not current_user.is_authenticated:
    #flash(f'{current_user.is_authenticated} {current_user._id}', 'warning')
    return redirect(url_for('welcome'))

#etc etc 

After being logged in the user is meant to be redirect to the feed route, this works however you are redirected back due to not being authenticated. 登录后,用户将被重定向到供稿路由,此方法有效,但是由于未通过身份验证,您被重定向回。

I've seen session be used to get around this problem however still curious to the solution of this. 我已经看到会话可用于解决此问题,但是仍然对此解决方案感到好奇。

Sources I've consulted: 我咨询过的资料:

Solution: I was searching mongoDB using a string instead of an ObjectId in the load_user. 解决方案:我正在使用字符串而不是load_user中的ObjectId搜索mongoDB。 I worked this out my switching to searching with the users imputed email, it working and I noticed my problem. 我解决了这一问题,转而使用用户推定的电子邮件进行搜索,该方法可以正常工作,并且我注意到了我的问题。

@login_manager.user_loader
def load_user(user_id):
    user = users.find_one({"_id": ObjectId(user_id)})
    if not user:
        return None
    return User(str(user['_id'])

Lesson learnt, strings != ObjectId(s). 获得的经验教训,字符串!= ObjectId(s)。 I hope this helps anyone who is having a similar problem! 希望这对遇到类似问题的人有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM