def execute(self, payload): # 1. Extract user id from payload key = self._settings['cookie_secret'] s = URLSafeSerializer(key) uid = None try: uid = ObjectId(s.loads(payload)) except BadSignature: raise tornado.web.HTTPError(400) db = self._settings['db'] # 2. Determine if user exists and is in unconfirmed state user = yield db.users.find_one({ '_id': uid, 'status': UserStatus.unconfirmed }) if not user: raise tornado.web.HTTPError(410) # 3. Set user status to active yield db.users.update({ '_id': uid}, { '$set': { 'status': UserStatus.active } }) # 4. Determine lifespan of new session lifespan = self._settings['session_lifespan'] # 5. Insert new session now = datetime.utcnow() sessionId = yield db.sessions.insert({ 'userId': uid, 'created': now, 'persistentCookie': True, 'expires': now + timedelta(days=lifespan) }) return EmailVerificationResult(user, sessionId, lifespan)
def confirm(payload=None): ''' This is where user creation lives, for now... ''' # TODO: Get this out of here! form = ConfirmForm() if request.method == 'GET': s = URLSafeSerializer(app.config['SECRET_KEY']) try: user_id = s.loads(payload) except BadSignature: abort(404) user = User.objects.get(id=user_id) if not user.registered: user.activate() flash("Your email has been verified.") AdminAlertEmail(subject="Confirmed user: %s" % user.email, body="User %s has confirmed their email address." % user.email).send() session["user_id"] = user_id # TODO: Why is this here? return render_template("confirm.html", form=form) else: return redirect(url_for("root.index")) if form.validate_on_submit(): user = User.objects.get(id=session["user_id"]) user.password = generate_password_hash(form.password.data) user.registered = True RegistrationEmail(user.email).send() AdminAlertEmail(subject="Registered user: %s" % user.email, body="User %s has finished registration." % user.email).send() user.save() login_user(user) return redirect(url_for("root.index")) return render_template("confirm.html", form=form)
def login_as_user(id): s = URLSafeSerializer(app.config['SECRET_KEY']) payload = {"id": id, "stamp": time.time()} token = s.dumps(payload) pieces = [app.config["LIME_URL"], 'trowel', token] url = '/'.join(piece.strip('/') for piece in pieces) return redirect(url)
def send_confirmmail_to_unregistered_users(items): """Send a confirmation email for external signups(email only) Args: item: The item, which was just inserted into the database """ for item in items: if 'user' not in item: event = current_app.data.find_one( 'events', None, **{current_app.config['ID_FIELD']: item['event']}) title = event.get('title_en') or event.get('title_de') s = URLSafeSerializer(get_token_secret()) token = s.dumps(str(item['_id'])) if current_app.config.get('SERVER_NAME') is None: current_app.logger.warning("SERVER_NAME is not set. E-Mail " "links will not work!") confirm_link = url_for('emails.on_confirm_email', token=token, _external=True) mail([item['email']], 'Registration for %s' % title, current_app.config['CONFIRM_EMAIL_TEXT'].format( title=title, link=confirm_link))
def resetpassword(): form = PasswordResetForm() if form.validate_on_submit(): if form.username.data: user = Users.query.filter_by(username=form.username.data).first() elif form.email.data: user = Users.query.filter_by(email=form.email.data).first() else: flash("Username or password doesn't exists") if user: if user.email: s = URLSafeSerializer('serliaizer_code') key = s.dumps([user.username, user.email]) msg = Message("Password reset", sender="your_id@your_host.com", recipients=[user.email]) msg.html = "<b>Click on this link to reset your password.</b> \ #<a href='http://127.0.0.1:5000/passwordreset/ \ " + key + "'>http://127.0.0.1:5000/passwordreset/ \ " + key + "</a>" send_async_email(msg) flash('Email sent to: ' + user.email) return redirect(url_for('resetpassword')) else: flash('No such user') return redirect(url_for('resetpassword')) flash(u'Enter your email or username') return render_template('reset_password.html', form=form)
def register(): form = RegisterUserForm() if form.validate_on_submit(): user = User.create( username=form.data['username'], email=form.data['email'], password=form.data['password'], remote_addr=request.remote_addr, ) s = URLSafeSerializer(current_app.secret_key) token = s.dumps(user.id) send_registration_email.delay(user, token) flash( gettext( 'Sent verification email to {email}'.format( email=user.email ) ), 'success' ) return redirect(url_for('index')) return render_template('register.html', form=form)
def send_invite(user): s = URLSafeSerializer(app.config['SECRET_KEY']) payload = s.dumps(str(user.id)) link_href = url_for("root.confirm", payload=payload, _external=True) InviteEmail(user.email, link_href).send() flash("Successfully sent invitation.")
def resetpassword(): form = PasswordResetForm() if form.validate_on_submit(): if form.username.data: user = Users.query.filter_by(username=form.username.data).first() elif form.email.data: user = Users.query.filter_by(email=form.email.data).first() else: flash("Username or password not in system") if user: if user.email: s = URLSafeSerializer('12fe454t') key = s.dumps([user.username, user.email]) #s.loads('WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo') msg = Message("Password reset", sender="*****@*****.**", recipients=[user.email]) msg.html = "<b>testing</b> \ #<a href='http://127.0.0.1:5000/passwordreset/" + key + "'>http://127.0.0.1:5000/passwordreset/" + key + "</a>" print msg.html mail.send(msg) flash('Email sent to: ' + user.email) return redirect(url_for('resetpassword')) else: flash('No such user') return redirect(url_for('resetpassword')) else: flash('No such user') return redirect(url_for('resetpassword')) return render_template('reset_password.html', form=form)
def create_reset_link(user): l = "http://localhost:5001/reset/" s = URLSafeSerializer("hacker-bees") token = s.dumps(user.id) l += token user.reset_time = datetime.today() return l
def get_context_data(self, **kwargs): context = super(AlbumView, self).get_context_data(**kwargs) serializer = URLSafeSerializer(settings.SECRET_KEY) token = serializer.dumps({'album_id': self.object.id}) context['token'] = token context['album'] = self.object return context
def post(self, request, id, token): a = get_object_or_404(Album, pk=id) s = URLSafeSerializer(settings.SECRET_KEY) d = s.loads(token) if str(d['album_id']) != id: return HttpResponse("bad token") if request.FILES.get('image', None): original_filename = request.FILES['image'].name extension = os.path.splitext(original_filename)[1].lower() if extension == ".jpeg": extension = ".jpg" if extension not in [".jpg", ".png", ".gif"]: return HttpResponse("unsupported image format") title = original_filename rhash = settings.UPLOADER.upload(request.FILES['image']) p = Photo.objects.create( title=title, reticulum_key=rhash, extension=extension, description='') AlbumPhoto.objects.create( album=a, photo=p) return HttpResponse("ok") else: return HttpResponse("no image")
def save(self, *args, **kwargs): from itsdangerous import URLSafeSerializer s = URLSafeSerializer(SECRET_KEY) x = datetime.now() self.ss_id = s.dumps(str(x)) if self.pk is None: super(Question, self).save(self, *args, **kwargs)
def generate_auth_token(self): """generate a token""" s = Serializer( current_app.config['SECRET_KEY'] # expiration ) return s.dumps({'id': self.id})
def new_task(app_id): # Check if the request has an arg: try: app = db.session.query(model.App).get(app_id) if app is None: raise NotFound if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 user_id = None if current_user.is_anonymous() else current_user.id user_ip = request.remote_addr if current_user.is_anonymous() else None task = sched.new_task(app_id, user_id, user_ip, offset) # If there is a task for the user, return it if task: s = URLSafeSerializer(current_app.config.get('SECRET_KEY')) r = make_response(json.dumps(task.dictize())) r.mimetype = "application/json" cookie_id = 'task_run_for_task_id_%s' % task.id r.set_cookie(cookie_id, s.dumps(task.dictize())) return r else: return Response(json.dumps({}), mimetype="application/json") except Exception as e: return error.format_exception(e, target='app', action='GET')
def resend_activation_email(email_to_activate): """ Function to resend the activation email """ #check local database loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username==email_to_activate) #@UndefinedVariable #get the user object user_rec = loc_db_user.first() if user_rec: #create an itsdangerous object to sign the verification email itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET) #send the confirmation email act_code = itsd.dumps(email_to_activate) message_html = """<h3>Dear %(name)s %(lastname)s, thank you for registering to the NASA ADS</h3> <p>Your activation code is <strong>%(code)s</strong></p> <p>To activate your account, please click <a href="%(act_url)s">here</a></p> <p>If the link doesn't work, please copy the following URL and paste it in your browser:<br/>%(act_url)s</p> <p>Please do not replay to this email: to contact us please use our <a href="%(feedb_url)s">feedback form</a></p> <p>Regards,<br/>The ADS team</p> """ % {'name':user_rec.firstname, 'lastname':user_rec.lastname, 'code':act_code, 'act_url': '%s%s?id=%s' % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('user.activate'), act_code), 'feedb_url' : '%s%s'%(config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('feedback.feedback')) } try: send_email_to_user(u"NASA ADS Account confirmation required", message_html, [email_to_activate]) except: app.logger.error('Failed to re-send confirmation email for user creation') return False, 'There are some technical problems: please try later.', 'error' return True, 'A new email with the activation code has been sent to your email address.', 'success' else: app.logger.error('Tried to re-send confirmation email for user creation for user not yet created or not stored in the DB. Email used %s' % email_to_activate) return False, 'The user with the given email does not exist', 'error'
def notify_signup_accepted(event, signup): """Send an email to a user that his signup was accepted""" id_field = current_app.config['ID_FIELD'] if signup.get('user'): lookup = {id_field: signup['user']} user = current_app.data.find_one('users', None, **lookup) name = user['firstname'] email = user['email'] else: name = 'Guest of AMIV' email = signup['email'] s = URLSafeSerializer(get_token_secret()) token = s.dumps(str(signup[id_field])) if current_app.config.get('SERVER_NAME') is None: current_app.logger.warning("SERVER_NAME is not set. E-Mail links " "will not work!") deletion_link = url_for('emails.on_delete_signup', token=token, _external=True) mail([email], 'Eventsignup accepted', current_app.config['ACCEPT_EMAIL_TEXT'].format( name=name, title=event.get('title_en') or event.get('title_de'), link=deletion_link, deadline=event['time_register_end'].strftime('%H.%M %d.%m.%Y')))
def generate_jwt(claims, lifetime=None, expires=None, not_before=None): """ Generate a JSON Web Token. - **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC. - **iat** (*IntDate*) -- The UTC date and time at which the token was generated. - **nbf** (*IntDate*) -- The UTC valid-from date and time of the token. - **jti** (*str*) -- A unique identifier for the token. """ claims = dict(claims) now = datetime.utcnow() claims['iat'] = timegm(now.utctimetuple()) claims['nbf'] = timegm((not_before or now).utctimetuple()) claims['jti'] = urlsafe_b64encode(urandom(128)) if lifetime: claims['exp'] = timegm((now + lifetime).utctimetuple()) elif expires: claims['exp'] = timegm(expires.utctimetuple()) signer = URLSafeSerializer(SECRET_KEY) return signer.dumps(claims)
def toggle_choice(request): campaign = get_active_campaign_or_404() volunteer = get_object_or_404(Volunteer, pk=request.POST.get('volunteer_id')) with transaction.atomic(): cursor = connection.cursor() cursor.execute('LOCK TABLE %s' % VolunteerCampaign._meta.db_table) created = False try: obj = VolunteerCampaign.objects.get( Q(accepted__isnull=True) | Q(accepted=True), campaign=campaign, volunteer=volunteer, ) except VolunteerCampaign.DoesNotExist: obj, created = VolunteerCampaign.objects.get_or_create( campaign=campaign, volunteer=volunteer, organisation=request.user.organisation, ) if created: serializer = URLSafeSerializer(settings.SECRET_KEY) confirm_invite_url = reverse('confirm_invite', args=[serializer.dumps(obj.pk)]) get_adapter().send_mail('emails/volunteer_invitation', volunteer.user.email, { 'organisation': request.user.organisation, 'confirm_invite_url': request.build_absolute_uri(confirm_invite_url), }) state, label = get_volunteer_status(obj, request.user.organisation) return JsonResponse({ 'state': state, 'label': label, })
def confirm_invite(request, volunteer_campaign_id): serializer = URLSafeSerializer(settings.SECRET_KEY) try: volunteer_campaign_id = serializer.loads(volunteer_campaign_id) except BadSignature as e: raise Http404(str(e)) volunteer_campaign = get_object_or_404(VolunteerCampaign, pk=volunteer_campaign_id) if request.user.is_authenticated() and volunteer_campaign.volunteer != request.user.volunteer: raise Http404('Invitation was sent to other volunteer.') response = log_user_in(request, volunteer_campaign.volunteer.user) if response is not None: return response if request.method == 'POST': if request.POST.get('action') == 'accept': volunteer_campaign.accepted = True get_adapter().send_mail('emails/volunteer_accept', volunteer_campaign.organisation.user.email, { 'volunteer': volunteer_campaign.volunteer, }) else: volunteer_campaign.accepted = False volunteer_campaign.save() return redirect('volunteer_profile') return render(request, 'volunteers/confirm.html', { 'organisation': volunteer_campaign.organisation, })
def reset_request(self, **kw): user = model.provider.query(app_model.User, filters=dict(email_address=kw['email_address']))[1][0] password_frag = user.password[0:4] serializer = URLSafeSerializer(tg.config['beaker.session.secret']) serialized_data = serializer.dumps(dict(request_date=datetime.utcnow().strftime('%m/%d/%Y %H:%M'), email_address=kw['email_address'], password_frag=password_frag)) password_reset_link = tg.url(self.mount_point + "/change_password/", params=dict(data=serialized_data), qualified=True) reset_password_config = tg.config.get('_pluggable_resetpassword_config') mail_body = reset_password_config.get('mail_body', _(''' We've received a request to reset the password for this account. Please click this link to reset your password: %(password_reset_link)s If you no longer wish to make the above change, or if you did not initiate this request, please disregard and/or delete this e-mail. ''')) email_data = {'sender': tg.config['resetpassword.email_sender'], 'subject': reset_password_config.get('mail_subject', _('Password reset request')), 'body': mail_body, 'rich': reset_password_config.get('mail_rich', '')} tg.hooks.notify('resetpassword.on_request', args=(user, email_data, password_reset_link)) email_data['body'] = email_data['body'] % dict(password_reset_link=password_reset_link) email_data['rich'] = email_data['rich'] % dict(password_reset_link=password_reset_link) send_email(user.email_address, **email_data) flash(_('Password reset request sent')) return plug_redirect('resetpassword', '/')
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 _update_object(self, obj): """Validate the task_run object and update it with user id or ip.""" s = URLSafeSerializer(current_app.config.get('SECRET_KEY')) # Get the cookie with the task signed for the current task_run cookie_id = 'task_run_for_task_id_%s' % obj.task_id task_cookie = request.cookies.get(cookie_id) if task_cookie is None: raise Unauthorized("Missing task cookie for posting" " a valid task_run") # Load the real task from the DB task_cookie = s.loads(task_cookie) task = db.session.query(model.Task).get(task_cookie['id']) if ((task is None) or (task.id != obj.task_id)): # pragma: no cover raise Forbidden('Invalid task_id') if (task.app_id != obj.app_id): raise Forbidden('Invalid app_id') if not current_user.is_anonymous(): obj.user = current_user else: obj.user_ip = request.remote_addr # Check if this task_run has already been posted task_run = db.session.query(model.TaskRun)\ .filter_by(app_id=obj.app_id)\ .filter_by(task_id=obj.task_id)\ .filter_by(user=obj.user)\ .filter_by(user_ip=obj.user_ip)\ .first() if task_run is not None: raise Forbidden('You have already posted this task_run')
def encrypt(self, payload, timestamp=False): result = '' s1 = URLSafeSerializer(self.secret_key) result = s1.dumps(payload) if(timestamp == True): s2 = TimestampSigner(self.secret_key) result = s2.sign(result) return result
def confirmation(token): serializer = URLSafeSerializer(app.config['SECRET_KEY']) email = serializer.loads(token) registration = Registration.query.filter(Registration.email == email).one() registration.confirmed_at = datetime.utcnow() db.session.commit() flash(_("Your registration has been confirmed."), 'success') return redirect("/")
def verify_confirm_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False id = data.get('confirm') # id int return id
def decode(something): """Decode something with SECRET_KEY.""" secret_key = current_app.config.get('SECRET_KEY') s = URLSafeSerializer(secret_key) try: return s.loads(something) except BadSignature: return None
def decode_token_or_400(auth_token): """ Decode the given auth_token and return the data dict therein, or fail with a HTTP 400 error. """ serializer = URLSafeSerializer(current_app.config['SECRET_KEY']) try: return serializer.loads(auth_token) except BadData as ex: generic_error_handler(ex) abort(400)
def save(self, *args, **kwargs): from itsdangerous import URLSafeSerializer s = URLSafeSerializer(SECRET_KEY) x = Test.objects.all().count() print(x) print(type(x)) self.s_id = s.dumps(x + 1) if self.pk is None: super(Test, self).save(self, *args, **kwargs)
def send_activation_email(self): s = URLSafeSerializer(app.config['SECRET_KEY']) payload = s.dumps(self.username) url = url_for('activate', payload=payload, _external=True) subject = "Activate your account" text = render_template("activate.txt", url=url) html = render_template("activate.html", url=url) email_helper.send_email(self.get_email(), subject, text, html)
def verify_auth_token(token): """verify the user with token""" s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None # get id return User.query.get_or_404(data['id'])
self.commit() return cursor class RetryDB(RetryOperationalError, MySQLDatabase): """封装数据库重试类""" pass CFG = config[os.getenv('FLASK_CONFIG') or 'default'] DB = RetryDB(host=CFG.DB_HOST, user=CFG.DB_USER, passwd=CFG.DB_PASSWD, database=CFG.DB_DATABASE) MIGRATOR = MySQLMigrator(DB) SERIALIZER = URLSafeSerializer(CFG.SECRET_KEY) def session_token_generate(): """随机session token生成""" return SERIALIZER.dumps(str(uuid.uuid1())) class BaseModel(Model): """基类初始化""" class Meta: """数据库初始化""" database = DB class User(UserMixin, BaseModel):
return redirect(url_for('changelist.report_changelist')) @bp.route('/silence/<string:staff>') def silence_staff_changelist(staff): """Ignore non-reported changes of a specific staff in next report.""" # remove changelist report for that staff remove_staff_changes(staff) # redirect to list of changes return redirect(url_for('changelist.report_changelist')) # utils # setup serializer that can decrypt staff's tokens secret = open('config/'+planning.config.name+'/secret.yaml') serializer = URLSafeSerializer(secret.read()) # holds current list of changes current_changes = [] class Change: def __init__(self, activity, kind): self.activity = activity self.kind = kind self.date_changed = datetime.now() def add_change(change): current_changes.append(change) def get_changes_per_staff(): changes_per_staff = []
def url_safe_serializer(): return URLSafeSerializer(current_app.secret_key, salt=cookie_session[EQ_SESSION_ID])
def generate_auth_token(self): """generate a token""" s = Serializer(current_app.config['SECRET_KEY'] # expiration ) return s.dumps({'id': self.id})
def get_serializer(secret_key=None): if secret_key is None: secret_key = app.secret_key return URLSafeSerializer(secret_key)
def generate_confirmation_token(user): serializer = URLSafeSerializer(app.config['SECRET_KEY']) return serializer.dumps(user.email, salt=app.config['SECURITY_PASSWORD_SALT'])
import os from enum import Enum from flask import url_for from flask_login import current_user from itsdangerous import URLSafeSerializer json_url = URLSafeSerializer(os.environ.get("SECRET_KEY", "secret_key")) class AbstractEnum(Enum): @classmethod def from_string(cls, value): return cls.__members__[value] class CognitiveEnum(AbstractEnum): Knowledge = 1 Comprehension = 2 Application = 3 class DifficultyEnum(AbstractEnum): Easy = 1 Medium = 2 Hard = 3 class QuestionTypeEnum(AbstractEnum): sub = 1 mcq = 2
def generate_auth_token(self): s = URLSafeSerializer(current_app.config['SECRET_KEY']) return s.dumps({'id': self.id})
def get_activation_link(user_id): s = URLSafeSerializer(current_app.secret_key) payload = s.dumps(user_id) return url_for('activate_user', payload=payload, _external=True)
#Flask login setup login_manager = LoginManager() login_manager.init_app(app) login_manager.user_loader(User) #Sendgrid setup sg = sendgrid.SendGridAPIClient(apikey=os.environ.get("SENDGRID_API_KEY")) from_email = Email("*****@*****.**") from_email.name = "DanielBCF" #Setup config parser object config = ConfigParser() #Setup Serializer object s = URLSafeSerializer(app.config["SECRET_KEY"]) from app.replenishjob import rep @app.route("/order", methods=["GET", "POST"]) def order(): rep() return "a" #Setup login_required decorator def login_required(f): @wraps(f) def wrap(*args, **kwargs): if not current_user.is_authenticated: flash("Please login to view this page!", "danger")
def read_token(token, salt, expiration=86400): serializer = URLSafeSerializer(app.config["SECRET_KEY"]) obj = serializer.loads(token, salt=salt) return obj
# mycursor = db.cursor() app = Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.googlemail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True mail = Mail(app) app.config.from_pyfile('config.cfg') app.secret_key = "fsggrsgsrgrg" s = URLSafeSerializer('secretthistime!') @app.route('/') def house(): return render_template('index.html') @app.route('/home') def home(): return render_template('index.html') @app.route('/about') def about(): return render_template('about.html')
def generete_token(email): serializer = URLSafeSerializer(app.secret_key) return serializer.dumps(email, salt=app.secret_key)
def unsign(self, signed, namespace="default"): return URLSafeSerializer(self._secret, namespace).loads(signed)
# -*- 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)
def generate_confirmation_token(email): serializer = URLSafeSerializer(secret_key, salt=security_password_salt) return serializer.dumps(email)
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user from itsdangerous import URLSafeSerializer app = Flask(__name__) ############ Mongo DB connection ################ app.config['SECRET_KEY'] = 'Hemmelig!' ## is required app.config["MONGO_DBNAME"] = "rat" ## DB name app.config[ "MONGO_URI"] = "mongodb://localhost:27017/rat" ## local DB, But can be used MLab(free 500MB) https://mlab.com/ mongo = PyMongo(app) login_manager = LoginManager(app) login_manager.login_view = 'login' serializer = URLSafeSerializer(app.secret_key) class Teacher(UserMixin): def __init__(self, teacher_data): self.teacher_data = teacher_data def get_id(self): return self.teacher_data['session_token'] @login_manager.user_loader def load_user(session_token): teachers = mongo.db.teachers teacher_data = teachers.find_one({'session_token': session_token}) if teacher_data:
def generate_invoice_token(invoiceID, userID): package = [invoiceID, userID] serializer = URLSafeSerializer(app.config['SECRET_KEY']) return serializer.dumps(package, salt=app.config['SECURITY_PASSWORD_SALT'])
def encode(something): """Encode something with SECRET_KEY.""" secret_key = current_app.config.get('SECRET_KEY') s = URLSafeSerializer(secret_key) return s.dumps(something)
from util.email_sender import send_email import util.string_validator as string_validator from database.security import address_failed_login, clear_failed_login from urllib.parse import urlparse from config import Config conf = Config() app = Flask(__name__) app.secret_key = conf.secret timed_serializer = URLSafeTimedSerializer(conf.secret) serializer = URLSafeSerializer(conf.secret) setup_database() @app.before_request def before_request(): ref_origin_check = True for header in request.headers: if header[0].lower() == "referer" or header[0].lower() == "origin": referer = urlparse(header[1]) config_domain = urlparse(conf.domain) if referer.netloc.lower() != config_domain.netloc.lower(): ref_origin_check = False print(header[0] + " is wrong!") if not ref_origin_check:
from parameterized import parameterized from airflow import DAG from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP from airflow.configuration import conf from airflow.models import DagBag, DagModel from airflow.models.serialized_dag import SerializedDagModel from airflow.operators.dummy_operator import DummyOperator from airflow.security import permissions from airflow.utils.session import provide_session from airflow.www import app from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user from tests.test_utils.config import conf_vars from tests.test_utils.db import clear_db_dags, clear_db_runs, clear_db_serialized_dags SERIALIZER = URLSafeSerializer(conf.get('webserver', 'secret_key')) FILE_TOKEN = SERIALIZER.dumps(__file__) class TestDagEndpoint(unittest.TestCase): dag_id = "test_dag" task_id = "op1" dag2_id = "test_dag2" @staticmethod def clean_db(): clear_db_runs() clear_db_dags() clear_db_serialized_dags() @classmethod
def generate_confirmation_token(email, secret_key): serializer = URLSafeSerializer(secret_key) return serializer.dumps(email)
import stripe from flask_sqlalchemy import SQLAlchemy from flask_cdn import CDN from flask_redis import Redis from celery import Celery from itsdangerous import URLSafeSerializer from . import settings DB = SQLAlchemy() redis_store = Redis() stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = "2018-09-24" cdn = CDN() celery = Celery(__name__, broker=settings.CELERY_BROKER_URL) spam_serializer = URLSafeSerializer(settings.SPAM_SECRET)
def sign(self, value, namespace="default"): return URLSafeSerializer(self._secret, namespace).dumps(value)
def generate_billdebt_token(billDebtID): serializer = URLSafeSerializer(app.config['SECRET_KEY']) return serializer.dumps(billDebtID, salt=app.config['SECURITY_BILLDEBT_SALT'])
def decrypt(token, key): salt = _salt(key) s = URLSafeSerializer(key) return s.loads(token, salt=salt)
import os from itsdangerous import URLSafeSerializer, BadData, BadSignature from flask import Flask from project.config import Config serializer = URLSafeSerializer(f"{os.getenv('SECRET_KEY')}") def generate_outcome_token(parent_email, baby_id): """Generate token using serialized dict of parent's email address and baby ID""" return serializer.dumps({ 'parent_email': parent_email, 'baby_id': baby_id, }) def deserialize_outcome_token(token): """Deserialize token and return data""" try: data = serializer.loads(token) return data except (BadData, BadSignature): return False
def encrypt(string, key): salt = _salt(key) s = URLSafeSerializer(key) return s.dumps(string, salt)
def generate_token(obj, salt): serializer = URLSafeSerializer(app.config["SECRET_KEY"]) return serializer.dumps(obj, salt=salt)
def get_token(obj: DagModel): """Return file token""" serializer = URLSafeSerializer(conf.get('webserver', 'secret_key')) return serializer.dumps(obj.fileloc)