Beispiel #1
0
 def validate_machine_token(self, token):
     s = Signer(self.secret)
     try:
         s.unsign(token)
         return True
     except BadSignature:
         return False
Beispiel #2
0
def validate_csrf_token(csrf_token):
    secret_key = current_app.config.get("WTF_CSRF_SECRET_KEY", current_app.secret_key)
    signer = Signer(secret_key)
    # if current_user.is_anonymous():
    #     return False

    try:
        signer.unsign(csrf_token)
    except BadSignature:
        return False

    # if str(current_user.get_id()) == id:
    #     return True
    return True
Beispiel #3
0
 def get_from_signed_code(cls, code):
     """Returns a discount policy given a valid signed code, returns None otherwise"""
     if not cls.is_signed_code_format(code):
         return None
     discount_code_base = code.split('.')[0]
     policy = cls.query.filter_by(discount_code_base=discount_code_base).one_or_none()
     if not policy:
         return None
     signer = Signer(policy.secret)
     try:
         signer.unsign(code)
         return policy
     except BadSignature:
         return None
def get_username_from_confirmation_token(app, confirmation_token):
    signer = Signer(app.config['SECRET_KEY'], salt='confirmation')
    try:
        username = signer.unsign(confirmation_token)
    except BadSignature:
        return None
    return username
def reset_password():
    form = ResetPasswordForm(request.form)

    if request.method == "POST" and form.validate():
        token = form.token.data

        s = Signer(app.config['SECRET_KEY'])

        try:
            email = s.unsign(token)
        except BadSignature:
            return render_template("reset_invalid_token.html")

        user = User.query.filter_by(email=email).first()

        if user:
            user.set_password(form.password.data)

            print user.password

            login_user(user)

            return redirect("/")
        else:
            return render_template("reset_invalid_token.html")

    token = request.args.get('token', None)

    if not token:
        return render_template("reset_invalid_token.html")

    return render_template("reset_password.html", form=form, token=token)
Beispiel #6
0
def on_confirm_email(token):
    """Email confirmation endpoint.

    We try to confirm the specified signup and redirect to a webpage.
    """
    try:
        s = Signer(get_token_secret())
        signup_id = ObjectId(s.unsign(token).decode('utf-8'))
    except BadSignature:
        return "Unknown token"

    patch_internal('eventsignups', {'confirmed': True},
                   skip_validation=True, concurrency_check=False,
                   **{current_app.config['ID_FIELD']: signup_id})

    # Now the user may be able to get accepted, so update the events waiting
    # list
    lookup = {current_app.config['ID_FIELD']: signup_id}
    signup = current_app.data.find_one('eventsignups', None, **lookup)

    update_waiting_list(signup['event'])

    redirect_url = current_app.config.get('EMAIL_CONFIRMED_REDIRECT')
    if redirect_url:
        return redirect(redirect_url)
    else:
        return current_app.config['CONFIRM_TEXT']
Beispiel #7
0
def reset_password():
    form = ResetPasswordForm(request.form)

    if request.method == "POST" and form.validate():
        token = form.token.data

        s = Signer(app.config['SECRET_KEY'])

        try:
            email = s.unsign(token)
        except BadSignature:
            return render_template("reset_invalid_token.html")

        user = User.query.filter_by(email=email).first()

        if user:
            user.set_password(form.password.data)

            print user.password

            login_user(user)

            return redirect("/")
        else:
            return render_template("reset_invalid_token.html")

    token = request.args.get('token', None)

    if not token:
        return render_template("reset_invalid_token.html")

    return render_template("reset_password.html", form=form, token=token)
Beispiel #8
0
def mailbox_confirm_change_route():
    s = Signer(MAILBOX_SECRET)
    mailbox_id = request.args.get("mailbox_id")

    try:
        r_id = int(s.unsign(mailbox_id))
    except Exception:
        flash("Invalid link", "error")
        return redirect(url_for("dashboard.index"))
    else:
        mailbox = Mailbox.get(r_id)

        # new_email can be None if user cancels change in the meantime
        if mailbox and mailbox.new_email:
            mailbox.email = mailbox.new_email
            mailbox.new_email = None

            # mark mailbox as verified if the change request is sent from an unverified mailbox
            mailbox.verified = True
            db.session.commit()

            LOG.d("Mailbox change %s is verified", mailbox)
            flash(f"The {mailbox.email} is updated", "success")
            return redirect(
                url_for("dashboard.mailbox_detail_route",
                        mailbox_id=mailbox.id))
        else:
            flash("Invalid link", "error")
            return redirect(url_for("dashboard.index"))
