#coding=utf8
from app import db,login_manager
from config import Config
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired,BadSignature
class User(UserMixin,db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(32), index = True)
password_hash = db.Column(db.String(12)
email = db.Column(db.String(30))
@staticmethod
def verify_auth_token(token):
print token
s = Serializer('mystr')
try:
data = s.loads(token)
except SignatureExpired:
print "过期"
return None # valid token, but expired
except BadSignature as bs:
print bs
return None # invalid token
user = User.query.get(data['id'])
return user
--------api view----------------文件
#coding:utf-8
from flask import abort,url_for
from flask_restful import reqparse,Resource,abort,fields, marshal_with
from . import api
from flask_httpauth import HTTPBasicAuth,HTTPTokenAuth
from app.utils import Fix_Url,serialize
from app.account.models import User
# ...
@auth.verify_token
def verify_token(token):
res=User.verify_auth_token(token)
print res,"123"
if res:
return True
# user=User.query.all()
users=[ serialize(user) for user in User.query.all()]
def abort_if_todo_doesnt_exist(id):
user = list(filter(lambda t:t['id']==int(id),users))
if not user:
abort(404, message="Todo {} doesn't exist".format(id))
else:
return user[0]
class GetToken(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('username', type = str, required = True,
help = 'No username provided', location=['json','form','args'])
self.reqparse.add_argument('password', type = str, required = True,
help = 'No user password provided', location=['json','form','args'])
super(GetToken, self).__init__()
def post(self):
"""Can be execute when receive HTTP Method `POST`."""
args = self.reqparse.parse_args()
user = User.query.filter_by(username=args['username']).first()
# Check the args['password'] whether as same as user.password.
if user.verify_password(args['password']):
# serializer object will be saved the token period of time.
user=abort_if_todo_doesnt_exist(id)
if args.has_key('id'):
abort(500, message="user's ID can not be change"
for key in args.keys():
if key =='id' or not args[key]:
args.pop(key)
user.update(args)
return user, 201
但是通过访问http://127.0.0.1:5000/api/v1.0/users/2 通过heders 传Authorization参数去api view 里面去验证就回报反签名失败的错误Signature 'YkDiicE28E3j-y7i80HbVMGG4LR6XEFsAl6OTofMlps' does not match