How to implement user_loader callback in Flask-Login

前端 未结 3 2210
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 16:57

I\'m attempting to use Flask and the Flask-Login extension to implement user authentication in a Flask app. The goal is to pull user account information from a database and then

3条回答
  •  走了就别回头了
    2021-01-30 17:47

    Here is my code, another User as data mapping object provide query_pwd_md5 method.

    User login:

    @app.route('/users/login', methods=['POST'])
    def login():
        # check post.
        uname = request.form.get('user_name')
        request_pwd = request.form.get('password_md5')
    
        user = User()
        user.id = uname
    
        try:
            user.check_pwd(request_pwd, BacktestUser.query_pwd_md5(
                uname, DBSessionMaker.get_session()
            ))
            if user.is_authenticated:
                login_user(user)
                LOGGER.info('User login, username: {}'.format(user.id))
                return utils.serialize({'userName': uname}, msg='login success.')
            LOGGER.info('User login failed, username: {}'.format(user.id))
            return abort(401)
        except (MultipleResultsFound, TypeError):
            return abort(401)
    

    User class:

    class User(UserMixin):
    """Flask-login user class.
    """
    
    def __init__(self):
        self.id = None
        self._is_authenticated = False
        self._is_active = True
        self._is_anoymous = False
    
    @property
    def is_authenticated(self):
        return self._is_authenticated
    
    @is_authenticated.setter
    def is_authenticated(self, val):
        self._is_authenticated = val
    
    @property
    def is_active(self):
        return self._is_active
    
    @is_active.setter
    def is_active(self, val):
        self._is_active = val
    
    @property
    def is_anoymous(self):
        return self._is_anoymous
    
    @is_anoymous.setter
    def is_anoymous(self, val):
        self._is_anoymous = val
    
    def check_pwd(self, request_pwd, pwd):
        """Check user request pwd and update authenticate status.
    
        Args:
            request_pwd: (str)
            pwd: (unicode)
        """
        if request_pwd:
            self.is_authenticated = request_pwd == str(pwd)
        else:
            self.is_authenticated = False
    

提交回复
热议问题