Beispiel #9
0
def confirm_user(data=None):
    if not utils.get_config('verify_emails'):
        return redirect(url_for('challenges.challenges_view'))
    if data and request.method == "GET":  # User is confirming email account
        try:
            s = Signer(app.config['SECRET_KEY'])
            email = s.unsign(urllib.unquote_plus(data.decode('base64')))
        except BadSignature:
            return render_template(
                'confirm.html', errors=['Your confirmation link seems wrong'])
        except:
            return render_template(
                'confirm.html',
                errors=['Your link appears broken, please try again.'])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} confirmed {2}".format(
            time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'),
            team.email.encode('utf-8')))
        db.session.close()
        if utils.authed():
            return redirect(url_for('challenges.challenges_view'))
        return redirect(url_for('auth.login'))
    if not data and request.method == "GET":  # User has been directed to the confirm page because his account is not verified
        if not utils.authed():
            return redirect(url_for('auth.login'))
        team = Teams.query.filter_by(id=session['id']).first_or_404()
        if team.verified:
            return redirect(url_for('views.profile'))
        else:
            utils.verify_email(team.email)
        return render_template('confirm.html', team=team)
def action():
    if not 'action' in request.json:
        abort(400)
    s = Signer(signkey)
    try:
        action = s.unsign(request.json['action'])
    except:
        abort(403)

    action = action.split('.', 1)
    if action[0] == 'LIST':
        return getList()

    if action[0] == 'GET':
        if len(action) != 2:
            abort(400)
        obj = action[1].split('.', 1)
        if len(obj) != 2:
            abort(400)

        key = obj[1]
        return getObject(key)

    if action[0] == 'STORE':
        if len(action) != 2:
            abort(400)
        return store(action[1])

    if action[0] == 'DELETE':
        if len(action) != 2:
            abort(400)
        return delete(action[1])

    abort(400)
Beispiel #11
0
def auth_mfa():
    """
    Validate the OTP Token
    Input:
        mfa_token: OTP token that user enters
        mfa_key: MFA key obtained in previous auth request, e.g. /api/auth/login
        device: the device name, used to create an ApiKey associated with this device
    Output:
        200 and user info containing:
        {
            name: "John Wick",
            api_key: "a long string",
            email: "user email"
        }

    """
    data = request.get_json()
    if not data:
        return jsonify(error="request body cannot be empty"), 400

    mfa_token = data.get("mfa_token")
    mfa_key = data.get("mfa_key")
    device = data.get("device")

    s = Signer(FLASK_SECRET)
    try:
        user_id = int(s.unsign(mfa_key))
    except Exception:
        return jsonify(error="Invalid mfa_key"), 400

    user = User.get(user_id)

    if not user:
        return jsonify(error="Invalid mfa_key"), 400
    elif not user.enable_otp:
        return (
            jsonify(
                error=
                "This endpoint should only be used by user who enables MFA"),
            400,
        )

    totp = pyotp.TOTP(user.otp_secret)
    if not totp.verify(mfa_token):
        return jsonify(error="Wrong TOTP Token"), 400

    ret = {"name": user.name, "email": user.email}

    api_key = ApiKey.get_by(user_id=user.id, name=device)
    if not api_key:
        LOG.d("create new api key for %s and %s", user, device)
        api_key = ApiKey.create(user.id, device)
        db.session.commit()

    ret["api_key"] = api_key.code

    # so user is logged in automatically on the web
    login_user(user)

    return jsonify(**ret), 200
Beispiel #12
0
 def check_token(token):
     signer = Signer(flask.current_app.config["SECRET_KEY"])
     try:
         id = int(signer.unsign(token).decode("ascii"))
     except Exception as e:
         return None
     user = Subscriber.query.filter_by(id=id).first()
     return user
Beispiel #13
0
 def open_session(self, app, request):
     signedSessionId = request.cookie.get(app.session_cookie_name)
     if not signedSessionId:
         sessionId = str(uuid.uuid4())
         return self.session_class(sessionId=sessionId)
     signer = Signer(app.secret_key, salt=self.salt, key_derivation='hmac')
     sessionId = signer.unsign(signedSessionId).decode()
     return self.session_class(sessionId=sessionId)
Beispiel #14
0
 def get_from_signed_code(cls, code, organization_id):
     """Returns a discount policy given a valid signed code, returns None otherwise"""
     if not cls.is_signed_code_format(code):
         return None
     discount_code_base = code.split('.')[0]
     policy = cls.query.filter_by(
         discount_code_base=discount_code_base,
         organization_id=organization_id
     ).one_or_none()
     if not policy:
         return None
     signer = Signer(policy.secret)
     try:
         signer.unsign(code)
         return policy
     except BadSignature:
         return None
Beispiel #15
0
 def attachment(self, att_id):
     s = Signer(current_app.config.get('SECRET_KEY'), sep='$')
     try:
         att_id = int(s.unsign(att_id))
         attach_obj = self.model.client.model('ir.attachment')
         content = attach_obj.read(att_id, ['datas'])['datas']
         image_fp = StringIO(base64.b64decode(content))
         return send_file(image_fp)
     except BadSignature:
         abort(404)
    def split_cookie(self, rv):
        signer = Signer(self.app.secret_key)
        cookie_data = rv.headers['Set-Cookie'].split(';', 1)[0]

        for cookie in cookie_data.split('&'):
            name, value = cookie_data.split('=')

            if name == self.app.session_cookie_name:
                unsigned_value = signer.unsign(value)
                return unsigned_value.split('_')
