class Statics: tjw_access_token = TJWSS(Constants.JWT_SECRET_KEY, Constants.JWT_ACCESS_TIME) tjw_refresh_token = TJWSS(Constants.JWT_SECRET_KEY, Constants.JWT_REFRESH_TIME) rpcs = { 'smart_search': RPCTarget('127.0.0.1', 9091, path='rpc/v1/bookfinder'), 'douban': RPCTarget('127.0.0.1', 9092) }
def verify_auth_token(token): t = TJWSS(current_app.config['SECRET_KEY']) try: data = t.loads(token) except: return None return User.query.get(data['id'])
def post(self, request): form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('name') password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') user = User.objects.create_user(username=username, password=password, email=email) user.is_active = 0 # 设置激活状态 user.save() print(username, password, email) # 加密 tjwss = TJWSS(settings.SECRET_KEY, 900) info = {'confirm': user.id} token = tjwss.dumps(info).decode() # 发送邮件 send_signup_active_mail.delay(email, username, token) return redirect(reverse('index')) else: return render(request, 'signup.html', {'form': form})
def validate(self, attrs): tjwss = TJWSS(settings.SECRET_KEY, 300) try: data = tjwss.loads(attrs['access_token']) except: raise serializers.ValidationError('无效的access_token') openid = data.get('openid') attrs['openid'] = openid conn = get_redis_connection('sms_code') real_sms_code = conn.get('sms_code_%s' % attrs['mobile']) if not real_sms_code: raise serializers.ValidationError('短信验证码失效') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码输入错误') try: user = User.objects.get(mobile=attrs['mobile']) except: return attrs else: if not user.check_password(attrs['password']): raise serializers.ValidationError('密码错误') attrs['user']=user return attrs
def Decode(token): salt = "xSrIG63Ov0dg" tjwss = TJWSS(salt, 10000) try: data = tjwss.loads(token) return data except: return -1
def MakeCode(username): salt = "xSrIG63Ov0dg" payload = { "username": "", } tjwss = TJWSS(salt, 10000) payload['username'] = username token = tjwss.dumps(payload).decode() return token
def userverify_token(value): token = TJWSS(USERPASSWORD_CONFIG['tokensecretkey']) try: data = token.loads(value) except SignatureExpired: return 'valid token, but expired' except BadSignature: return 'invalid token' # return data #此时返回的data已经解密了。可以看到里面的内容 return True
def confirm(self,token): t = TJWSS(current_app.config['SECRET_KEY']) try : data = t.loads(token) except : return False if data.get('id') != self.id : return False self.confirmed = True db.session.add(self) return True
def post(self, request): form = ForgetPasswordFrom(request.POST) if form.is_valid(): email = form.cleaned_data['email'] user = User.objects.get(email=email) tjwss = TJWSS(settings.SECRET_KEY, 900) info = {'confirm': user.id} token = tjwss.dumps(info).decode() send_forget_password_mail.delay(email, user.username, token) return HttpResponse("发送成功") else: return render(request, 'forget_pwd.html', {'form': form})
def get(self, request, token): form = ResetPasswordFrom() tjwss = TJWSS(settings.SECRET_KEY, 900) print(token) try: # 获取解密信息 info = tjwss.loads(token) user_id = info['confirm'] user = User.objects.get(id=user_id) request.user = user print(request.user, "&&&&&&&&&&&&&&&&&&&&&&get") return render(request, 'reset_pwd.html', {'form': form}) except SignatureExpired as e: return HttpResponse('链接已过期')
def active(request, token): ''' 激活 ''' if request.method == 'GET': tjwss = TJWSS(settings.SECRET_KEY, 900) try: # 获取解密信息 info = tjwss.loads(token) user_id = info['confirm'] user = User.objects.get(id=user_id) user.is_active = 1 # 修改激活状态 user.save() return redirect(reverse('login')) except SignatureExpired as e: # 激活链接过期 # username = token_confirm.remove_validate_token(token) # user = User.objects.get(id=user_id) request.user.delete() return HttpResponse('链接已过期')
def gen_confirm_token(self,exp=3600): t =TJWSS(current_app.config['SECRET_KEY'],exp) #加密 return t.dumps({'id':self.id})
from flask import Flask from flask_cors import CORS from flask_restful import reqparse, Api, Resource from utils.logger import logger from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS from itsdangerous import BadSignature, BadData, BadHeader, BadPayload, BadTimeSignature app = Flask(__name__) CORS(app, supports_credentials=False) app.config["JWT_SECRET_KEY"] = "my-super-secret" # Change this! app.config["JWT_HEADER_TYPE"] = "" app.config["JWT_HEADER_NAME"] = "Authorization" tjw_access_token = TJWSS(app.config["JWT_SECRET_KEY"], 60 * 5) tjw_refresh_token = TJWSS(app.config["JWT_SECRET_KEY"], 60 * 60 * 24 * 30) def create_access_token(identity: str = None) -> str: if identity is None: return "" return tjw_access_token.dumps(identity).decode() def create_refresh_token(identity: str = None) -> str: if identity is None: return "" return tjw_refresh_token.dumps(identity).decode() def args_required_method(parser): def decorator(fn): def wrapper(*args, **kwargs):
from flask import Flask,request,render_template,redirect,url_for,jsonify,session,make_response from flask_sqlalchemy import SQLAlchemy import pymysql,datetime,time,json,random,hashlib from PIL import Image from var_dump import var_dump from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/notes" app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY']='leave notes when' EXPIRE_TIME = 60000 tjwss = TJWSS(app.config['SECRET_KEY'],expires_in=EXPIRE_TIME) db = SQLAlchemy(app) class Users(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(40), nullable=True) password_hash = db.Column(db.String(256), nullable=True) email = db.Column(db.String(80), nullable=True, unique=True) #role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(256), nullable=True) confirmed = db.Column(db.Boolean, default=False) reg_time = db.Column(db.Integer) log_time = db.Column(db.Integer) token = db.Column(db.String(40),nullable=True,unique=True) expire_time = db.Column(db.Integer,nullable=True) ip = db.Column(db.String(50),nullable=True) def __init__(self,email,password_hash,username): if username == None: username = ''
def generate_token(value): token = TJWSS(USERPASSWORD_CONFIG['tokensecretkey'], expires_in=USERPASSWORD_CONFIG['tokenexpiration']) return token.dumps(value)
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS, SignatureExpired, BadData import time salt = "adsafergberhere" payload = { "name": "dawsonenjoy", } tjwss = TJWSS(salt, 1) # 实例化jwt序列化对象,设置salt和超时时间,这里设置1s后超时 token = tjwss.dumps(payload).decode() # 编码payload数据,生成token data = tjwss.loads(token) # 校验和解码token print(data) time.sleep(2) # 2s后让token超时 try: print(tjwss.loads(token)) except SignatureExpired: print("token超时") except BadData: print("认证失败")
def generate_auth_token(self, expiration): t = TJWSS(current_app.config['SECRET_KEY'], expires_in=expiration) return t.dumps({'id': self.id}).decode('utf-8')
class Statics: tjw_access_token = TJWSS(Constants.JWT_SECRET_KEY, Constants.JWT_ACCESS_TIME) tjw_refresh_token = TJWSS(Constants.JWT_SECRET_KEY, Constants.JWT_REFRESH_TIME)