#-*- coding: utf-8 -*-
from passlib.apps importcustom_app_context as pwd_contextimportconfigimportMySQLdb,datetimefrom itsdangerous importTimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpiredclassQXPasswd(object):def __init__(self, password):
self.password=passworddefgenerate_password(self):
password_hash=pwd_context.encrypt(self.password)returnpassword_hashdefverify_password(self, password_hash):returnpwd_context.verify(self.password, password_hash)classQXToken(object):def __init__(self, name):
self.name=namedef generate_auth_token(self, expiration = 3600):
s= Serializer(config.SECRET_KEY, expires_in =expiration)return s.dumps({'name': self.name })defverify_auth_token(self, token):
s=Serializer(config.SECRET_KEY)try:
data=s.loads(token)exceptSignatureExpired:return None #valid token, but expired
exceptBadSignature:return None #invalid token
return data['name'] ==self.name#插入一条用户密码加密的数据
'''conn = MySQLdb.connect(host="localhost", user="root", passwd="", db='qixin', port=3306, charset="utf8")
cursor = conn.cursor()
now = datetime.datetime.now()
currentTime = now.strftime("%Y-%m-%d %H:%M:%S")
sql = "insert into qx_user(username,password,addTime) values(%s, %s, %s)"
u = QXPasswd('123456')
value = ['zl', u.generate_password(), currentTime]
cursor.execute(sql, value)
conn.commit()'''
#验证用户密码正确性
'''conn = MySQLdb.connect(host="localhost", user="root", passwd="", db='qixin', port=3306, charset="utf8")
cursor = conn.cursor()
sql="select username, password from qx_user where username = 'zl'"
cursor.execute(sql)
row = cursor.fetchone()
u = QXPasswd('123456')
print u.verify_password(row[1])'''
#生成用户token
'''token = QXToken('zl')
print token.generate_auth_token()'''
#验证token
token = QXToken('zl')print token.verify_auth_token('eyJhbGciOiJIUzI1NiIsImV4cCI6MTQ2NDI1NzI4OCwiaWF0IjoxNDY0MjUzNjg4fQ.eyJuYW1lIjoiemwifQ.iVlCfzIk5YMXhlzO3lOqHBBtYTiJV3_ze8wUR80GWAc')