Beispiel #17
0
 def attachment(self, att_id):
     s = Signer(current_app.config.get('SECRET_KEY'), sep='$')
     try:
         att_id = int(s.unsign(att_id))
         attach_obj = self.model.client.model('ir.attachment')
         content = attach_obj.read(att_id, ['datas'])['datas']
         image_fp = StringIO(base64.b64decode(content))
         return send_file(image_fp)
     except BadSignature:
         abort(404)
def split_cookie(app, rv):
    signer = Signer(app.secret_key)
    cookie_data = rv.headers['Set-Cookie'].split(';', 1)[0]

    for cookie in cookie_data.split('&'):
        name, value = cookie_data.split('=')

        if name == app.session_cookie_name:
            unsigned_value = signer.unsign(value)
            sid, created = unsigned_value.split(b('_'))
            return sid.decode('ascii'), int(created, 16)
Beispiel #19
0
def cookie_unserialize(session_data, secure_key):
    """Unserialize the cookie: separate the session_id and expire_time timestamp."""
    signer = Signer(secret_key=secure_key)
    try:
        session_data = signer.unsign(session_data).decode('utf-8')
    except BadSignature:
        session_data = None
    if not session_data:
        return None, None
    session_id, session_expire = session_data.split('&')
    return session_id, session_expire
Beispiel #20
0
def main():
    k = 'bt6n4k2m'
    signer = Signer(k)
    s = '11878121-b36d-4c38-9f87-682e8986d1f9'
    ss = signer.sign(s)
    print('signed str: {}'.format(ss))
    us = signer.unsign(ss)
    print('unsigned str: {}'.format(us))

    # 做点改动
    try:
        print(signer.unsign('{}a'.format(ss)))
    except BadSignature as e:
        print e

    print('------')
    cid = 110000000000000262
    uid = 105697106
    for i in xrange(10):
        print(signer.sign("{}_{}".format(cid, uid + i)))
Beispiel #21
0
def split_cookie(app, rv):
    signer = Signer(app.secret_key)
    cookie_data = rv.headers["Set-Cookie"].split(";", 1)[0]

    for cookie in cookie_data.split("&"):
        name, value = cookie_data.split("=")

        if name == app.session_cookie_name:
            unsigned_value = signer.unsign(value)
            sid, created = unsigned_value.split(b("_"))
            return sid.decode("ascii"), int(created, 16)
Beispiel #22
0
def split_cookie(app, rv):
    signer = Signer(app.secret_key)
    cookie_data = rv.headers['Set-Cookie'].split(';', 1)[0]

    for cookie in cookie_data.split('&'):
        name, value = cookie_data.split('=')

        if name == app.session_cookie_name:
            unsigned_value = signer.unsign(value)
            sid, created = unsigned_value.split(b('_'))
            return sid.decode('ascii'), int(created, 16)
Beispiel #23
0
def format():
    md = request.form.get(
        "text", "# hello\nyou didnt put anything so this is default doc")
    filename = '/tmp/' + str(uuid.uuid4())
    dbg_option = request.form.get("debug", "")
    template = request.form.get(
        "template", """
    \\documentclass[12pt]{article}
    \\begin{document}
    $body$
    
    Generated by DocuFMT
    \\end{document}
  """)
    if dbg_option != "":
        # this makes us super safe
        with open("/key", "r") as key_file:
            skey = key_file.read().strip()
        s = Signer(skey)
        try:
            dbg_option = s.unsign(dbg_option).decode('utf-8')
        except BadSignature:
            return "ERROR: debug option is not signed correctly"

    with open(filename + ".md", "w") as text_file:
        text_file.write(md)
    with open(filename + "_template.tex", "w") as text_file:
        text_file.write(template)
    try:
        p = Popen(('timeout', '5', 'pandoc',
                   '--template=' + filename + "_template.tex",
                   '--from=markdown', '-s', '-o', filename + '.pdf',
                   '--latex-engine-opt', dbg_option, filename + '.md'),
                  stdout=PIPE,
                  stderr=PIPE)
        out, err = p.communicate()
        exitcode = p.returncode
        if exitcode != 0:
            rsp = make_response(
                "%s\n%s\nexited with error code %d" % (out, err, exitcode))
            rsp.headers['Content-type'] = 'text/plain'
            return rsp
        try:
            with open(filename + '.pdf', mode='rb') as pdf_file:
                rsp = make_response(pdf_file.read())
                rsp.headers['Content-type'] = "application/pdf"
            return rsp
        except FileNotFoundError:
            rsp = make_response(
                "%s\n%s\nNo response PDF generated" % (out, err))
            rsp.headers['Content-type'] = 'text/plain'
            return rsp
    except Exception as e:
        return "ERROR: " + str(e)
