def reset(): status = Status() form = Form(request.forms) token = request.query.token s = URLSafeTimedSerializer(secret_key, max_age=3600, salt=salt) try: username = s.loads(token) except: return abort(500, 'bad signature') else: if request.method == 'POST' and form.validate(): new_pbkdf2 = to_bytes(pbkdf2_sha256.encrypt(form.password.data)) try: conn = db.engine.connect() conn.execute(users.update().values( pbkdf2=new_pbkdf2).where(users.c.id == username)) conn.close() except exc.SQLAlchemyError as message: status.danger = message else: status.success = 'Password Changed. Please log in.' return render_template('/status.html', status=status) return render_template('/action/reset.html', status=status, form=form, username=username, token=token)
def token(self): config = current_app.config secret_key = config.setdefault("SECRET_KEY") salt = config.setdefault("SECURITY_PASSWORD_SALT") serializer = URLSafeTimedSerializer(secret_key) token = serializer.dumps(self.username, salt=salt) return token
def registration(self): form = UserForm() if request.method == "GET": return render_template("registration.html", form=form) if form.validate_on_submit(): g.current_user = {} name = form.name.data password = bcrypt.hashpw(form.password.data.encode("utf-8"), bcrypt.gensalt(12)).decode("utf-8") email = form.email.data user = User(name, password, email) g.db_session.add(user) g.db_session.commit() serializer = URLSafeTimedSerializer(cfg.SECRET_KEY) token = serializer.dumps(user.email, salt="myblogappconfirm") msg = Message("Hello, {}".format(name), recipients=[user.email]) href = url_for("blog.BlogView:confirm_user", _external=True, token=token) msg.html = render_template("email_confirm.html", name=name, href=href) msg.subject = "Hello, {}. Verify your email please!".format(name) g.mail_manager.send(msg) return redirect(blp_url("BlogView:index")) else: return render_template("registration.html", form=form)
def generate_security_token(self): """Generate a security token.""" serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) return serializer.dumps(self.email, salt=current_app.config[ 'SECURITY_PASSWORD_SALT' ])
def email_change_hash(request, email_change_hash=None, group=None): s = URLSafeTimedSerializer(getattr(settings, 'EMAIL_CHANGE_SECRET', '87fuhaidfhahfokhh3u')) email_data = None signature_expired = False invalid_user = False try: email_data = s.loads(email_change_hash, max_age=3600 * 24) except SignatureExpired as e: signature_expired = True except Exception as e: pass if email_data: if request.user.is_authenticated: if request.user.id != email_data['user_id']: invalid_user = True else: user = request.user user.email = email_data['email'] user.save() else: user = User.objects.get(id=email_data['user_id']) user.email = email_data['email'] user.save() return render( request, 'sphene/community/email_changed.html', {'signature_expired': signature_expired, 'invalid_user': invalid_user, 'email_data': email_data} )
def verify_email_token(token, expiration=3600): s = UrlSerializer(DevelopmentConfig.SECRET_KEY) try: email = s.loads(token, max_age=expiration) except: return False return email
class Signer(object): def __init__(self, app=None): self.app = app if app is not None: # pragma: no cover self.init_app(app) def init_app(self, app): key = app.config['ITSDANGEROUSKEY'] self.signer = URLSafeTimedSerializer(key) def loads(self, string, **kwargs): return self.signer.loads(string, **kwargs) def dumps(self, key, **kwargs): return self.signer.dumps(key, **kwargs) def generate_password_hash(self, password): return generate_password_hash(password) def check_password_hash(self, passwd_hash, password): return check_password_hash(passwd_hash, password)
def reset(): form = EmailForm() if request.method == 'POST' and form.validate_on_submit(): user = Client.query.filter_by(email=form.email.data).first_or_404() app.logger.debug( "Password reset request from {0}".format( user.email)) subject = "Password reset requested" # Here we use the URLSafeTimedSerializer we created in `util` at the # beginning of the chapter try: ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) token = ts.dumps(user.email, salt='recover-key') except Exception as e: app.logger.error(e) abort(404) recover_url = url_for( 'users.reset_with_token', token=token, _external=True) html = render_template( 'emails/recover.html', recover_url=recover_url) run_celery.send_email.apply_async( (user.email, subject, html) ) msg = u""" Please, check your email. """ flash(msg, 'error') return redirect(url_for('users.login')) return render_template('users/reset.html', form=form)
def confirm_token(token, expiration=3600): serializer = URLSafeTimedSerializer(cfg.SECRET_KEY) try: email = serializer.loads(token, salt=cfg.SECURITY_PASSWORD_SALT, max_age=expiration) except: return False return email
def generate_reset_url(user_id, email_address): ts = URLSafeTimedSerializer(main.config["SECRET_KEY"]) token = ts.dumps({"user": user_id, "email": email_address}, salt=main.config["RESET_PASSWORD_SALT"]) url = url_for('main.reset_password', token=token, _external=True) current_app.logger.debug("Generated reset URL: %s", url) return url
def get_email_token(email, salt, secret): """ Generate a timestamped token from the specified email """ ts = URLSafeTimedSerializer(secret) token = ts.dumps(email, salt=salt) return token
def generate_csrf(secret_key=None, token_key=None): """Generate a CSRF token. The token is cached for a request, so multiple calls to this function will generate the same token. During testing, it might be useful to access the signed token in ``g.csrf_token`` and the raw token in ``session['csrf_token']``. :param secret_key: Used to securely sign the token. Default is ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``. :param token_key: Key where token is stored in session for comparision. Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``. """ secret_key = _get_config( secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key, message='A secret key is required to use CSRF.' ) field_name = _get_config( token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token', message='A field name is required to use CSRF.' ) if field_name not in g: if field_name not in session: session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest() s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token') setattr(g, field_name, s.dumps(session[field_name])) return g.get(field_name)
def checkUserToken(self,token): serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) username = serializer.loads(token) if(username == self.username): return True else: return False
def timed_safe_url_load(serialized_data, max_age_in_seconds, salt='peri2organise'): """ De-serializes the serialized data into the original data. Salt can be used when generating safe URL tokens for different purposed, e.g. salt='reset_password' or salt='auth_token'. The salt must be the same as the salt used when the data was serialized. """ try: secret_key = app.config['SECRET_KEY'] except KeyError: raise Exception('A Secret Key is required to generate tokens.') else: # Ensure key is a string. if secret_key is None or not isinstance(secret_key, str): raise Exception('A Secret Key is required to generate tokens.') # Create URL safe timed serializer. serializer = URLSafeTimedSerializer(secret_key, salt=salt) try: # Try and decode the data. decoded_data = serializer.loads(serialized_data, max_age=max_age_in_seconds) except BadSignature as e: encoded_payload = e.payload if encoded_payload is not None: try: decoded_data = serializer.load_payload(encoded_payload) except BadData: return False return False else: return decoded_data
def confirm_reset_password_token(token): max_age_key = 'USERS_RESET_PASSWORD_TOKEN_MAX_AGE_IN_SECONDS' max_age = current_app.config[max_age_key] salt = current_app.config['USERS_RESET_PASSWORD_TOKEN_SALT'] serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) user, data = None, None expired, invalid = False, False try: data = serializer.loads( token, max_age=max_age, salt=salt) except SignatureExpired: d, data = serializer.loads_unsafe(token, salt=salt) expired = True except (BadSignature, TypeError, ValueError): invalid = True if data: user = User.get(id=data[0]) if not invalid and user and user.password: password_hash = hashlib.md5(user.password).hexdigest() if not safe_str_cmp(password_hash, data[1]): invalid = True expired = expired and (user is not None) logger.debug("reset password token confirmed?", expired=expired, invalid=invalid, user=user, data=data) return expired, invalid, user, data
def _verify(self, signed_token, salt, timeout = None): serializer = URLSafeTimedSerializer(self.token, salt) try: name = serializer.loads(signed_token, max_age=timeout) return self.name == serializer.loads(signed_token, max_age=timeout) except SignatureExpired: return False
def get_serializer(self): secret_key = self.app.settings.get('SECRET_KEY') if not secret_key: return None s = URLSafeTimedSerializer(secret_key, salt=self.salt) s.digest_method = self.digest_method return s
def share(self, file): file = walker.get_path(file) s = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) share_code = s.dumps({'file': str(file.relative())}) if request.args.get('modal', 'false') == 'true': return render_template('tree/share_modal.html', file=file, share_code=share_code) return render_template('tree/share.html', file=file, share_code=share_code)
def notify(): '''change notification settings params: POST: method - notification method returns: GET: change notify form POST: redirect ''' form = ChangeNotifyForm() # If user has confirmed phone, add that notify choice if g.user.phone_confirmed: form.method.choices.extend([('Text', 'Text'), ('Both', 'Both')]) if form.validate_on_submit(): if request.form['method'] != g.user.notify_method: g.user.notify_method = request.form['method'] g.user.notify_confirmed = False db.session.add(g.user) db.session.commit() flash('Updated unconfirmed settings') s=URLSafeTimedSerializer(current_app.config['SECRET_KEY'], salt=current_app.config['NOTIFY_CONFIRM_SALT']) token=s.dumps(g.user.id) msg = Message('Confirm settings', recipients=[g.user.email]) msg.body='Confirm notification changes: {0}'.format(url_for('.confirm_notify', token=token, _external=True)) mail.send(msg) logger.info('mail sent: {0}'.format(msg)) flash('Confirmation email sent') else: flash('Nothing changed') return redirect_xhr_or_normal('.profile') return render_xhr_or_normal('change_notify.html', form=form)
def get_auth_token(self): """ Encode a secure token for cookie """ login_serializer = URLSafeTimedSerializer(configuration.get('auth', 'secret_key')) data = [str(self.id), self.password] return login_serializer.dumps(data)
def verify_key(request): # TODO: convert to a decorator key = request.META.get('HTTP_ROLF_API_KEY', '') s1 = URLSafeSerializer(settings.API_SECRET, salt="rolf-ipaddress-key") try: d = s1.loads(key) # check their IP remote_addr = request.META.get( 'HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR')) if d['remote_addr'] != remote_addr: return None return get_object_or_404(User, username=d['username']) except BadSignature: # try timed key s2 = URLSafeTimedSerializer(settings.API_SECRET, salt="rolf-timed-key") try: d = s2.loads(key, max_age=60 * 60 * 24 * 7) return get_object_or_404(User, username=d['username']) except BadSignature: # invalid return None except SignatureExpired: return None return None
def load_user_from_unique_code(token): s = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return return User.query.get(data.get('unique_code'))
class Isso(object): salt = b"Eech7co8Ohloopo9Ol6baimi" def __init__(self, conf): self.conf = conf self.db = db.SQLite3(conf.get('general', 'dbpath'), conf) self.signer = URLSafeTimedSerializer(conf.get('general', 'session-key')) super(Isso, self).__init__(conf) subscribers = [] subscribers.append(Stdout(None)) if conf.get("general", "notify") == "smtp": subscribers.append(SMTP(self)) self.signal = ext.Signal(*subscribers) self.urls = Map() views.Info(self) comments.API(self) def sign(self, obj): return self.signer.dumps(obj) def unsign(self, obj, max_age=None): return self.signer.loads(obj, max_age=max_age or self.conf.getint('general', 'max-age')) def dispatch(self, request): local.request = request local.host = wsgi.host(request.environ) local.origin = origin(self.conf.getiter("general", "host"))(request.environ) adapter = self.urls.bind_to_environ(request.environ) try: handler, values = adapter.match() except HTTPException as e: return e else: try: response = handler(request.environ, request, **values) except HTTPException as e: return e except Exception: logger.exception("%s %s", request.method, request.environ["PATH_INFO"]) return InternalServerError() else: return response def wsgi_app(self, environ, start_response): response = self.dispatch(JSONRequest(environ)) return response(environ, start_response) def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response)
def handle_logging_user_out(self): serializer = URLSafeTimedSerializer(self.token.consumer.private_key) parse_result = urlparse.urlparse(self.token.redirect_to) query_dict = QueryDict(parse_result.query, mutable=True) query_dict['access_token'] = serializer.dumps(self.token.access_token) url = urlparse.urlunparse((parse_result.scheme, parse_result.netloc, parse_result.path, '', query_dict.urlencode(), '')) return HttpResponseRedirect(url)
def confirm_token(token, expiration=3600): serializer = URLSafeTimedSerializer( ALERTCONFIG.EMAIL_KEY ) try: email = serializer.loads( token, salt=ALERTCONFIG.EMAIL_SALT, max_age=expiration ) except: return False return email
def activate(): ''' Activate user account - finish the sign up process now that the email is verified - get user's password, do checks on it, and insert user into database ''' #send user to form to set password if hash is good if request.method == 'GET': #first, pull user's email and username out of hash hash = request.args.get('code') serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) try: decoded = serializer.loads(hash, salt='sign_up', max_age=3600) except SignatureExpired: flash('Activation period expired. Please sign up again.') return redirect(url_for('main.index')) except: flash("Error activating your account. Please sign up again below.") return redirect(url_for('main.index')) return render_template('activate.html', username=decoded[0], email=decoded[1]) # get user's desired password, check, add account if request.method == 'POST': username = request.form['username'] email = request.form['email'] password = request.form['password'] confirm_password = request.form['confirm_password'] #checks - password if password != confirm_password: flash("Your passwords did not match. Please try again.") return render_template('activate.html', username=username, email=email) if len(password) < 5: flash("Your password is too short. Please try again.") return render_template('activate.html', username=username, email=email) #checks - if user already completed sign up, redirect if User.query.filter_by(username=username).count() > 0: flash("You've already activated your account.") return redirect(url_for('main.index')) # use passlib to encrypt password myctx = CryptContext(schemes=['pbkdf2_sha256']) hashed_password = myctx.encrypt(password) # create a salt alphabet = string.ascii_letters + string.digits salt = ''.join(secrets.choice(alphabet) for i in range(32)) #add user user = User(username, hashed_password, salt, email) db.session.add(user) db.session.commit() login_user(user) flash('Thank you. Your account has been activated.') return redirect(url_for('main.settings'))
def createToken(emailAddress,database,token_type) : """Creates a token to be used and saves it with the salt in the database""" salt = uuid.uuid1().int ts = URLSafeTimedSerializer(sesEmail.SIGNING_KEY) token = ts.dumps(emailAddress, salt=str(salt)+token_type) #saves the token and salt pair database.saveToken(str(salt),str(token)) return urllib.quote_plus(str(token))
def validate_token(config, token, expire_time=3600): """from token and expire_time to confirm user's email""" serializer = URLSafeTimedSerializer(config['SECRET_KEY']) try: confirmed_email = serializer.loads(token, max_age=expire_time, salt=config['EMAIL']['salt']) except Exception: return False return confirmed_email
def get_email_from_token(token, salt, secret, max_age=86400): """ Read an email from a timestamped token. Raises an exception if the token is more than 24 hours old or invalid """ ts = URLSafeTimedSerializer(secret) email = ts.loads(token, salt=salt, max_age=max_age) return email
def confirm_email_token(token, expiration=86400): serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) try: email = serializer.loads(token, salt=app.config['SECURITY_SALT'], max_age=expiration) except: # should be watching for specifically BadTimeSignature and SignatureExpired # add a separate template for failed or expired confirmations return False return email
def _get_serializer(app, name): secret_key = app.config.get('SECRET_KEY') salt = app.config.get('SECURITY_%s_SALT' % name.upper()) return URLSafeTimedSerializer(secret_key=secret_key, salt=salt)
class Isso(object): def __init__(self, conf): self.conf = conf db_type = conf.get('general', 'db-type') if db_type == 'sqlite': self.db = db.SQLite3(conf.get('general', 'dbpath'), conf) elif db_type == 'psql': self.db = db_psql.PSQL(conf.get('general', 'dbpath'), conf) self.signer = URLSafeTimedSerializer( self.db.preferences.get("session-key")) self.markup = html.Markup(conf.section('markup')) self.hasher = hash.new(conf.section("hash")) super(Isso, self).__init__(conf) subscribers = [] smtp_backend = False for backend in conf.getlist("general", "notify"): if backend == "stdout": subscribers.append(Stdout(None)) elif backend in ("smtp", "SMTP"): smtp_backend = True else: logger.warn("unknown notification backend '%s'", backend) if smtp_backend or conf.getboolean("general", "reply-notifications"): subscribers.append(SMTP(self)) self.signal = ext.Signal(*subscribers) self.urls = Map() views.Info(self) views.Metrics(self) comments.API(self, self.hasher) def render(self, text): return self.markup.render(text) def sign(self, obj): return self.signer.dumps(obj) def unsign(self, obj, max_age=None): return self.signer.loads(obj, max_age=max_age or self.conf.getint('general', 'max-age')) def dispatch(self, request): local.request = request local.host = wsgi.host(request.environ) local.origin = origin(self.conf.getiter("general", "host"))(request.environ) adapter = self.urls.bind_to_environ(request.environ) try: handler, values = adapter.match() except HTTPException as e: return e else: try: response = handler(request.environ, request, **values) except HTTPException as e: return e except Exception: logger.exception("%s %s", request.method, request.environ["PATH_INFO"]) return InternalServerError() else: return response def wsgi_app(self, environ, start_response): response = self.dispatch(JSONRequest(environ)) return response(environ, start_response) def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response)
def generate_token(email, salt=None): serializer = URLSafeTimedSerializer(current_app.config.get('SECRET_KEY')) return serializer.dumps(email, salt=salt)
def generate_confirmation_token(email): serializer = URLSafeTimedSerializer('IAMSOFLUBINSECUREuuKEY') return serializer.dumps(email, salt='THl72DfWa36wdEPJOEGbe71GSCDWADuuSALT')
from __init__ import login from models import User from flask_login import login_user, logout_user, login_required, current_user import hashlib import random import math import os import urllib.request from flask import flash, url_for from werkzeug.utils import secure_filename from authy.api import AuthyApiClient import utils import smtplib from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer, SignatureExpired s = URLSafeTimedSerializer('thisissecret!') app.config['CSRF_ENABLED'] = True app.config['USER_ENABLE_EMAIL'] = True app.config.from_pyfile('config.cfg') mail = Mail(app) mail.init_app(app) app.config.from_object('config') app.secret_key = 'super-secret' api = AuthyApiClient(app.config['AUTHY_API_KEY']) @app.route('/about') def about(): return render_template('about.html', list_book_category=utils.get_book_category())
def generate_confirmation_token(email): serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) return serializer.dumps(email, salt=app.config['SECURITY_PASSWORD_SALT'])
def generate_token(email): """ generate verification token """ serializer = URLSafeTimedSerializer(app.config["SECRET_KEY"]) return serializer.dumps(email, salt=app.config["PASSWORD_SALT"])
from werkzeug.security import generate_password_hash, check_password_hash from flask import Blueprint, request, jsonify, make_response, json, url_for from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadSignature from app import app, db, models from flasgger import swag_from from .helpers import token_required, check_password, check_mail, special_character, password_match from .serializers import UserSchema, LoginSchema from .models import User mod = Blueprint('auth', __name__) mail = Mail(app) serializer = URLSafeTimedSerializer(app.secret_key) @mod.route('/auth/register', methods=['POST']) @swag_from('docs/auth_register.yml') def register(): """ User Registration """ data = request.get_json() schema = UserSchema() try: user, errors = schema.loads(request.data) except JSONDecodeError: # response for no data/invalid data
from app.forms import RegistrationForm, LoginForm, MoneyForm, NgoForm, Food_donation from app.models import User, Money, Ngo from flask_login import login_user, current_user, logout_user, login_required from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadTimeSignature from oauthlib.oauth2 import WebApplicationClient from app.paytm import checksum import requests GOOGLE_CLIENT_ID = "SECRET" GOOGLE_CLIENT_SECRET = 'SECRET' GOOGLE_DISCOVERY_URL = "https://accounts.google.com/.well-known/openid-configuration" os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' sq = URLSafeTimedSerializer(app.config['SECRET_KEY']) # @login_manager.unauthorized_handler # def unauthorized(): # return "You must be logged in to access this content.", 403 @app.route('/') @app.route('/home') def home(): return render_template('index.html') @app.route('/about') @login_required def about():
def get_serializer(name: str) -> TimedSerializer: config: Dict[str, Any] = current_app.config secret_key: bytes = config.get("SECRET_KEY") salt = config.get(f"SECURITY_{name.upper()}_SALT") return URLSafeTimedSerializer(secret_key=secret_key, salt=salt)
from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer #import pdb; pdb.set_trace() app = Flask(__name__) bcrypt = Bcrypt(app) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.config.update(MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME='******', MAIL_PASSWORD='******') mail = Mail(app) ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) import datetime as dt resetlink_context = [] #password reset expiry link for a user needs to expire after some time PASSWORD_RESET_EXPIRY_WINDOW = dt.timedelta( days=30) #setting this to 30 days as most apps do these days #pagination POSTS_PER_PAGE = 5 import models, logs from constnts import * import bokehbar, bokehradial @app.route('/', methods=['GET'])
from flask import Flask, request, url_for from flask_mail import Mail, Message from flask_restful import Resource from itsdangerous import URLSafeTimedSerializer, SignatureExpired from config import SECRET_KEY from Model import db, Etudiants, Enseignants mail = Mail() s = URLSafeTimedSerializer(SECRET_KEY) def send_email(email): token = s.dumps(email, salt='email-confirm') msg = Message('Confirm Email', sender='*****@*****.**', recipients=[email]) link = url_for('confirmation.confirmemailresource', token=token, _external=True) msg.body = 'Your link is {}'.format(link) mail.send(msg) class ConfirmEmailResource(Resource): def get(self): token=request.args['token'] try: email_sent = s.loads(token, salt='email-confirm', max_age=3600) except SignatureExpired: return {'error' : 'Link has expired!'} etudiant = Etudiants.query.filter_by(email=email_sent).first() enseignant = Enseignants.query.filter_by(email=email_sent).first()
import re # Khaya Configurations # app app = Flask(__name__) CORS(app) # cross-origin reference security implementation app.config['SECRET-KEY'] = urandom(36) app.config.from_pyfile('config.cfg') # mongodb khaya = MongoClient('localhost', 27017) db = khaya['khaya'] # keen analytics # paynow # bcrypt hashes salt = b'$2b$05$iIjhPDKsIoHJC7sDr4IVLO' # validators # token configuration s = URLSafeTimedSerializer('KHAYA_ZIMBABWE...') # global variables newpassword = None dbEmail = ''
def create_ws_token(public_key=None): from itsdangerous import URLSafeTimedSerializer s = URLSafeTimedSerializer(UI_API_KEY) return s.dumps({'public_key': public_key})
# -*- coding: utf-8 -*- import logging from flask import render_template from redash import settings from redash.tasks import send_mail from redash.utils import base_url from redash.models import User # noinspection PyUnresolvedReferences from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadSignature logger = logging.getLogger(__name__) serializer = URLSafeTimedSerializer(settings.COOKIE_SECRET) def invite_token(user): return serializer.dumps(str(user.id)) def invite_link_for_user(user): token = invite_token(user) invite_url = "{}/invite/{}".format(base_url(user.org), token) return invite_url def reset_link_for_user(user): token = invite_token(user) invite_url = "{}/reset/{}".format(base_url(user.org), token) return invite_url
def generate_confirmation_token(email): serializer = URLSafeTimedSerializer(SECRET_KEY) return serializer.dumps(email)
from flask import Flask, request, url_for #from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer import mysql.connector import smtplib import json import os.path app = Flask(__name__) with open(os.path.dirname(__file__) + '/../secretkey.json') as f: secretkey = json.load(f) s = URLSafeTimedSerializer(secretkey['key']) @app.route('/', methods=['GET', 'POST']) def index(): from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText with open(os.path.dirname(__file__) + '/../googlecredentials.json') as f: google = json.load(f) smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(google['username'], google['password']) if request.method == 'GET': return '<form action="/" method="POST"><input name="email"><input type="submit"></form>' email = request.form['email']
def create_app(**kwargs_config): """ Create the flask app :param kwargs_config: overwrite any base level config :return: flask.Flask instance """ app = factory.create_app( app_name=__name__.replace('.app', ''), **kwargs_config ) api = Api(app) api.unauthorized = lambda noop: noop #Overwrite WWW-Authenticate challenge on 401 csrf = CsrfProtect(app) mail = Mail(app) cors = CORS(app, origins=app.config.get('CORS_DOMAINS'), allow_headers=app.config.get('CORS_HEADERS'), methods=app.config.get('CORS_METHODS'), supports_credentials=True, ) app.json_encoder = JSONEncoder api.add_resource(Bootstrap, '/bootstrap') api.add_resource(StatusView, '/status') api.add_resource(OAuthProtectedView, '/protected') api.add_resource(CSRFView, '/csrf') api.add_resource(UserAuthView, '/user') api.add_resource(DeleteAccountView, '/user/delete') api.add_resource(UserRegistrationView, '/register') api.add_resource(LogoutView, '/logout') api.add_resource(PersonalTokenView, '/token') api.add_resource(UserInfoView, '/info/<string:account_data>') api.add_resource(ChangePasswordView, '/change-password') api.add_resource(ChangeEmailView, '/change-email') api.add_resource(VerifyEmailView, '/verify/<string:token>') api.add_resource(ForgotPasswordView, '/reset-password/<string:token>') app.ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) @app.login_manager.unauthorized_handler def unauthorized(): """ flask_login callback when @login_required is not met. This overrides the default behavior or re-directing to a login view """ abort(401) # Register custom error handlers if not app.config.get('DEBUG'): app.errorhandler(AdsWSError)(on_adsws_error) app.errorhandler(AdsWSFormError)(on_adsws_form_error) @csrf.error_handler def csrf_error(reason): app.logger.warning("CSRF Blocked: {reason}".format(reason=reason)) return jsonify(dict(error="Invalid CSRF token")), 400 return app
from flask import render_template, request, make_response,session,url_for,send_file import datetime from app.Controller import Controller from app import app import pdfkit from base64 import b64encode import base64 from flask_mail import Mail,Message import ldap from io import BytesIO import json import easygui from itsdangerous import URLSafeTimedSerializer,SignatureExpired s = URLSafeTimedSerializer('this is seceret') mail = Mail(app) re=1 from werkzeug.security import generate_password_hash, \ check_password_hash control=Controller() #index page function @app.route('/') @app.route('/index') def index(): return render_template('index.html') #login @app.route('/login',methods = ['POST', 'GET']) def loginuser(): if request.method == 'POST': category=request.form['cat'] username=request.form['username']
from datetime import datetime from flask import render_template, session, redirect, url_for, request from . import main import psycopg2 #from app.main.forms import NameForm from app import db from app.emails import send_email from app.models import User from itsdangerous import URLSafeTimedSerializer, SignatureExpired token_serializer = URLSafeTimedSerializer("the secret key is here") @main.route('/', methods=['GET', 'POST']) def index(): req_data = request.form if req_data.get("user_name") != None: if User.query.filter_by( user_name=req_data.get("user_name")).first() == None: new_user = User(user_name=req_data.get("user_name"), user_image=request.files.get("image").read(), user_email_adrs=req_data.get("email"), user_password=req_data.get("user_password")) db.session.add(new_user) db.session.commit() email = new_user.user_email_adrs email_token = token_serializer.dumps(email, salt='email-confirmation') salutation = "hi-NewUser{}".format(req_data.get("user_name")) text_message = 'click on the link for account confirm <a href="http://127.0.0.1:5000' + url_for( '.email_token_varify',
login_manager = LoginManager() ''' Note: With session_protection 'strong', this can fail in cases where this is used as a stand in authenticator/authorizer called as a sub request from a proxy This is because, the 'ip address' and 'user agent' are different. For more details see - https://flask-login.readthedocs.io/en/latest/#session-protection TODO: Update nginx configs to ensure client's ip and user agent are used in the sub request. ''' login_manager.session_protection = 'basic' REMEMBER_COOKIE_DURATION_SECONDS = int( os.getenv('REMEMBER_COOKIE_DURATION_SECONDS', 120)) SESSION_TOKEN_SECRET_KEY = os.environ[ 'SESSION_TOKEN_SECRET_KEY'] # secret key used for the session user cookie login_serializer = URLSafeTimedSerializer( SESSION_TOKEN_SECRET_KEY ) #Login_serializer used to encryt and decrypt the cookie token for the remember me option of flask-login class SessionUser(UserMixin): actas = '' def __init__(self, username, userpasshash): ''' Note that the userpasshash can be some kind of a token too.''' self.user_id = username self.userpasshash = userpasshash def get_auth_token(self): ''' Encode a secure token for cookie. This is used to remember the user. ''' return login_serializer.dumps(self.user_id, self.userpasshash)
def generate_confirmation_token(nickname): serializer = URLSafeTimedSerializer(application.config["SECRET_KEY"]) return serializer.dumps(nickname, salt=application.config["SECURITY_PASSWORD_SALT"])
def generate_token(self): data = {"email": self.email, "id": self.id} signer = URLSafeTimedSerializer(app.secret_key) return signer.dumps(data)
#-*- coding:utf-8 -*- from flask import Blueprint, current_app, render_template, request, jsonify, redirect, flash, url_for, g from flask_login import login_user, logout_user, login_required, current_user from flask_mail import Message from itsdangerous import URLSafeTimedSerializer from .datastorage.user_db import Users from flask_wtf import FlaskForm from wtforms import StringField, BooleanField, PasswordField from wtforms.validators import DataRequired, Email, EqualTo infos = {"desc": "user api", "version": "0.2dev"} serialiser = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) ACTIVATION_EMAIL_SUBJECT = "NOos-Citoyens // Valider votre inscription à NOos-Citoyens " ACTIVATION_EMAIL = """ Bienvenue sur NOos-Citoyens. Vous êtes désormais incrit sur la plateforme NOos-Citoyens. Pour commencer, veuillez activer votre compte en cliquant sur le lien ci-dessous ou collez le lien suivant dans la barre d'adresse de votre navigateur: %s Nous vous contacterons par la suite pour vous tenir informé des avancées de la plate-forme. Dans quelques jours vous recevrez un courriel pour vous prévenir de l'ouverture des votes.
def _token_serializer(): config = current_app.config secret_key = config.setdefault('SECRET_KEY') salt = config.setdefault('SECRET_KEY_SALT') serializer = URLSafeTimedSerializer(secret_key) return serializer, salt
def handle(self, *args, **options): """ python manage.py load_company_user deployment/deployment-v1-2018-03/mo_users.json :return: """ filename = options['filename'] try: with open(filename) as json_data: data = json.load(json_data) except Exception as e: print( '\n**************\nUnable to load json file. {0}. \n\n\nException message: ' .format(filename), e.message) else: companies_data = data.get('companies') if companies_data: for company_data in companies_data: if not 'uuid' in company_data: continue try: # expected value: email, company_name, member_organization, uuid, company_prefix email = company_data.get('email') company_name = company_data.get('company_name') try: member_organisation = MemberOrganisation.objects.get( slug=company_data.get('role')) except MemberOrganisation.DoesNotExist: member_organisation = None # get company company_organisation, company_organisation_created = CompanyOrganisation.objects.get_or_create( uuid=company_data.get('uuid'), defaults={ 'member_organisation': member_organisation, 'name': company_data.get('name') }) #print("Company Created:- " if company_organisation_created else "Company Updated:- ", # u' '.join( # [company_organisation.uuid]).encode('utf-8').strip()) # update company name if any if company_name: company_organisation.company = company_name company_organisation.save() auth_user, auth_user_created = users_service.get_or_create( email=email, defaults={ 'username': email, 'member_organisation': member_organisation, 'company_organisation': company_organisation }) auth_user.save() # print('Create New User:- ' if auth_user_created else 'Updated User:- ', auth_user.email) company_organisation = users_service.get_company_organisation( auth_user) except Exception as e: print(company_data) print(str(e)) continue log_message = 'logging in: ' + str( auth_user.email) + '::' + str( company_organisation.company) log_extra = { 'user': auth_user.email, 'company': company_organisation.company } logging.getLogger().info(log_message, extra=log_extra) logging.getLogger('audit').info(log_message, extra=log_extra) # if user's organisation has prefix override, use it # if not use prefixes provided by the form if company_organisation.prefix_override: form_prefix = company_organisation.prefix_override form_prefixes = form_prefix.split(',') else: form_prefixes = company_data.get('prefixes') prefixes = prefix_service.find(user=auth_user).all() prefixes_list = [p.prefix for p in prefixes] # set gln to be first prefix if len(prefixes_list) > 0: first_prefix = prefixes_list[0] derived_gln = normalize("EAN13", first_prefix) company_organisation.gln = derived_gln company_organisation.save() for prfx in form_prefixes: # if not re.match(settings.GS1_PREFIX_START_REGEX, prfx[:3]) or len(prfx) < 6: # if prfx.find('20') == 0: # we will not complain about variable weight # continue # else: # return jsonify(success=False, message='Invalid prefix %s' % prfx) if prfx not in prefixes_list: try: prefix = prefix_service.create(user=auth_user, prefix=prfx) except IntegrityError: print( '\n\n*** ERROR: Prefix {0} has been allocated for another user\n\n' .format(prfx)) continue try: prefix.make_starting_from() except: prefix.starting_from = None prefix_service.save(prefix) else: i = prefixes_list.index(prfx) if prefixes[i].is_suspended: prefixes[i].is_suspended = False prefix_service.save(prefixes[i]) for prfx in prefixes_list: if prfx not in form_prefixes: prefix = prefix_service.find(user=auth_user, prefix=prfx).first() prefix.is_suspended = True prefix_service.save(prefix) # Check active prefix and set accordingly user_active_prefix = auth_user.profile.product_active_prefix if not user_active_prefix: prefix = prefix_service.find( user=auth_user, is_suspended=False).order_by('prefix').first() if prefix: prefix_service.make_active(user=auth_user, prefix=prefix.prefix) prefix_service.save(prefix) else: print('\n\nERROR: No working prefix found\n\n') continue serializer = URLSafeTimedSerializer(settings.SECRET_KEY) token = serializer.dumps( [auth_user.email, company_organisation.uuid]) logging.getLogger().debug('Created token: %s' % token)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from unicodedata import category from itsdangerous import URLSafeTimedSerializer, URLSafeSerializer from app import app auth_token_serializer = URLSafeTimedSerializer(app.secret_key) auth_token_serializer_perm = URLSafeSerializer(app.secret_key) REJECT_CHARACTERS = ('\u2028', '\u2029') def has_control_characters(s): """ Return True if the given string contains any unprintable/control characters """ cat = category return any( cat(letter).startswith('C') # Control character or letter in REJECT_CHARACTERS for letter in s) def allow_password(password): """ Current password strength rules are:: 1) unicode allowed 2) only "printable" characters (e.g. excluding control characters) 3) at least 8 characters 4) fewer than 1024 characters (arbitrarily large)
class YouckanAuthPlugin(object): implements(IIdentifier, IChallenger, IAuthenticator, IChallengeDecider) def __init__(self, secret=None, login_url=None, session_cookie_name='sessionid', auth_cookie_name='youckan.auth', next_url_name='next', https=False): if not secret or not login_url: raise ValueError('secret and login_url parameters are required') self.session_cookie_name = session_cookie_name self.auth_cookie_name = auth_cookie_name self.secret = secret self.login_url = login_url self.next_url_name = next_url_name self.use_https = https is True or https == 'true' self.marker_cookie_name = '{0}.logged'.format(auth_cookie_name) self.signer = URLSafeTimedSerializer(secret, signer_kwargs={'sep': ':'}) log.debug('YouckanAuth https: %s', self.use_https) log.debug('YouckanAuth session cookie: %s', self.session_cookie_name) log.debug('YouckanAuth auth cookie: %s', self.auth_cookie_name) log.debug('YouckanAuth marker cookie: %s', self.marker_cookie_name) def __call__(self, environ, status, headers): '''Challenge if marker present and not in https''' request = Request(environ) if self.needs_redirect(request): return True return default_challenge_decider(environ, status, headers) def challenge(self, environ, status, app_headers=(), forget_headers=()): '''Redirect to YouCKAN login page''' request = Request(environ) if self.needs_redirect(request): response = Response() response.status = 302 response.location = request.url.replace('http://', 'https://') return response next_url = quote(request.url) if self.use_https and next_url.startswith('http://'): next_url = next_url.replace('http://, https://') auth_url = '{0}?{1}={2}'.format(self.login_url, self.next_url_name, next_url) response = Response() response.status = 302 response.location = auth_url return response def identify(self, environ): '''Identity user from its Django session and YouCKAN auth cookies''' request = Request(environ) if not self.session_cookie_name in request.cookies or not self.auth_cookie_name in request.cookies: return None session_id = request.cookies[self.session_cookie_name] cookie = request.cookies[self.auth_cookie_name] try: username = self.signer.loads(cookie, salt=session_id) log.debug('Signature ID mismatch: %s', username) except BadSignature: return None return {'username': username} def authenticate(self, environ, identity): '''Fetch the user given its username in identity''' if 'username' in identity: user = User.by_name(identity['username']) if user is None: return None else: identity.update({'repoze.who.userid': user.name}) return user.name return None def remember(self, environ, identity): '''Remember is YouCKAN SSO responsibility''' pass def forget(self, request, environ): '''Forget is YouCKAN SSO responsibility''' pass def needs_redirect(self, request): return self.use_https and self.marker_cookie_name in request.cookies and not request.scheme == 'https'
def generate_confirmation_token(user): serializer = URLSafeTimedSerializer('my_precious') return serializer.dumps(user, salt='my_precious_two')
from flask import Flask, url_for, request, render_template from itsdangerous import URLSafeTimedSerializer, SignatureExpired import smtplib #import uuid from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText app = Flask(__name__) app.config.from_pyfile('config.cfg') s = URLSafeTimedSerializer('') @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': me = "*****@*****.**" you = "*****@*****.**" msg = MIMEMultipart() msg['Subject'] = "Alert from credit card" msg['From'] = me msg['To'] = you access = "Vijayawada" #access = input("Enter Location:") #token = uuid.uuid4().hex token = s.dumps('heelo', salt='email-confirm') #token1 = s.dumps('heelo',salt='email-reject') #print(token) link = url_for('confirm_email', token=token, _external=True) link1 = url_for('reject_email', token=token, _external=True)