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'})