Beispiel #24
0
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'))

    # User is confirming email account
    if data and request.method == "GET":
        try:
            s = Signer(app.config['SECRET_KEY'])
            email = s.unsign(urllib.unquote_plus(data.decode('base64')))
        except BadSignature:
            return render_template(
                'confirm.html', errors=['Your confirmation link seems wrong'])
        except:
            return render_template(
                'confirm.html',
                errors=['Your link appears broken, please try again.'])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} confirmed {2}".format(
            time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'),
            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)
            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)
Beispiel #25
0
 def open_session(self, app, request):
     signed_id = request.cookies.get(app.session_cookie_name)
     if not signed_id:
         return InMemorySession()
     try:
         signer = Signer(app.secret_key)
         session_id = signer.unsign(signed_id).decode("utf-8")
         if session_id in self._sessions:
             return self._sessions[session_id]
         else:
             return InMemorySession()
     except BadSignature:
         return InMemorySession()
def verify():
    s = Signer(
            bytes(input("Enter a secret(!!) key: "),
                  encoding="UTF-8"))
    try:
        unsigned = s.unsign(bytes(
            input("Enter data\n"),
            encoding="UTF-8")).decode('UTF-8')
    except BadSignature:
        print("!!!!! FAILED !!!!!")
        return 0
    print("---")
    print(unsigned)
Beispiel #27
0
def alias_transfer_receive_route():
    """
    URL has ?alias_id=signed_alias_id
    """
    s = Signer(ALIAS_TRANSFER_SECRET)
    signed_alias_id = request.args.get("alias_id")

    try:
        alias_id = int(s.unsign(signed_alias_id))
    except Exception:
        flash("Invalid link", "error")
        return redirect(url_for("dashboard.index"))
    else:
        alias = Alias.get(alias_id)

    # alias already belongs to this user
    if alias.user_id == current_user.id:
        flash("You already own this alias", "warning")
        return redirect(url_for("dashboard.index"))

    mailboxes = current_user.mailboxes()

    if request.method == "POST":
        mailbox_ids = request.form.getlist("mailbox_ids")
        # check if mailbox is not tempered with
        mailboxes = []
        for mailbox_id in mailbox_ids:
            mailbox = Mailbox.get(mailbox_id)
            if (not mailbox or mailbox.user_id != current_user.id
                    or not mailbox.verified):
                flash("Something went wrong, please retry", "warning")
                return redirect(request.url)
            mailboxes.append(mailbox)

        if not mailboxes:
            flash("You must select at least 1 mailbox", "warning")
            return redirect(request.url)

        LOG.d("transfer alias from %s to %s with %s", alias.user, current_user,
              mailboxes)
        transfer(alias, current_user, mailboxes)
        flash(f"You are now owner of {alias.email}", "success")
        return redirect(url_for("dashboard.index",
                                highlight_alias_id=alias.id))

    return render_template(
        "dashboard/alias_transfer_receive.html",
        alias=alias,
        mailboxes=mailboxes,
    )
Beispiel #28
0
def reset_password(token):

    signerU = Signer(app.secret_key)
    try:
        email = signerU.unsign(token)

    except BadSignature:
        flash('Invalid token')
        return redirect(url_for('index'))

    else:
        flash(email)

        return render_template('reset_password.html', email=email)
Beispiel #29
0
def task_run():
    signer = Signer(current_app.secret_key)

    _data = request.form['_']
    data = json.loads(signer.unsign(_data))

    callname = data.get('call')
    a, kw = data['args'], data['kwargs']

    modname, symname = callname.rsplit('.', 1)
    mod = __import__(modname, fromlist=[symname])
    call = getattr(mod, symname)

    call.direct(*a, **kw)
    return 'ok'
def share():
    if not 'sig' in request.args:
        abort(403)
    s = Signer(signkey)
    try:
        action = s.unsign(request.args['sig'])
    except:
        abort(403)

    action = action.split('.', 1)
    key = action[0]
    if not key in objects:
        abort(404)

    return getObject(key)
Beispiel #31
0
 def open_session(self, app, request):
     signed_id = request.cookies.get(app.session_cookie_name)
     if not signed_id:
         return Session(new=True)
     try:
         signer = Signer(app.secret_key)
         session_id = signer.unsign(signed_id)
         if self.r.exists(b"session." + session_id):
             return msgpack.unpackb(self.r.get(b"session." + session_id),
                                    object_hook=unpack_hook,
                                    raw=False)
         else:
             return Session(new=True)
     except BadSignature:
         return Session(new=True)
