Skip to content

Instantly share code, notes, and snippets.

@jt-wang
Created February 18, 2016 15:47
Show Gist options
  • Save jt-wang/c9dac553c78c79df5752 to your computer and use it in GitHub Desktop.
Save jt-wang/c9dac553c78c79df5752 to your computer and use it in GitHub Desktop.
class User(flask_login.UserMixin):
    def __init__(self, username):
        self.username = username
        self.id = username
        
    @staticmethod
    def get(username):
        return User(username)

    @staticmethod
    def exist_in_db(username):
        try:
            users = db.users # use pymongo
            result = users.find_one({'username': username})
            if result:
                return True
            else:
                return False
        except pymongo.errors.PyMongoError as error:
            return False
login_manager = flask_login.LoginManager()
login_manager.init_app(app)


@login_manager.user_loader  # reload the user from session
def user_loader(username):
    if not User.exist_in_db(username):
        Logger.debug('user does not exist in user_loader')
        return
    else:
        user = User.get(username)
        return user


@login_manager.request_loader  # load the user from request
def request_loader(request):
    if request.method != 'POST':
        return
    else:
        username = request.form['username']
        password = request.form['password']
        if not User.exist_in_db(username):
            return
        else:
            status = User.auth(username, password)['status']
            if status == True:
                return User.get(username)
            else:
                return


@login_manager.unauthorized_handler
def unauthorized_handler():
    return flask.jsonify({'status': False,'cause': 'unauthorized'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment