def get_response(self, method, signed_data, get_header): if method != 'POST': return (405, ['POST']) public_key = get_header(PUBLIC_KEY_HEADER, None) if not public_key: return (400, "No public key") private_key = self.get_private_key(public_key) if not private_key: return (400, "Invalid public key") signer = TimedSerializer(private_key) try: data = signer.loads(signed_data, max_age=self.max_age) except SignatureExpired: return (400, "Signature expired") except BadSignature: return (400, "Bad Signature") try: raw_response_data = self.provide(data) except: self.report_exception() return (400, "Failed to process the request") response_data = signer.dumps(raw_response_data) return (200, response_data)
def processReset(form): username = sanitize(form.username.data) password = sanitize(form.password.data) email = None status = None token = None cursor, dbconn = dbConnection() query = "SELECT * FROM users WHERE username = %s" query_result = cursor.execute(query, [username]) if int(query_result) <= 0: status = "No Such User Exists..!!" else: email = cursor.fetchone()[4] url_serial = URLSafeSerializer( "XHhkMVx4OTgzXFxceDhmZilceDk2Ilx4MTZceDhkXHhhYlx4ZGFceDlkXHhiYUNHXHhlM1x4YTRceDFiK0RceGNhfg==" ) timed_serial = TimedSerializer( "XHhkMVx4OTgzXFxceDhmZilceDk2Ilx4MTZceDhkXHhhYlx4ZGFceDlkXHhiYUNHXHhlM1x4YTRceDFiK0RceGNhfg==" ) token = timed_serial.dumps(url_serial.dumps([username, password])) cursor.close() dbconn.close() return status, email, token
def enable_two_factor(): """ Switch two factor auth on for the currently logged in user. """ secret = pyotp.random_base32() provisioning_url = pyotp.totp.TOTP(secret).provisioning_uri( current_user.username, issuer_name=current_app.config["FLOWAUTH_TWO_FACTOR_ISSUER"], ) signed_secret = TimestampSigner( current_app.config["SECRET_KEY"]).sign(secret) backup_codes = generate_backup_codes() serialised_codes = TimedSerializer( current_app.config["SECRET_KEY"]).dumps(backup_codes) return ( jsonify({ "provisioning_url": provisioning_url, "secret": signed_secret.decode(), "issuer": current_app.config["FLOWAUTH_TWO_FACTOR_ISSUER"], "backup_codes": backup_codes, "backup_codes_signature": serialised_codes, }), 200, )
def test_push_tr(self): credits = [] tr = m.TradeRequest( quantity=sum(xrange(1, 20)), type="sell", currency="TEST" ) db.session.add(tr) for i in xrange(1, 20): c = m.CreditExchange( amount=i, sell_req=tr, currency="TEST", address="test{}".format(i)) credits.append(c) db.session.add(c) db.session.commit() push_data = {'trs': {tr.id: {"status": 6, "quantity": "1000", "fees": "1"}}} db.session.expunge_all() with self.app.test_request_context('/?name=Peter'): flask.g.signer = TimedSerializer(self.app.config['rpc_signature']) flask.g.signed = push_data update_trade_requests() db.session.rollback() db.session.expunge_all() previous = 0 for credit in m.CreditExchange.query.all(): print credit.id, credit.amount, credit.sell_amount assert credit.sell_amount > previous previous = credit.sell_amount assert m.TradeRequest.query.first()._status == 6
def __init__(self, base_url, public_key, private_key): self.base_url = base_url self.public_key = public_key self.signer = TimedSerializer(private_key)
def check_token_password(self, token): serializer = TimedSerializer(current_app.config['SECRET_KEY']) full_token = '"' + self.email + '".' + token return serializer.loads(full_token, max_age=1800)
def get_email_confirmation_token_info(token, max_age=1800): s = TimedSerializer(current_app.secret_key, "user_id_email_confirm") try: return s.loads(token, max_age=max_age) except Exception as e: return None
def get_reset_token(user_id): s = TimedSerializer(current_app.secret_key, "user_id_reset") return s.dumps(user_id)
def encrypt_token(user_id, secret_key, expiration=1800): '''Encrypts a user id into a timed token. Default expiration time is 30 minutes.''' ts = TimedSerializer(secret_key, expires_in=expiration) return ts.dumps({ 'id': user_id })
def __init__(self, config): self.signer = TimedSerializer(config['shared_secret']) super(Auth_webSilvia, self).__init__(config)
def forgot_password(email, team_name): s = TimedSerializer(app.config['SECRET_KEY']) token = s.dumps(team_name) text = get_tip('MAIL_MSG_FORGOT').format(url_for('auth.reset_password', _external=True), base64encode(token, urlencode=True)) sendmail(email, text)
def generate_timed_token(user_dict): s = TimedSerializer(SECRET_KEY) return s.dumps(user_dict)
def check_signature(): g.signer = TimedSerializer(current_app.config['rpc_signature']) try: g.signed = g.signer.loads(request.data) except BadData: abort(403)
admin = Admin(app, index_view=MyAdminIndexView()) admin.add_view(UserView(collection)) # Mail configuration app.config['MAIL_SERVER'] = MAIL_SERVER app.config['MAIL_USERNAME'] = MAIL_USERNAME app.config['MAIL_PASSWORD'] = MAIL_PASSWORD app.config['MAIL_DEFAULT_SENDER'] = MAIL_DEFAULT_SENDER app.config['MAIL_PORT'] = MAIL_PORT app.config['MAIL_USE_SSL'] = MAIL_USE_SSL app.config['MAIL_USE_TLS'] = MAIL_USE_TLS app.config['MAIL_ASCII_ATTACHMENTS'] = MAIL_ASCII_ATTACHMENTS app.config['USER_ENABLE_EMAIL'] = True mail = Mail(app) URL_SERIALYZER = URLSafeTimedSerializer(APP_SECRET_KEY) TOKEN_SERIALIZER = TimedSerializer(APP_SECRET_KEY) # images handle photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = IMAGES_PATH configure_uploads(app, photos) @app.route('/') def index(): return render_template("index.html") @app.route("/about") def about(): return render_template("about.html")
def _dump(secret, d, salt=None, expires_in=None): if expires_in: s = TimedSerializer(secret, expires_in=expires_in) else: s = Serializer(secret) return s.dumps(d, salt=salt)
def get_reset_token(self, expires_sec=1800): s = TimedSerializer(current_app.config['SECRET_KEY'], expires_sec) return s.dumps({'user_id': self.id}).decode('utf-8')
def _get_token_serializer(): return TimedSerializer(client_secret)
def generate_reset_token(self): s = TimedSerializer(current_app.config['SECRET_KEY']) return s.dumps({'confirm': self.id}, salt="please give some salt")
def confirm_user(data=None): if not utils.get_config('verify_emails'): # If the CTF doesn't care about confirming email addresses then redierct to challenges return redirect(url_for('challenges.challenges_view')) logger = logging.getLogger('regs') # User is confirming email account if data and request.method == "GET": try: s = TimedSerializer(app.config['SECRET_KEY']) email = s.loads(utils.base64decode(data, urldecode=True), max_age=1800) except BadTimeSignature: return render_template( 'confirm.html', errors=['Your confirmation link has expired']) except (BadSignature, TypeError, base64.binascii.Error): return render_template( 'confirm.html', errors=['Your confirmation token is invalid']) team = Teams.query.filter_by(email=email).first_or_404() team.verified = True db.session.commit() logger.warn( "[{date}] {ip} - {username} confirmed their account".format( date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'), email=team.email.encode('utf-8'))) db.session.close() if utils.authed(): return redirect(url_for('challenges.challenges_view')) return redirect(url_for('auth.login')) # User is trying to start or restart the confirmation flow if not utils.authed(): return redirect(url_for('auth.login')) team = Teams.query.filter_by(id=session['id']).first_or_404() if data is None: if request.method == "POST": # User wants to resend their confirmation email if team.verified: return redirect(url_for('views.profile')) else: utils.verify_email(team.email) logger.warn( "[{date}] {ip} - {username} initiated a confirmation email resend" .format(date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'), email=team.email.encode('utf-8'))) return render_template( 'confirm.html', team=team, infos=['Your confirmation email has been resent!']) elif request.method == "GET": # User has been directed to the confirm page team = Teams.query.filter_by(id=session['id']).first_or_404() if team.verified: # If user is already verified, redirect to their profile return redirect(url_for('views.profile')) return render_template('confirm.html', team=team)
def generate_signup_token(self, email): serializer = TimedSerializer( settings.ITSDANGEROUS_KEY, serializer=URLSafeSerializer(settings.ITSDANGEROUS_KEY), ) return serializer.dumps(email, salt="signup")
def get_email_confirmation_token(user_id): s = TimedSerializer(current_app.secret_key, "user_id_email_confirm") return s.dumps(user_id)
def generate_token(expiration=600, **kwargs): s = TimedSerializer(config.parser.get('security', 'secret'), expires_in=expiration) return s.dumps(kwargs).decode('UTF-8')
def get_token(self): serializer = TimedSerializer(current_app.config['SECRET_KEY']) token = serializer.dumps(self.email) return token
def _get_token_serializer(): return TimedSerializer(current_app.config['SECRET_KEY'])
def get_token(self, expires_in): timed_serializer = TimedSerializer(current_app.config['SECRET_KEY'], expires_in) return timed_serializer.dumps({ 'user_email': self.email }).decode('utf-8')
def generate_auth_token(self): s = TimedSerializer(secret_key) return s.dumps(self.id)
import os # import django # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings') # django.setup() from celery import Celery from django.core.mail import send_mail from django.conf import settings from itsdangerous import TimedJSONWebSignatureSerializer as TimedSerializer from goods.models import Goods, GoodsType, GoodsSKU, GoodsImage, IndexGoodsBanner, IndexTypeGoodsBanner, IndexPromotionBanner from django.template import loader # 初始化Celery类的对象 app = Celery('celery_tasks.tasks', broker="redis://192.168.1.110:6379/8") # 生成48小时有效期的私钥 TIMEDSER48 = TimedSerializer(settings.SECRET_KEY, 48 * 3600) @app.task def send_register_active_email(to_email, username, token): """ 发送激活邮件的方法 :param to_email: 收件人的邮箱地址 :param username: 激活邮件中需要包含用户名信息 :param token: 激活邮件内容需要包含用户加密信息的token :return: None """ # 发邮件 subject = "天天生鲜欢迎信息" message = "" # 发送包含html标签的邮件内容时需要使用html_message
def reset_password(data=None): logger = logging.getLogger('logins') if data is not None and request.method == "GET": return render_template('reset_password.html', mode='set') if data is not None and request.method == "POST": try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(utils.base64decode(data, urldecode=True), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=['Your link has expired']) except: return render_template( 'reset_password.html', errors=['Your link appears broken, please try again']) team = Teams.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt(request.form['password'].strip()) db.session.commit() logger.warn( "[{date}] {ip} - successful password reset for {username}".format( date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'))) db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() errors = [] if utils.can_send_mail() is False: return render_template( 'reset_password.html', errors=[ 'Email could not be sent due to server misconfiguration' ]) if not team: return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) s = TimedSerializer(app.config['SECRET_KEY']) token = s.dumps(team.name) text = """ Did you initiate a password reset? {0}/{1} """.format(url_for('auth.reset_password', _external=True), utils.base64encode(token, urlencode=True)) utils.sendmail(email, text) return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) return render_template('reset_password.html')
def reset_password(data=None): if data is not None and request.method == "GET": return render_template('reset_password.html', mode='set') if data is not None and request.method == "POST": try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(urllib.unquote_plus(data.decode('base64')), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=['Your link has expired']) except: return render_template( 'reset_password.html', errors=['Your link appears broken, please try again.']) if not request.form.get('password'): return render_template('reset_password.html', mode='set', errors=['Pick a longer password']) elif len(request.form['password']) > 128: return render_template('reset_password.html', mode='set', errors=['Pick a shorter password']) elif request.form['password'] != request.form.get('password-confirm'): return render_template('reset_password.html', mode='set', errors=["These passwords don't match"]) team = Teams.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt(request.form['password'].strip()) db.session.commit() db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() if not team: return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) s = TimedSerializer(app.config['SECRET_KEY']) token = s.dumps(team.name) text = """ Did you initiate a password reset? {0}/{1} """.format(url_for('auth.reset_password', _external=True), urllib.quote_plus(token.encode('base64'))) sendmail(email, text) return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) return render_template('reset_password.html')
def timed_serializer(): return TimedSerializer(config.parser.get('security', 'secret'))