def _get_user_id():
    if current_app.config.get('DEBUG'):
        return request.values.get('user_id')

    if 'mws-track-id' not in request.cookies:
        raise MWSServerError(400, "Invalid request (missing cookie)")

    key = current_app.config.get('EDX_SHARED_KEY')
    s = Signer(key)
    try:
        user_id = s.unsign(request.cookies['mws-track-id'])
    except (BadSignature, TypeError) as e:
        _logger.exception(e)
        raise MWSServerError(403, "Invalid request (invalid cookie)")
    return user_id
Beispiel #33
0
def _get_user_id():
    if current_app.config.get('DEBUG'):
        return request.values.get('user_id')

    if 'mws-track-id' not in request.cookies:
        raise MWSServerError(400, "Invalid request (missing cookie)")

    key = current_app.config.get('EDX_SHARED_KEY')
    s = Signer(key)
    try:
        user_id = s.unsign(request.cookies['mws-track-id'])
    except (BadSignature, TypeError) as e:
        _logger.exception(e)
        raise MWSServerError(403, "Invalid request (invalid cookie)")
    return user_id
Beispiel #34
0
def get_public_deploy_key(instance_dns_name, secret, salt):
    ''' Wait for and retrieve instance public key.
    '''
    signer = Signer(secret, salt)
    path = '/.well-known/deploy-key.txt'

    while True:
        print('    Waiting for', path)
        sleep(5)

        resp = requests.get('http://{}{}'.format(instance_dns_name, path))

        if resp.status_code == 200:
            break

    return signer.unsign(resp.content)
Beispiel #35
0
def on_delete_signup(token):
    """Endpoint to delete signups via email"""
    try:
        s = Signer(get_token_secret())
        signup_id = ObjectId(s.unsign(token).decode('utf-8'))
    except BadSignature:
        return "Unknown token"

    deleteitem_internal('eventsignups', concurrency_check=False,
                        **{current_app.config['ID_FIELD']: signup_id})

    redirect_url = current_app.config.get('SIGNUP_DELETED_REDIRECT')
    if redirect_url:
        return redirect(redirect_url)
    else:
        return current_app.config['SIGNUP_DELETED_TEXT']
Beispiel #36
0
def get_public_deploy_key(instance_dns_name, secret, salt):
    ''' Wait for and retrieve instance public key.
    '''
    signer = Signer(secret, salt)
    path = '/.well-known/deploy-key.txt'

    while True:
        print('    Waiting for', path)
        sleep(5)

        resp = requests.get('http://{}{}'.format(instance_dns_name, path))

        if resp.status_code == 200:
            break

    return signer.unsign(resp.content)
Beispiel #37
0
def confirmation(token):
    signer = Signer(app.secret_key)
    try:
        email = signer.unsign(token)

    except BadSignature:
        flash('Invalid token')
        return redirect(url_for('index'))

    else:
        userC = p.PeopleProfile.query.filter_by(email=email).first()
        userC.active = True
        db.session.add(userC)
        db.session.commit()
        flash('Your account is verified')
        return redirect(url_for('user'))
def uid_is_valid(user, uid, festival):
    s = Signer(SECRET_SIGN_KEY)
    # cookie is uid hashed with our private key, check that the cookie was sent
    cookie = cherrypy.request.cookie.get('mfc_sch'+str(uid))
    if cookie:
        # and if it's correct
        return str(uid) == s.unsign(str(cookie.value))
    elif user:
        #check if this user is the user that's allowed for this uid.
        with get_db() as cur:
            cur.execute("select id from mfc.schedules where username = %s and festival = %s", [user['email'], festival])
            r = cur.fetchall()
        if r:
            return str(uid) == str(r[0]['id'])
    # else not valid
    else:
        return False
Beispiel #39
0
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'))

    # User is confirming email account
    if data and request.method == "GET":
        try:
            s = Signer(app.config['SECRET_KEY'])
            email = s.unsign(urllib.unquote_plus(data.decode('base64')))
        except BadSignature:
            return render_template('confirm.html', errors=['Your confirmation link seems wrong'])
        except:
            return render_template('confirm.html', errors=['Your link appears broken, please try again.'])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} confirmed {2}".format(time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'), 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)
            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)
Beispiel #40
0
 def decorated_view(*args, **kwargs):
     """
     """
     if '_session_id' in login_session:
         s = Signer('secret_key')
         user_id = s.unsign(login_session.get('_session_id'))
         try:
             user = session.query(User).filter_by(id=user_id).one()
         except NoResultFound:
             app.logger.error("Error: {}.".format(NoResultFound))
         if user:
             return fnc(*args, **kwargs)
         else:
             flash("Session exists, but user does not exist (anymore)")
             return make_response('not authorized')
     else:
         flash("Please log in")
         return make_response('not authorized')
