def login(): """ 登录 api 接口 :return: 结果 json """ # POST username/password username = request.form.get('username') # TODO 可采用邮箱登录 password = request.form.get('password') # print(request.form) if not username or not password: # parameters are invalid return value_error(u"无效的用户名或密码") try: user = User(name=username) if user and user.verify_password(password): # login_manager 保存登录状态 login_user(user, remember=True) # TODO 可让用户选择是否保存登录状态 # ajax response # 生成 token tokens = user.generate_access_token() tokens.update(success=1, message=u'登录成功') response = jsonify(tokens) response.status_code = 200 return response else: return value_error(u"用户名或密码错误") except: return action_failed(u'查找用户失败')
def verify_password(username, password): authorization = request.headers.get('Authorization', '').split(' ') bearer = authorization[1] if len(authorization) > 1 else '' if bearer: g.current_user = User.verify_access_token(bearer) g.token_used = True return g.current_user is not None if username == '': g.current_user = AnonymousUser() return True user = User(username=username) if not user or not user.user_id: return False g.current_user = user g.token_used = False return user.verify_password(password)
def grant_token(): username = request.form.get('username') or request.args.get('username') password = request.form.get('password') or request.args.get('password') if not username or not password: # parameters are invalid return value_error(u"无效的用户名或密码") try: user = User(name=username) if user and user.verify_password(password): # ajax response # 生成 token tokens = user.generate_access_token() tokens.update(success=1, message=u'登录成功') response = jsonify(tokens) response.status_code = 200 return response else: return value_error(u"用户名或密码错误") except: return action_failed(u'查找用户失败')