def __init__(self, secret_key): """ Initializes the token store :param str secret_key: The signing key for the serializer """ self._serializer = itsdangerous.URLSafeSerializer(secret_key)
def unsign_data(token, **kw): """ To unsign url safe data. If expires_in is provided it will Time the signature :param token: :param secret_key: :param salt: (string) a namespace key :param kw: :return: """ if len(token.split(".")) == 3: s = URLSafeTimedSerializer2(secret_key=__CRYPT.get("secret_key"), salt=__CRYPT.get("salt"), **kw) value, timestamp = s.loads(token, max_age=None, return_timestamp=True) now = datetime.datetime.utcnow() if timestamp > now: return value else: raise itsdangerous.SignatureExpired('Signature age %s < %s ' % (timestamp, now), payload=value, date_signed=timestamp) else: s = itsdangerous.URLSafeSerializer( secret_key=__CRYPT.get("secret_key"), salt=__CRYPT.get("salt"), **kw) return s.loads(token)
def create(request, *args, **kwargs): serializer = itsdangerous.TimedSerializer( settings.ITSDANGEROUS_KEY, serializer=itsdangerous.URLSafeSerializer(settings.ITSDANGEROUS_KEY), ) try: email = serializer.loads(kwargs["token"], max_age=settings.ITSDANGEROUS_EXPIRE_PERIOD, salt="signup") Registration.objects.filter(email=email).update(pending=False) except itsdangerous.SignatureExpired: msg = "Link has expired. Please contact department administrator for new link" return http.HttpResponse(msg) except itsdangerous.BadSignature: return http.HttpResponseNotFound("Page Not Found") form = SignupForm(prefix="user_form") if request.method == "POST": form = SignupForm(request.POST, prefix="user_form") if form.is_valid(): form.save() messages.success( request, "Account created successfully. Please login to proceed", extra_tags="alert", ) return http.HttpResponseRedirect(reverse("login")) context = {"user_form": form, "title": "Registration"} return render(request, "staff/signup.html", context)
def sign_auth_path(next_path): """returns a URL-safe signed next_path""" # next_path must start with a / if not next_path.startswith('/'): abort(503) # sign the next_path notary = itsdangerous.URLSafeSerializer(app.secret_key) next_path_signed = notary.dumps(next_path) return url_for('authenticate', next=next_path_signed)
def encrypt_resource(string): user_id = current_user.get_id() key = user_id or current_app.config['RESOURCE_KEY'] access = 'user' if user_id else 'public' return url_for("download_resource", encrypted=itsdangerous.URLSafeSerializer( key, salt=access).dumps(string), access=access)
def get_email_addressed(address_encoded): signer = itsdangerous.URLSafeSerializer(flask.current_app.secret_key) email_address = signer.loads(address_encoded) print('TEST', email_address, 'from', address_encoded) return flask.render_template('email-registered.html', email_address=email_address) with psycopg2.connect(os.environ['DATABASE_URL']) as conn: with conn.cursor() as db: phone_number = flask.session['phone_number'] users.update_email_address(db, phone_number, email_address)
def post_email_address(): email_address = flask.request.form['email-address'] users.send_email_verification_code(app.config['mailgun_account'], email_address, 1234) signer = itsdangerous.URLSafeSerializer(flask.current_app.secret_key) address_encoded = signer.dumps(email_address) redirect_url = flask.url_for('get_email_addressed', address_encoded=address_encoded) return flask.redirect(redirect_url, code=303)
def password_reset(db): name = request.forms.get("name") flag = users.check_user(db, name) if flag: username = name password = database.return_passwordHashV2(db, name) key = itsdangerous.URLSafeSerializer(config.cred['secretKeys']) token = key.dumps([username, password]) send_email(token, database.return_email(db, name)) return {'result': 'true'} # return a redirect to a page where it says please check your email else: return {'result': 'false'}
def token_reset(db): key = itsdangerous.URLSafeSerializer(config.cred['secretKeys']) user = request.forms.get("user") out = key.loads(user) password = request.forms.get("pword") check = password_test(password) if check: userID = users.return_userID(db, out[0]) hash = database.password_hash(db, password, userID) database.update_password(db, hash, userID) # does this redirect not work anymore??? redirect('http://localhost:3000/') else: return template('pwordReset', user=user, pwordError=True)
async def create(self, session, user: rbt.User, args: rc.CommandArgs, data: Optional[rc.CommandData] = None) -> Optional[Osu]: serializer = itsdangerous.URLSafeSerializer(self.secret_key, salt="osu") # TODO: Ensure the chat the link is being sent in is secure!!! await data.reply( "🔑 [b]Login necessario[/b]\n" f"[url=https://osu.ppy.sh/oauth/authorize" f"?client_id={self.client_id}" f"&redirect_uri={self.base_url}{ApiAuthLoginOsuStar.path}" f"&response_type=code" f"&state={serializer.dumps(user.uid)}]" f"Connetti account di osu! a {user.username}" f"[/url]") return None
def sign_data(data, expires_in=None, **kw): """ To sign url safe data. If expires_in is provided it will Time the signature :param data: (mixed) the data to sign :param expires_in: (int) in minutes. Time to expire :param kw: kwargs for itsdangerous.URLSafeSerializer :return: """ if expires_in: expires_in *= 60 s = URLSafeTimedSerializer2(secret_key=__CRYPT.get("secret_key"), expires_in=expires_in, salt=__CRYPT.get("salt"), **kw) else: s = itsdangerous.URLSafeSerializer( secret_key=__CRYPT.get("secret_key"), salt=__CRYPT.get("salt"), **kw) return s.dumps(data)
def createlink(): projects = request.json['projects'] expire = request.json['expire'] if not expire: expire = (date.today() + timedelta(365)).strftime("%Y-%m-%d") s = itsdangerous.URLSafeSerializer(app.config["SECRET_KEY"]) token = s.dumps({ 'projects': projects, 'expire': expire, }) url = url_for('view', token=token, _external=True) try: url = dvlrit(url) except: pass return jsonify({ 'link': url })
def sign_url_safe(data, secret_key, expires_in=None, salt=None, **kw): """ To sign url safe data. If expires_in is provided it will Time the signature :param data: (mixed) the data to sign :param secret_key: (string) the secret key :param expires_in: (int) in minutes. Time to expire :param salt: (string) a namespace key :param kw: kwargs for itsdangerous.URLSafeSerializer :return: """ if expires_in: expires_in *= 60 s = URLSafeTimedSerializer2(secret_key=secret_key, expires_in=expires_in, salt=salt, **kw) else: s = itsdangerous.URLSafeSerializer(secret_key=secret_key, salt=salt, **kw) return s.dumps(data)
def reactivate_isp(projectid): """ Allow to reactivate an ISP after it has been disabled because of problems with the JSON file. """ p = ISP.query.filter(ISP.id == projectid, ISP.is_disabled == False, ISP.update_error_strike >= 3).first_or_404() if request.method == 'GET': key = request.args.get('key') try: s = itsdangerous.URLSafeSerializer(current_app.secret_key, salt='reactivate') d = s.loads(key) except Exception: abort(403) if (len(d) != 2 or d[0] != p.id or d[1] != str(p.last_update_attempt)): abort(403) session['form_reactivate'] = {'isp_id': p.id} return render_template('reactivate_validator.html', isp=p) else: if 'form_reactivate' not in session or \ not session['form_reactivate'].get('validated', False): abort(409) p = ISP.query.get(session['form_reactivate']['isp_id']) p.json = session['form_reactivate']['jdict'] p.cache_info = session['form_reactivate']['cache_info'] p.last_update_attempt = session['form_reactivate']['last_update'] p.last_update_success = p.last_update_attempt p.update_error_strike = 0 db.session.add(p) db.session.commit() flash(_(u'Automatic updates activated'), 'info') return redirect(url_for('.project', projectid=p.id))
WHERE batchmessages.batch=%s ORDER BY batchmessages.created ASC''' return fetchall(q, batch) def get_unread_batches(userid): q = 'SELECT batch from batchunread where voter=%s' return set(x.batch for x in fetchall(q, userid)) def mark_batch_read(batch, user): l('mark_batch_read', gid=batch, uid=user) q = 'DELETE FROM batchunread WHERE batch=%s AND voter=%s' execute(q, batch, user) """ Discussion """ _USER_FB_ITSD = itsdangerous.URLSafeSerializer(os.environ['ITSD_KEY']) _SENDGRID = sendgrid.SendGridAPIClient(apikey=os.environ['SENDGRID_API_KEY']) _EMAIL_FROM = os.environ['EMAIL_FROM'] _WEB_HOST = os.environ['WEB_HOST'] _TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates') _JINJA = Environment(loader=FileSystemLoader(_TEMPLATE_PATH)) def get_discussion(proposal): q = '''SELECT discussion.*, users.display_name FROM discussion LEFT JOIN users ON (users.id=discussion.frm) WHERE proposal=%s ORDER BY created ASC''' return fetchall(q, proposal) def add_to_discussion(userid, proposal, body, feedback=False, name=None): l('add_to_discussion', uid=userid, id=proposal, body=body,
https://github.com/PlaidWeb/Authl/issues/47 Run with e.g. FLASK_APP=test/rogue_indieauth.py pipenv run flask run -p 6789 """ import urllib.parse import flask import itsdangerous app = flask.Flask(__name__) # pylint:disable=invalid-name sign = itsdangerous.URLSafeSerializer('key') # pylint:disable=invalid=-name @app.route('/', methods=('GET', 'POST')) @app.route('/<path:path>', methods=('GET', 'POST')) def endpoint(path=''): get = flask.request.args post = flask.request.form if 'code' in post: return flask.jsonify({ 'me': sign.loads(post['code']), 'scope': 'read', }) if 'me' in post: redir = post['redirect_uri']
def test_invalid_base64_does_not_fail_load_payload(self): s = idmod.URLSafeSerializer('aha!') self.assertRaises(idmod.BadPayload, s.load_payload, 'kZ4m3du844lIN')
def get_unread_batches(userid): q = 'SELECT batch from batchunread where voter=%s' return set(x.batch for x in fetchall(q, userid)) def mark_batch_read(batch, user): l('mark_batch_read', gid=batch, uid=user) q = 'DELETE FROM batchunread WHERE batch=%s AND voter=%s' execute(q, batch, user) """ Discussion """ _USER_FB_ITSD = itsdangerous.URLSafeSerializer(os.environ['ITSD_KEY']) _MANDRILL = mandrill.Mandrill(os.environ['MANDRILL_API_KEY']) _EMAIL_FROM = os.environ['EMAIL_FROM'] _WEB_HOST = os.environ['WEB_HOST'] _TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates') _JINJA = Environment(loader=FileSystemLoader(_TEMPLATE_PATH)) def get_discussion(proposal): q = '''SELECT discussion.*, users.display_name FROM discussion LEFT JOIN users ON (users.id=discussion.frm) WHERE proposal=%s ORDER BY created ASC''' return fetchall(q, proposal)
def unsign_auth_path(path_signed): """returns the path from a signed/sealed next_path""" notary = itsdangerous.URLSafeSerializer(app.secret_key) next_path_unsigned = notary.loads(path_signed) return next_path_unsigned
def __init__(self): self.secret_key = '1sandeep' self.v_salt = 'email-verification' self.urls1 = ITS_D.URLSafeSerializer(self.secret_key, salt=self.v_salt)
def gen_reactivate_key(isp): s = itsdangerous.URLSafeSerializer(app.secret_key, salt='reactivate') return s.dumps([isp.id, str(isp.last_update_attempt)])
from webargs import fields as wfields from webargs.flaskparser import use_args from wtforms import fields from wtforms import validators from wtforms.fields import html5 from . import notas from . import sendmail app = flask.Flask(__name__) app.secret_key = os.environ["NOTAS_SECRET"] app.config.title = os.environ["NOTAS_COURSE_NAME"] + " - Consulta de Notas" assert app.secret_key signer = itsdangerous.URLSafeSerializer(app.secret_key) class Formulario(flask_wtf.FlaskForm): """Pide el padrón y la dirección de correo. """ padron = fields.StringField( "Padrón", validators=[ validators.Regexp(r"\w+", message="Ingrese un padrón válido") ], ) email = html5.EmailField( "E-mail",
def view(token): s = itsdangerous.URLSafeSerializer(app.config["SECRET_KEY"]) try: data = s.loads(token) except: abort(404) expire = datetime.strptime(data["expire"], "%Y-%m-%d") if expire <= datetime.today(): return render_template("view_error.jade", error="EXPIRED"), 403 o = OdooTimereg() client = o.login( app.config["ODOO_URI"], app.config["ODOO_USER"], app.config["ODOO_PASSWORD"], app.config["ODOO_DB"] ) if "date" in request.args: from_date = MonthDate.fromstring(request.args["date"]) else: from_date = MonthDate.today().prev() to_date = from_date.next() hours = o.hours(client, data["projects"], from_date.topython(), to_date.topython()) hours = parseHours(hours) # Filter non billable hours hours = [h for h in hours if h["billable"]] total = 0 for h in hours: s = h["time"].total_seconds() h["time"] = "%dh %dm" % (s // 3600, (s % 3600) // 60) total += s total = "%dh %dm" % (total // 3600, (total % 3600) // 60) if "csv" in request.args: string = io.StringIO() writer = csv.writer(string) writer.writerow(["Project", "Date", "User", "Remark", "Time"]) for hour in hours: writer.writerow([ hour["project"], hour["date"].strftime("%d %b %Y"), hour["user"], hour["remark"], hour["time"] ]) # Creating the byteIO object from the StringIO Object mem = io.BytesIO() mem.write(string.getvalue().encode()) # seeking was necessary. Python 3.5.2, Flask 0.12.2 mem.seek(0) string.close() fn = "develer-%s-%s.csv" % ("-".join(data["projects"]), from_date.englishformat()) return send_file( mem, attachment_filename=fn, as_attachment=True) prev_url = url_for("view", token=token, date=str(from_date.prev())) next_url = url_for("view", token=token, date=str(from_date.next())) cur_month = from_date.englishformat() num_projects = len(data["projects"]) project_name = ", ".join(data["projects"]) csv_url = url_for("view", token=token, date=from_date, csv=True) return render_template("view.jade", project_name=project_name, num_projects=num_projects, hours=hours, total=total, cur_month=cur_month, prev_url=prev_url, next_url=next_url, csv_url=csv_url)
import csv import datetime from bson.objectid import ObjectId from flask import current_app, url_for, render_template from flask.ext.login import UserMixin from .mail import send_mail from copy import deepcopy import itsdangerous from flask_blog import db, app from utils import after_app_teardown from pymongo import IndexModel, ASCENDING serializer = itsdangerous.URLSafeSerializer( secret_key=app.config['SECRET_KEY']) ACTIVATION_SALT = app.config['ACTIVATION_SALT'] # bytes(urandom(10)) def get_activation_hash(user): return serializer.dumps(str(user._id), salt=ACTIVATION_SALT) class MongoBase(object): _id = None def __getattr__(self, key): if key in self.values: return self.values[key] else:
def __init__(self): self.s = itsdangerous.URLSafeSerializer(SECRET_KEY) self.expire = EXPIRE
async def get(self, data: rca.ApiData) -> ru.JSON: """Login to Royalnet with your osu! account.""" OsuT = self.alchemy.get(Osu) TokenT = self.alchemy.get(rbt.Token) code = data.str("code") state = data.str("state", optional=True) if state is not None: serializer = itsdangerous.URLSafeSerializer( self.config["secret_key"], salt="osu") uid = serializer.loads(state) user = await rbt.User.find(self.alchemy, data.session, uid) else: user = None try: t = await oauth_auth(url="https://osu.ppy.sh/oauth/token", client_id=self.client_id, client_secret=self.client_secret, redirect_uri=f"{self.base_url}{self.path}", auth_code=code) except aiohttp.client_exceptions.ClientResponseError as e: ru.sentry_exc(e) raise rca.ForbiddenError( "osu! API returned an error in the OAuth token exchange") async with aiohttp.ClientSession( headers={"Authorization": f"Bearer {t['access_token']}" }) as session: async with session.get( "https://osu.ppy.sh/api/v2/me/") as response: m = await response.json() if user is not None: osu = OsuT(user=user, access_token=t["access_token"], refresh_token=t["refresh_token"], expiration_date=datetime.datetime.now() + datetime.timedelta(seconds=t["expires_in"]), osu_id=m["id"], username=m["username"]) data.session.add(osu) else: osu = await ru.asyncify( data.session.query(OsuT).filter_by(osu_id=m["id"]).all) if osu is None: raise rcae.ForbiddenError("Unknown osu! account") user = osu.user if self.config["osu"]["login"]["enabled"]: token: rbt.Token = TokenT.generate( alchemy=self.alchemy, user=user, expiration_delta=datetime.timedelta(days=7)) data.session.add(token) await data.session_commit() return token.json() else: await data.session_commit() raise rcae.ForbiddenError( "Account linked successfully; cannot use this account to generate a Royalnet" " login token, as osu! login is currently disabled on this Royalnet instance." )
# coding: utf-8 import itsdangerous import redis from .settings import config signer = itsdangerous.URLSafeSerializer("notasecurekey") rd = redis.StrictRedis(config.redis_host, config.redis_port, decode_responses=True)
def pword(db, tok): key = itsdangerous.URLSafeSerializer(config.cred['secretKeys']) out = key.loads(tok) res = database.check_user(db, out[0], out[1]) if res: return template('pwordReset', user=tok, pwordError=False)
def query_signer(): return itsdangerous.URLSafeSerializer(current_app.config['SECRET_KEY'], salt='fdt-sql-query')
def _url_safe_serializer(): # URL安全序列化 s = itsdangerous.URLSafeSerializer('secret-key') s.loads(s.dumps([1, 2, 3]))