Beispiel #41
0
def mailbox_verify():
    s = Signer(MAILBOX_SECRET)
    mailbox_id = request.args.get("mailbox_id")

    try:
        r_id = int(s.unsign(mailbox_id))
    except Exception:
        flash("Invalid link. Please delete and re-add your mailbox", "error")
        return redirect(url_for("dashboard.mailbox_route"))
    else:
        mailbox = Mailbox.get(r_id)
        mailbox.verified = True
        db.session.commit()

        LOG.d("Mailbox %s is verified", mailbox)

        return render_template("dashboard/mailbox_validation.html",
                               mailbox=mailbox)
Beispiel #42
0
def join_team(team_link):
    errors = []
    if authed():
        user = Users.query.filter_by(id=session.get('id')).first_or_404()
        s = Signer(app.config['SECRET_KEY'])
        team_id = s.unsign(urllib.unquote_plus(team_link.decode('base64')))
        team = Teams.query.filter_by(id=team_id).first_or_404()
        user_ids = [
            u.id for u in Users.query.with_entities(Users.id).filter_by(
                teamid=team.id)
        ]
        team_captain = Teams.query.filter_by(captain=user.id).first()
        print team_captain
        if request.method == "POST":
            if len(user_ids) >= get_config('team_limit'):
                errors.append('This team is full')
            if team_captain:
                errors.append(
                    "You are captain of another team, you can't join another team"
                )
            if errors:
                return render_template('join_team.html',
                                       team=team,
                                       errors=errors)
            user.teamid = int(team.id)
            db.session.commit()
            db.session.close()
            return redirect(url_for('views.team_management'))
        else:
            if len(user_ids) >= get_config('team_limit'):
                errors.append('This team is full')
            if user.teamid:
                errors.append(
                    'You are already on a team. <br>Joining a new team will take all your solves with you.'
                )
            if team_captain:
                errors.append(
                    "You are captain of another team, you can't join another team"
                )
            return render_template('join_team.html', team=team, errors=errors)
    else:
        return redirect(url_for('auth.login', next=request.path))
Beispiel #43
0
class DriverAuth:
    def __init__(self, secret_key=settings.SECRET_KEY):
        if secret_key is None:
            raise Exception("secret key not set")

        self.s = Signer(secret_key)

    def createtoken(self, id):
        token = self.s.sign(str(id).encode())
        return base64.b64encode(token).decode('UTF-8')

    def verifytoken(self, token):
        """Returns if the token is valid otherwise, returns throws does not
        exist exception """
        try:
            bytesToken = base64.b64decode(token.encode())
            id = self.s.unsign(bytesToken)
            driver = Driver.objects.get(pk=id)
            return driver
        except (ObjectDoesNotExist, BadSignature):
            raise BadTokenError()
Beispiel #44
0
def confirm_user(data=None):
    if not get_config('verify_emails'):
        return redirect(url_for('challenges.challenges_view'))
    if data and request.method == "GET":  ## User is confirming email account
        try:
            s = Signer(app.config['SECRET_KEY'])
            email = s.unsign(data.decode('base64'))
        except BadSignature:
            return render_template('confirm.html', errors=['Your confirmation link seems wrong'])
        team = Teams.query.filter_by(email=email).first()
        team.verified = True
        db.session.commit()
        db.session.close()
        if authed():
            return redirect(url_for('challenges.challenges_view'))
        return redirect(url_for('auth.login'))
    if not data and request.method == "GET": ## User has been directed to the confirm page because his account is not verified
        team = Teams.query.filter_by(id=session['id']).first()
        if team.verified:
            return redirect(url_for('views.profile'))
        return render_template('confirm.html', team=team)
Beispiel #45
0
def create_item():
    """
    Create a new item for the catalog
    """
    s = Signer('secret_key')
    user_id = s.unsign(login_session.get('_session_id'))
    category_list = session.query(Category).all()
    if request.method == 'POST':
        new_item = Item(name=request.form['name'],
                        description=request.form['description'],
                        category_id=request.form['category'],
                        created_by=user_id,
                        price=request.form['price'])
        session.add(new_item)
        try:
            session.commit()
        except IntegrityError:
            app.logger.error("Error: {}".format(IntegrityError))
        flash("Created new catalog item.")
        return redirect(url_for('get_categories'))
    return render_template('createitem.html', category_list=category_list)
Beispiel #46
0
class Pastie:

    SECRET_KEY = '\x85\xe1Pc\x11n\xe0\xc76\xa1\xd9\x93$\x1ei\x06'
    HTTBL_KEY = 'THIS IS NOT A VALID HTTPBL KEY'

    def __init__(self, data_dir='pastes/', host='http://localhost/'):

        self.httpbl = HttpBL(self.HTTBL_KEY)
        self.signer = Signer(self.SECRET_KEY)

        self.jinja_env = Environment(loader=FileSystemLoader(
            join(dirname(__file__), 'layouts'))
        )
        self.host = host
        self.data_dir = data_dir

        if not isdir(data_dir):
            makedirs(data_dir)

    def render_template(self, template_name, **kwargs):
        return self.jinja_env.get_template(template_name).render(**kwargs)

    def sign(self, value):
        return self.signer.sign(value)

    def unsign(self, value):
        return self.signer.unsign(value)

    def dispatch(self, request, start_response):

        adapter = urlmap.bind_to_environ(request.environ)
        request.adapter = adapter

        try:
            endpoint, values = adapter.match()
            return endpoint(self, request, **values)
        except NotFound, e:
            return Response('Not Found', 404)
        except HTTPException, e:
            return e
Beispiel #47
0
def load_user_from_signed_token(signed_token):
    s = Signer(current_app.config['SECRET_KEY'])
    auth_token = None
    try:
        auth_token = s.unsign(signed_token)
    except:
        pass
    if auth_token:
        user = User.query.filter_by(auth_token=auth_token).first()
        if user:
            session['auth_token'] = user.auth_token
            LogEvent.remember_me_authenticated(user)
            return user
        else:
            LogEvent.remember_me_bad_auth_token()
    else:
        LogEvent.remember_me_cookie_malformed()
    # This causes Flask-Login to clear the "remember me" cookie. This could
    # break if Flask-Login's internal implementation changes. A better way
    # should be implemented. Perhaps install an after_request hook.
    session['remember'] = 'clear'
    return None
Beispiel #48
0
    def open_session(self, app, request):
        sessionid = request.cookies.get(app.session_cookie_name, None)
        if sessionid is None:
            sessionid = self.generate_sessionid()
            return ServerSession(session_id=sessionid)

        if self.use_sign and app.secret_key:
            signer = Signer(app.secret_key, salt='flask-redis-session',
                            key_derivation='hmac')
            try:
                sessionid = signer.unsign(sessionid).decode('utf-8')
            except BadSignature:
                sessionid = 'None'

        data = self.redis.get(self.session_prefix + sessionid)
        if data is None:
            return ServerSession(session_id=sessionid)
        try:
            json_data = self.serialization_method.loads(data)
            return ServerSession(json_data, session_id=sessionid)
        except:
            return ServerSession(session_id=sessionid)
Beispiel #49
0
 def attachments(self):
     attach_obj = self.model.client.model('ir.attachment')
     obj_id = request.args.get('id')
     if not obj_id:
         return abort(404)
     if request.method == 'POST':
         if request.args.get('action') == "delete":
             attach_id = request.args.get('attach_id')
             if not attach_id:
                 return abort(404)
             try:
                 s = Signer(current_app.config.get('SECRET_KEY'), sep='$')
                 attach_id = int(s.unsign(attach_id))
             except BadSignature:
                 return abort(404)
             attach_obj.unlink([attach_id])
             flash("Attachment deleted succesfully", "info")
         else:
             created = 0
             for key, value in request.files.items():
                 if key.startswith('attachment_'):
                     content = base64.b64encode(value.read())
                     if not content:
                         continue
                     name_field = 'name_'+key.split('_')[1]
                     name = request.form.get(name_field, value.filename)
                     attach_obj.create({
                         'name': name,
                         'datas': content,
                         'datas_fname': value.filename,
                         'res_model': self.model._name,
                         'res_id': obj_id
                     })
                     created += 1
             flash("%s new attachments created" % created, "info")
         return redirect(url_for('.edit_view', id=obj_id))
Beispiel #50
0
def get_sign_safe(true_file):
    s= Signer(Config.login_sign)
    return s.unsign(true_file)
Beispiel #51
0
def unsign(s, config):
    signer = Signer(config['SIGNING_KEY'])
    try:
        return signer.unsign(s)
    except BadSignature:
        raise BadRequestError()
Beispiel #52
0
#
# Free Coding session for 2015-03-09
# Written by Matt Warren
#


if __name__ == '__main__':
    s = Signer('secret-password')
    signed_string = s.sign(b'data to sign')
    print(signed_string)  # HMAC SHA1 signed string

    # tamper with string
    signed_string = b'my ' + signed_string
    try:
        s.unsign(signed_string)
    except BadSignature as e:
        print("failed to unsign the modified data")

    s = TimestampSigner('secret-password', salt='signup')  # adds current time to data
    signed_string = s.sign(b'data to sign')
    print(signed_string)
    s.unsign(signed_string, max_age=5)  # would only unsign if signed less than 5 seconds ago
    time.sleep(2)
    try:
        s.unsign(signed_string, max_age=1)  # would only unsign if signed less than 1 seconds ago
    except SignatureExpired as e:
        print('tried to unsign expired data')

    s = JSONWebSignatureSerializer('secret-password')
    print(s.dumps({'name': 'matt'}))
Beispiel #53
0
class User():
    def __init__(self,secret_key):
        #initialize signer
        self.s = Signer(secret_key)
        

    def deserialize(self,request):
        #it runs in framework BEFORE_REQUEST function
        self.cookies = request.cookies
        #check stat in cookie and verify it
        stat_str = str(self.cookies.get('stat'))
        stat_signature = str(self.cookies.get('stat_signature'))
        stat_token = stat_str+'.'+stat_signature
        

        if stat_str=='None' or self.s.validate(stat_token)==False:
            self._create_new_stat(request)
        #if validation success
        else:
            self.stat = json.loads(stat_str)        

        #increase kolvo_visits
        self._increase_kolvo_visits()

        #add actual IP for checking log_token
        self.stat['ip'] = request.environ['REMOTE_ADDR']
        self.log_token = str(self.cookies.get('log_token'))

        #initialize DB
        self._db_init()


    def serialize(self,response):
        #it runs in framework AFTER_REQUEST function
        stat_str = json.dumps(self.stat)

        sign_str = self.s.sign(stat_str)
        last_elem = len(sign_str.split('.'))
        #because dots in IP
        self.stat_signature = sign_str.split('.')[last_elem-1]

        response.set_cookie('stat',value=stat_str)
        response.set_cookie('stat_signature',value=self.stat_signature)

        if self.log_token!='None':
            response.set_cookie('log_token',value=self.log_token)
	else:
            response.set_cookie('log_token','',expires=0)
 


        #increase visits
        return response

    def _create_new_stat(self,request):
        self.stat = {}
        

        self.stat['ip'] = request.environ['REMOTE_ADDR']
        self.stat['first_reg'] = int(time.time())
        self.stat['kolvo_visits'] = 1
        self.stat['_id'] = 'yap'+str(int(time.time()))
        self.stat['last_visit'] = int(time.time()/86400)


    def _increase_kolvo_visits(self):
        new_day = int(time.time()/86400)
        if self.stat.get('last_visit')==None:
            self.stat['last_visit'] = int(time.time()/86400)

        if int(self.stat.get('last_visit'))<new_day:
            self.stat['kolvo_visits'] = self.stat['kolvo_visits']+1
            self.stat['last_visit'] = new_day



    def check_auth(self,roles):

        if self.log_token=='None':
            return 'Error User:Not Login, Please Log IN'

        if self.s.validate(self.log_token)!=True:
            return 'Error User:Not Valid Login Token. Please, Log IN'

        
        self.session = self._get_json(self.log_token)
        if self.session['ip']!=self.stat['ip']:
            return 'Error User:Not valid IP. Please, log IN'
        
        
        if (int(time.time()) - int(self.session['ts']))>int(self.session['live_time']):
            return 'Error User:Session nor fresh, please Log IN'

        #check permission
        for each in self.session['roles']:
            if each in roles:
                return True



        return 'Error User:Not enough permission'


        
    def _gen_token(self,user_id,u_doc):
        self.session = {}

        self.session['_id'] = user_id
        self.session['name'] = u_doc['name']
        self.session['ts'] = int(time.time())
        self.session['roles'] = u_doc['roles']
        self.session['live_time'] = u_doc.get('token_live_time')
        self.session['ip'] = self.stat['ip']



        #create JSON from dict and compress
        j = json.dumps(self.session)
        j64 = base64.b64encode(j)

        #create signature
        j64_sign = self.s.sign(j64)    
    
        return j64_sign
    
    def _get_json(self,token):
        if self.s.validate(token)!=True:
            return 'Error User: not valid Log Token'
        
        jb64 = self.s.unsign(token)
        j = base64.b64decode(jb64)
        j = json.loads(j)
        return j


    def login(self,user_name,user_pass):
        #if user id in db and pass is equal md5 with secret

        #check user name and get user doc

        u_doc,u_id = self._db_check_in(user_name)

        if u_doc==False:
            return 'Error User:No such User'

        #check pass
        if self._md5_trans(user_pass)!=u_doc['pass']:
            return 'Error User:Wrong Pass'

        self.log_token = self._gen_token(u_id, u_doc)
        return True


    def registr(self,u_doc):
        user_id = 'yap'+str(int(time.time()))
        if self._db_check_in(u_doc['name'])!=[False,False]:
            return 'Error User:There is user with the name '+u_doc['name']


        u_doc['pass'] = self._md5_trans(u_doc['pass'])
        self._db_add(user_id,u_doc)

	
        return True



    def drop_log_token(self):
        self.log_token = 'None'
        return True

    def _md5_trans(self,rec):
        m = md5.new()
        m.update(rec)
        return m.hexdigest()

    ##########  DB  #################
    def _db_init(self):
	cl = MongoClient('localhost',27017)
	_db = cl['users']
	self.db = _db['users']


    def _db_check_in(self,u_name):

	u_doc = self.db.find_one({'name':u_name})

	if u_doc==None:
		return [False,False]

	return u_doc,u_doc['_id']


    
    def _db_add(self,u_id,user_d):

	user_d['_id'] = u_id
	self.db.insert_one(user_d)