Exemplo n.º 1
0
    def decorated_function(*args, **kwargs):
        s = URLSafeSerializer(APP.config['SECRET_KEY'],
                              salt=APP.config['FEED_SALT'])

        try:
            s.loads(request.args.get('token'))
        except:
            abort(401)

        return func(*args, **kwargs)
Exemplo n.º 2
0
def unencryptme(key, filename='oids'):
    s = URLSafeSerializer(key)
    csv = pd.read_csv(filename + "_encrypted.csv")
    market = s.loads(csv['strings'][0])
    pcc = s.loads(csv['strings'][1])
    epr = s.loads(csv['strings'][2])
    pwd = s.loads(csv['strings'][3])
    df = pd.DataFrame(list(zip(market, pcc, epr, pwd)),
                      columns=['market', 'pcc', 'epr', 'pwd'])
    return df
Exemplo n.º 3
0
def activate_user(activation_code):
    """
    Function that activate an user given an activation code
    It takes care of the actual creation on ADS Classic
    """
    # create an itsdangerous object to un sign the verification code and decrypt the password
    itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET)
    # decrypt the activation code
    try:
        login = itsd.loads(activation_code)
    except BadSignature:
        app.logger.error("Activation code not valid. Code used: %s" % activation_code)
        return False, "Activation Code not valid.", "error"
    # check local database
    loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username == login)  # @UndefinedVariable
    # get the user object
    user_rec = loc_db_user.first()
    if not user_rec:
        app.logger.error("User activation error: user not in db. Email used: %s" % login)
        return False, "Account not found", "error"
    if user_rec.active:
        app.logger.warn("User account already active. Email from activation code used: %s" % login)
        return False, "Account already active", "warn"
    # if everything is of it's time to proceed
    try:
        classic_user = create_classic_user(
            user_rec.username, itsd.loads(user_rec.password), user_rec.firstname, user_rec.lastname
        )
    except TypeError:
        app.logger.error("ADS Classic account creation error. Email from activation code used: %s" % login)
        return False, "Problems in the account creation. Please try later.", "error"
    if classic_user:
        update_params = {}
        if classic_user.get("cookie"):
            update_params.update(
                {
                    "cookie_id": classic_user["cookie"],
                    "active": True,
                    "password": "",
                    "remote_login_system": classic_user["request"]["man_url"],
                }
            )
            # actual update in the DB
            loc_db_user.set(**update_params).execute()
            return True, "Account activated", "success"
        else:
            app.logger.error(
                "User account activation failed on the classic user creation: user created but no cookie id in the response from classic. Email from activation code used: %s"
                % login
            )
            return False, "Problems in the creation of the classic user", "error"

    app.logger.error("User activation error. Classic user not created. Email from activation code used: %s" % login)
    return False, "Problems in the account creation. Please try later.", "error"
def main():
    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)

    action = sys.argv[1]
    secret_key = sys.argv[2]

    if action == "generate":
        filename = sys.argv[3]
        basename = filename.split(".")[-2]
        extension = filename.split(".")[-1]
        digest = hashlib.sha512(secret_key + basename).hexdigest()
        des = URLSafeSerializer(digest)
        credentials = {
            'filename': filename.encode("base64"),
            'ext': extension,
            'length': len(filename),
            'signature': digest
        }
        print des.dumps(credentials, salt="donttread")
        return

    signed_serial = sys.argv[3]

    result = URLSafeSerializer("").loads_unsafe(signed_serial)

    img = "snek.jpg"

    try:
        if result[1]:
            signature = result[1]['signature']
            extension = result[1]['ext']
            filename = result[1]['filename'].decode("base64")
            length = result[1]['length']
            if len(filename) == length and len(extension) == 3:
                basename = filename.split(".")[-2]
                digest = hashlib.sha512(secret_key +
                                        splitext(filename)[0]).hexdigest()
                if digest == signature:
                    des = URLSafeSerializer(digest)
                    des.loads(signed_serial, salt="donttread")
                    img = "%s.%s" % (basename, extension)
    except:
        pass

    proc = subprocess.Popen(["./read_file", img], stdout=subprocess.PIPE)
    imgo = proc.stdout.read().encode("base64").replace("\n", "")
    output = '<img src="data:image/png;base64,%s" alt="i am %s" />' % (imgo,
                                                                       img)
    print output
Exemplo n.º 5
0
    def decorated_function(*args, **kwargs):
        s = URLSafeSerializer(current_app.config['SECRET_KEY'],
                              salt=kwargs['facility'])

        if 'token' not in request.args:
            raise InvalidUsage('no token', status_code=401)

        try:
            s.loads(request.args.get('token'))

        except:
            raise InvalidUsage('bad token', status_code=401)

        return f(*args, **kwargs)
Exemplo n.º 6
0
def index(token):
    # Token verification
    with open('credentials.txt') as f:
        credentials = {k: v for k, v in map(str.split, f.readlines())}
        server_secret = credentials['SERVER_SECRET']

    serializer = URLSafeSerializer(server_secret, salt='flightstatus')
    try:
        email = serializer.loads(token)
    except BadData as e:
        return 'Invalid token provided'

    # Get flight details from db and then query the api
    flight_statuses = []
    updates = []
    for flight in get_tracked_flights(current_app, email):
        flight_details, curr_price = query_tracked_flight(flight)

        # If no results are returned by the api
        if curr_price == -1:
            continue

        flight_statuses.append(
            (flight_details, float(flight['prev_price']), float(curr_price)))

        if float(curr_price) != float(flight['prev_price']):
            updates.append((flight['id'], curr_price))

    print(flight_statuses)
    # Update prices in database
    update_stored_prices(current_app, updates)
    return render_template('flight_email.html',
                           flight_statuses=flight_statuses)
Exemplo n.º 7
0
def reset_password(token):
    """ sumary_line """
    try:
        urlsafeserializer = URLSafeSerializer(os.environ.get('SALT'))
        username = urlsafeserializer.loads(token, salt='forgot-password')
        if request.form['newpassword0'] == request.form['newpassword1']:
            if validate_password(request.form['newpassword0']):
                user = User(username)
                user_details = user.get_user_details()
                newhash = get_password_hash(request.form['newpassword1'])
                user.update_password_hash(newhash)
                send_reset_password_email(user_details['email'])
                message = 'Password updated'
                alert = 'success'
                return render_template('/login.html', message=message, alert=alert)
            message = 'Password should be at least 9 chars, [A-Za-z0-9@#$%^&+!=.]'
            alert = 'warning'
            return '<h3>'+ message + ' ' + alert +'</h3>'
        message = 'passwords do not match'
        alert = 'danger'
        return '<h3>'+ message + ' '+ alert +'</h3>'

    except BadSignature:
        message = 'This token has been tempered with create a new account'
        alert = 'danger'
        return redirect('/login', 302)
Exemplo n.º 8
0
 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'])
     task = Task.query.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)\
     task_run = TaskRun.query\
         .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')
Exemplo n.º 9
0
def current_user():
    user_id = session.get('id')
    if user_id:
        # g is unique object for each request
        current_user = getattr(g, 'current_user', None)
        if not current_user:
            current_user = User.find(user_id)
            if current_user:
                g.current_user = current_user
        return current_user
    else:
        # cookieからuser id取得を試みる
        signed_id = request.cookies.get('user_id')
        if signed_id:
            try:
                # 署名を確認する
                key = current_app.secret_key
                s = URLSafeSerializer(key, salt='remember_me')
                user_id = s.loads(signed_id)
                user = User.find(user_id)

                # 記憶トークンの確認
                if user and \
                   (remember_token := request.cookies.get('remember_token')) and \
                   (user.authenticated('remember', remember_token)):
                    log_in(user)
                    g.current_user = user
                    return user
            except BadSignature:
                # 改ざんされている
                return None

        return None
Exemplo n.º 10
0
class SendEmail(object):
    def __init__(self):
        self.serial = URLSafeSerializer(app.config["SECRET_KEY"])
        self.sg = SGMail
        self.template = os.path.dirname(
            __file__) + "/templates/email_template.html"

    def send_invite_email(self, sender, league, to_email):
        j2_env = jinja2.Environment(
            loader=jinja2.PackageLoader('MovieLeague', 'templates'))
        template = j2_env.get_template('email_template.html')
        from_email = Email("*****@*****.**")
        to_email = Email(to_email)
        subject = "Invite to join %s" % league
        html = template.render(sender=sender,
                               league=league,
                               token=self.token_dump(league))
        content = Content("text/html", html)
        mail = Mail(from_email, subject, to_email, content)
        response = self.sg.client.mail.send.post(request_body=mail.get())
        print(response.status_code)
        print(response.body)
        print(response.headers)

    def token_dump(self, data):
        return self.serial.dumps(data)

    def token_load(self, token):
        return self.serial.loads(token)
Exemplo n.º 11
0
def activate_device_sharing_token(account_id, token):
    """
    Activates device sharing token for account with passed id

    :param account_id: Id of account
    :type account_id: int
    :param token: Token created by device owner
    :type token: string
    :raises: ValueError if device does not exist
    """
    serializer = URLSafeSerializer(app.config['SECRET_KEY'],
                                   salt=app.config['SECURITY_PASSWORD_SALT'])
    token_data = serializer.loads(token)
    device_id = token_data['device_id']
    access_level_id = token_data['access_level_id']
    if (token_data.get('account_id') or account_id) != account_id:
        return False

    if not Device.exists(id=device_id):
        raise NotPresentError("Device does not exist!")

    device_association = DeviceAssociation(device_id, account_id,
                                           access_level_id)
    device_association.save()
    return True
Exemplo n.º 12
0
def weixin(signed_openid):
    aliases = g.user.get_type_alias()
    is_bound = ACCOUNT_REG_TYPE.WEIXIN_OPENID in aliases

    # decrypt the openid (sender) which provided by weixin
    serializer = URLSafeSerializer(current_app.secret_key)
    try:
        openid = serializer.loads(signed_openid)
    except BadSignature:
        return u'bad signature', 403

    if request.method == 'GET':
        return render_template('mine/alias/weixin.html', is_bound=is_bound)

    # overrides method with a hidden field
    if request.method == 'POST':
        if request.form['method'] == 'post':
            # bind to current account
            g.user.add_alias(openid, ACCOUNT_REG_TYPE.WEIXIN_OPENID)
            return redirect('/mine/plan')

        if request.form['method'] == 'delete':
            g.user.remove_alias(ACCOUNT_REG_TYPE.WEIXIN_OPENID)
            return redirect(request.path)

        abort(400)
Exemplo n.º 13
0
    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)
Exemplo n.º 14
0
def load_user(token):
    _query = get_query()
    #     return _query.filter_by(id = userid).first()
    key = current_app.config.get("SECRET_KEY", "It's a secret.")
    try:
        s = URLSafeSerializer(key)
        userid, username, password, life_time = s.loads(token)
    except BadData:
        # token had been modified!
        return None

    # 校验密码
    user = _query.get(userid)
    if user:
        # 能loads出id,name等信息,说明已经成功登录过,那么cache中就应该有token的缓存
        token_cache = simple_cache.get(token)
        if not token_cache:  # 此处找不到有2个原因:1.cache中因为超时失效(属于正常情况);2.cache机制出错(属于异常情况)。
            # the token is not found in cache.
            return None

        if str(password) != str(user.password):
            # the password in token is not matched!
            simple_cache.delete(token)
            return None
        else:
            simple_cache.set(token, 1, timeout=life_time)
    else:
        # the user is not found, the token is invalid!
        return None
    return user
Exemplo n.º 15
0
Arquivo: root.py Projeto: wiota/lime
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)
Exemplo n.º 16
0
Arquivo: views.py Projeto: v2up/queyue
def current_insti():
    insti_uurl = request.cookies.get('insti-uurl')
    if insti_uurl:
        s = URLSafeSerializer(current_app.config['SECRET_KEY'])
        uurl = s.loads(insti_uurl)
        return Institution.query.filter_by(uurl=uurl).first()
    return None
Exemplo n.º 17
0
def quiz_reply_page(quiz_id, secure_user_id):
    secret_key = app.config['SECRET_KEY']
    serializer = URLSafeSerializer(secret_key)

    try:
        user_id = serializer.loads(secure_user_id)
    except BadSignature:
        abort(404)

    user = User.query.get_or_404(user_id)
    quiz = Quiz.query.get_or_404(quiz_id)

    if request.method == 'POST':
        reply_text = request.form.get("reply_text")
        reply_mark = request.form.get("reply_mark")
        new_reply = Reply(user.id, reply_text, reply_mark)
        db.session.add(new_reply)
        db.session.commit()
        return 'success'

    reply_form = Reply_form()

    return flask.render_template('quiz_reply.html',
                                 user=user,
                                 quiz=quiz,
                                 secure_user_id=secure_user_id,
                                 reply_form=reply_form)
Exemplo n.º 18
0
def confirm_token(token):
    serializer = URLSafeSerializer(secret_key, salt=security_password_salt)
    try:
        email = serializer.loads(token)
    except:
        return False
    return email
Exemplo n.º 19
0
def itsDecode(data: str,
              time: int = 15,
              url_safe_key: str = DEFAULT_SAFE_KEY,
              time_safe_key: str = DEFAULT_SAFE_KEY) -> (bool, str):
    '''
    @description: its解密
    @param {data} data 加密数据 
    @param {int}  time 过期时间
    @param {str}  url_safe_key URL加密密钥
    @param {str}  time_safe_key Time加密密钥
    @return: True/False, Data
    '''
    result = None
    time = int(time)
    try:
        tSafe = TimestampSigner(time_safe_key)
        tUnsign = tSafe.unsign(data, time)
    except:
        return False, "授权过期"
    try:
        uSafe = URLSafeSerializer(url_safe_key)
        result = uSafe.loads(url_safe_key)
        return True, result
    except:
        return False, "解析失败"
Exemplo n.º 20
0
def load_token(token):
    # 通过loads()方法来解析浏览器发送过来的token,从而进行初步的验证
    key = current_app.config.get("SECRET_KEY", "The securet key by C~C!")

    try:
        s = URLSafeSerializer(key)
        id, name, password, browser_id, life_time = s.loads(token)
    except BadData:
        print("token had been modified!")
        return None

    # 判断浏览器信息是否改变
    bi = create_browser_id()
    if not constant_time_compare(str(bi), str(browser_id)):
        print("the user environment had changed, so token has been expired!")
        return None

    # 校验密码
    user = User.query.get(id)
    if user:
        # 能loads出id,name等信息,说明已经成功登录过,那么cache中就应该有token的缓存
        token_cache = simple_cache.get(token)
        if not token_cache:  # 此处找不到有2个原因:1.cache中因为超时失效(属于正常情况);2.cache机制出错(属于异常情况)。
            print("the token is not found in cache.")
            return None
        if str(password) != str(user.password):
            print("the password in token is not matched!")
            simple_cache.delete(token)
            return None
        else:
            simple_cache.set(token, 1, timeout=life_time)  # 刷新超时时长
    else:
        print('the user is not found, the token is invalid!')
        return None
    return user
Exemplo n.º 21
0
def load_bill_token(token):
    serializer = URLSafeSerializer(app.config['SECRET_KEY'])
    try:
        billid = serializer.loads(token, salt=app.config['SECURITY_BILL_SALT'])
    except:
        return False
    return billid
Exemplo n.º 22
0
def recover_password(token):
    s = URLSafeSerializer(app.config['SECRET_KEY'])
    try:
        token_data = s.loads(token)
    except BadSignature:
        flash('Failed to validate token.')
        return redirect(url_for('index'))
    if token_data['time'] + 600 < int(time.time()):
        flash('That link has expired')
        return redirect(url_for('forgot'))
    form = ChangePasswordForm()
    if form.validate_on_submit():
        try:
            user = User.get(User.email == token_data['email'])
        except User.DoesNotExist:
            flash('That user does not exist.')
            return redirect(url_for('index'))
        user.password = generate_password_hash(form.password.data)
        user.save()
        flash('Your password has been updated.')
        return redirect(url_for('login'))
    else:
        return render_template(
            'recover_password.html',
            form=form,
            token_data=token_data,
            token=token,
        )
Exemplo n.º 23
0
class Serializer:
    def __init__(self, app):
        self.serializer = URLSafeSerializer(app.config['SECRET_KEY'])
        self.salt = app.config['SECRET_SALT']

    def loads(self, token):
        return self.serializer.loads(token)

    def dumps(self, string):
        return self.serializer.dumps(string)

    def loads_salted(self, token):
        return self.serializer.loads(token, salt=self.salt)

    def dumps_salted(self, string):
        return self.serializer.dumps(string, salt=self.salt)
Exemplo n.º 24
0
def activate_user(activation_token):
    """
    Activate a particular user, based on activation token.
    This sets the is_active field to true in the db.
    :param activation_token: the token that user should have in email
    :return: 403 if any errors, else redirect to root  , and user is activated
    """
    serializer = URLSafeSerializer(app.config['SECRET_KEY'])

    try:
        email = serializer.loads(
                activation_token
        )
        user = User.query \
            .filter(User.email == email) \
            .one()

        user.is_active = True
        db.session.commit()

        # Mail(user.email,
        #      subject_data={'name': user.full_name},
        #      html_data={'name': user.full_name},
        #      text_data={'name': user.full_name},
        #      template_root=WELCOME_MAIL
        #      ).send()

        activate_user_to_mautic.delay(user.email)

        return redirect(f"{request.url_root}login")

    except (NoResultFound, BadSignature):
        return Error('Invalid Token', 403)()
Exemplo n.º 25
0
def confirm_status_token(token):
    serializer = URLSafeSerializer(Config.SECRET_KEY)
    try:
        status = serializer.loads(token, salt='status-confirm')
    except:
        return False
    return status
Exemplo n.º 26
0
 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')
Exemplo n.º 27
0
def decrypt_cookie(encrypted_content):
    s = URLSafeSerializer(current_app.secret_key, salt='cookie')
    try:
        content = s.loads(encrypted_content)
    except:
        content = '-1'
    return content
Exemplo n.º 28
0
def stoptoday(request):
    import sys
    from itsdangerous import URLSafeSerializer
    try:
        if 'id' in request.GET and request.GET['id'] != '':
            try:
                secretkey = oper_para.objects.get(name='sk')
                s = URLSafeSerializer(secretkey.content)
                vid = s.loads(request.GET['id'])
            except:
                return HttpResponseRedirect('/')
            
            #singleL = LineInformList.objects.get(id = request.GET['id'])
            singleL = LineInformList.objects.get(id = vid)
            print 'id:' + str(request.GET['id'])
            print 'TF:' + str(request.GET['TF'])
            if request.GET['TF'] == 'true':
                singleL.stoptoday = 'X'
            else:
                singleL.stoptoday = 'V'
            singleL.save()
            #return HttpResponse('您好,本通知本日已停用')
            return render_to_response('stoptoday.html')
    except ValueError:
        pass
Exemplo n.º 29
0
Arquivo: views.py Projeto: ccnmtl/rolf
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
Exemplo n.º 30
0
 def get_data(token):
     s = URLSafeSerializer(os.environ['SIGNER_SECRET'])
     try:
         return s.loads(token)
     except BadSignature:
         # Invalid token
         return None
Exemplo n.º 31
0
    def save_password(self, **kw):
        secret = tg.config.get('session.secret',
                               tg.config.get('beaker.session.secret'))
        serializer = URLSafeSerializer(secret)
        deserialized_data = serializer.loads(kw['data'])
        request_date = datetime.strptime(deserialized_data['request_date'],
                                         '%m/%d/%Y %H:%M')
        user = model.provider.query(
            app_model.User,
            filters=dict(
                email_address=deserialized_data['email_address']))[1][0]
        password_frag = user.password[0:4]
        if abs((datetime.now() - request_date).days) > 1:
            flash(_('Password reset request timed out'), 'error')
            return plug_redirect('resetpassword', '/')

        if password_frag != deserialized_data['password_frag']:
            flash(_('Invalid password reset request'), 'error')
            return plug_redirect('resetpassword', '/')

        user.password = kw['password']
        flash(_('Password changed successfully'))
        if 'redirect_to' in deserialized_data:
            redirect(deserialized_data['redirect_to'])
        else:
            return redirect('/')
class LinkGenerator:
    """
    Link to personalised form in email
    """
    DELIMITER = ';'

    def __init__(self, app):
        self._app = app
        self._serializer = URLSafeSerializer(app.config['SECRET_KEY'])

    def generate_payload(self, gala_id, club_id, swimmer_id):
        """
        Include identifiers in payload
        :param gala_id:
        :param club_id:
        :param swimmer_id:
        """
        payload = str(time()) + self.DELIMITER + str(gala_id) + self.DELIMITER + str(club_id) + \
                  self.DELIMITER + str(swimmer_id)
        return self._serializer.dumps(payload, salt=constants.LINK_GENERATOR_SALT)

    def load_payload(self, payload):
        """
        Retrieve identifiers from payload
        :param payload:
        """
        plain_payload = self._serializer.loads(payload, salt=constants.LINK_GENERATOR_SALT)
        try:
            plain_payload = plain_payload.split(self.DELIMITER)
            return {'gala_id': plain_payload[1], 'club_id': plain_payload[2], 'swimmer_id': plain_payload[3]}
        except:
            raise ValueError('Invalid payload format detected.')
Exemplo n.º 33
0
    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")
Exemplo n.º 34
0
def on_confirm_email(token):
    """Email confirmation endpoint.

    We try to confirm the specified signup and redirect to a webpage.
    """
    try:
        s = URLSafeSerializer(get_token_secret())
        signup_id = ObjectId(s.loads(token))
    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']
Exemplo n.º 35
0
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,
    })
Exemplo n.º 36
0
def read_token(token, salt, expiration=86400):
    serializer = URLSafeSerializer(app.config['SECRET_KEY'])
    obj = serializer.loads(
        token,
        salt=salt
    )
    return obj
Exemplo n.º 37
0
def resetVerifyCheck(key):
    url_serial = URLSafeSerializer(
        "XHhkMVx4OTgzXFxceDhmZilceDk2Ilx4MTZceDhkXHhhYlx4ZGFceDlkXHhiYUNHXHhlM1x4YTRceDFiK0RceGNhfg=="
    )
    timed_serial = TimedSerializer(
        "XHhkMVx4OTgzXFxceDhmZilceDk2Ilx4MTZceDhkXHhhYlx4ZGFceDlkXHhiYUNHXHhlM1x4YTRceDFiK0RceGNhfg=="
    )
    status = None
    try:
        key = timed_serial.loads(key, max_age=300)
        key = url_serial.loads(key)

        username = str(sanitize(key[0]))
        password = sha512_crypt.encrypt(sanitize(key[1]))
    except:
        status = "Oops, The Link Has Expired..!!"
        return status
    cursor, dbconn = dbConnection()
    query = "UPDATE users SET password = %s WHERE username = %s"
    try:
        cursor.execute(query, (password, username))
        dbconn.commit()
        status = "Password Updated Successfully..!!"
    except:
        dbconn.rollback()
        status = "Oops, Something Went Wrong Please Try Again..!!"
    cursor.close()
    dbconn.close()
    return status
Exemplo n.º 38
0
def shifts(payload):
    serializer = URLSafeSerializer(APP.secret_key)
    available_shifts = SPREADSHEET.get_available_shifts()
    employees = SPREADSHEET.get_employees()
    if request.method == 'GET':
        try:
            employee_num = serializer.loads(payload)
        except BadSignature:
            abort(404)
    else:
        employee_num = int(payload)
        employee_row = employees.iloc[employee_num]
        if employee_row['Current'] == 'TRUE':
            row = int(request.form.get('row'))
            employee_name = employee_row['Name']
            assigned = int(employee_row['Assigned']) + 1

            if employee_row['GiveTo'] != '':
                employee_name = '{} ({})'.format(employee_row['GiveTo'],
                                                 employee_name)

            SPREADSHEET.update_available_shifts_cell(row, 4, employee_name)
            SPREADSHEET.update_employees_cell(employee_num, 3, assigned)
            SPREADSHEET.update_employees_cell(employee_num, 5, False)
            SPREADSHEET.update_employees_cell(employee_num, 6, '')
            available_shifts.iloc[row]['OnCall'] = employee_name
            flash('Thank you, {}!'.format(employee_name))

        else:
            flash('Please wait until it is your turn.')

    return render_template('shifts.html',
                           shifts=available_shifts,
                           employeeNum=employee_num,
                           employees=employees)
Exemplo n.º 39
0
def confirm_token(token, secret_key):
    serializer = URLSafeSerializer(secret_key)
    try:
        email = serializer.loads(token)
    except:
        return False
    return email
def main():
    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)

    action = sys.argv[1]
    secret_key = sys.argv[2]

    if action == "generate":
        filename = sys.argv[3]
        basename = filename.split(".")[-2]
        extension = filename.split(".")[-1]
        digest = hashlib.sha512(secret_key + basename).hexdigest()
        des = URLSafeSerializer(digest)
        credentials = {'filename': filename.encode("base64"),
                       'ext': extension,
                       'length': len(filename),
                       'signature': digest}
        print des.dumps(credentials, salt="donttread")
        return

    signed_serial = sys.argv[3]

    result = URLSafeSerializer("").loads_unsafe(signed_serial)

    img = "snek.jpg"

    try:
        if result[1]:
            signature = result[1]['signature']
            extension = result[1]['ext']
            filename  = result[1]['filename'].decode("base64")
            length    = result[1]['length']
            if len(filename) == length and len(extension) == 3:
                basename = filename.split(".")[-2]
                digest = hashlib.sha512(secret_key + splitext(filename)[0]).hexdigest()
                if digest == signature:
                    des = URLSafeSerializer(digest)
                    des.loads(signed_serial, salt="donttread")
                    img = "%s.%s" % (basename, extension)
    except:
        pass

    proc = subprocess.Popen(["./read_file", img], stdout=subprocess.PIPE)
    imgo = proc.stdout.read().encode("base64").replace("\n", "")
    output = '<img src="data:image/png;base64,%s" alt="i am %s" />' % (imgo, img)
    print output
Exemplo n.º 41
0
 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
Exemplo n.º 42
0
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
Exemplo n.º 43
0
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)
Exemplo n.º 44
0
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("/")
Exemplo n.º 45
0
def signed_deserialize(token):
    """De-serialize signed data."""
    c = get_config()
    s = URLSafeSerializer(c.secrets.signing_key)
    try:
        result = s.loads(token)
        return result
    except:
        return None
Exemplo n.º 46
0
 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'])
Exemplo n.º 47
0
def confirm_account(secretstring):
    s = URLSafeSerializer("serliaizer_code")
    uname, uemail = s.loads(secretstring)
    user = Users.query.filter_by(username=uname).first()
    user.activate = True
    db.session.add(user)
    db.session.commit()
    flash(u"Your account was confirmed succsessfully!!!")
    return redirect(url_for("login"))
Exemplo n.º 48
0
def reset_password(token):
    s = URLSafeSerializer("hacker-bees")
    user_id = s.loads(token)
    user = User.query.get(int(user_id))
    expired = datetime.today() - user.reset_time
    if expired.days > 1:
        flash("Password reset link has expired")
        return redirect(url_for("login"))
    return render_template("reset.html", token=token)
Exemplo n.º 49
0
def buy_worker(defaults=None, template="ssl/buy"):
    if defaults is None:
        defaults = {}
    country = request.headers.get("X-Appengine-Country", "").upper()
    region = request.headers.get("X-AppEngine-Region", "").upper()

    if "country" not in defaults:
        # When App Engine is running locally or cannot determine country it
        # returns ZZ as the country code.
        if country == "ZZ":
            country = "GB"

        if country is not None:
            defaults["country"] = country
        else:
            defaults["country"] = "US"

    if "state" not in defaults:
        if country in REGIONS and region in REGIONS[country]:
            defaults["state"] = REGIONS[country][region]

    defaults["coupon_code"] = coupon = request.args.get("coupon")
    defaults["price"] = 50

    promotion = request.args.get("promotion")

    if promotion:
        defaults["promotion"] = promotion
        if promotion == "academic":
            defaults["price"] = 25
            defaults["coupon_message"] = "Academic discount applied"

    if coupon:
        s = URLSafeSerializer(current_app.config.get("SECRET_KEY"), salt="SSL_COUPON_USD")
        # Load the coupon
        try:
            coupon = s.loads(coupon)
            # coupon should contain price, domain
            if "price" in coupon:
                defaults["price"] = int(coupon["price"])

            if "domain" in coupon and coupon["domain"] != "":
                defaults["domain"] = coupon["domain"]
                defaults["domain_locked"] = True

            logging.info(coupon)

            defaults["coupon_message"] = "Coupon applied (price: $%d)" % defaults["price"]
        except BadPayload:
            defaults["coupon_code"] = None
            defaults["error"] = "The coupon is malformed"
        except BadSignature:
            defaults["coupon_code"] = None
            defaults["error"] = "This coupon is no longer valid"

    return render_template(template, countries=COUNTRIES_BY_NAME, **defaults)
Exemplo n.º 50
0
class Encryption:
    def init_app(self, app):
        self.serializer = URLSafeSerializer(app.config.get('SECRET_KEY'))
        self.salt = app.config.get('DANGEROUS_SALT')

    def encrypt(self, thing_to_encrypt):
        return self.serializer.dumps(thing_to_encrypt, salt=self.salt)

    def decrypt(self, thing_to_decrypt):
        return self.serializer.loads(thing_to_decrypt, salt=self.salt)
Exemplo n.º 51
0
 def verify_client_token(token):
     """
     verify client token
     but need client_key
     """
     s = Serializer(
         current_app.config["SECRET_KEY"]
     )
     data = s.loads(token)
     return Client.query.get_or_404(data['client_id'])
Exemplo n.º 52
0
 def verify_auth_token(token):
     s = Serializer(app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except SignatureExpired:
         return None
     except BadSignature:
         return None
     user = User.query.get(data['id'])
     return user
Exemplo n.º 53
0
def unsing_string(signed_string):
    """
    Récupérer le mail depuis une string signée

    :param signed_string: la string signée
    :returns: le mail caché dedans
    """
    signer_kwargs = {"digest_method": sha256}
    signer = URLSafeSerializer(app.secret_key, signer_kwargs=signer_kwargs)
    return signer.loads(signed_string)
def login_get_next_url():
  if 'next' not in request.args:
    return None
  try:
    serializer = URLSafeSerializer(config.secret)
    goto = serializer.loads(request.args['next'])
    goto = request.url_root + goto
    return goto
  except:
    return None
Exemplo n.º 55
0
 def wrapped(*args, **kwargs):
     s = Serializer(current_app.config['SECRET_KEY'])
     token = request.headers.get('eD-Token', '')
     if not token:
         return bad_request('Missing token')
     try:
         data = s.loads(token)
     except:
         return bad_request('Token incorrect')
     g.session_data = data
     return f(*args, **kwargs)
Exemplo n.º 56
0
 def ping(self, incoming_request):
     serializer = URLSafeSerializer(self.config['SECRET_KEY'])
     req = serializer.loads(incoming_request['payload'])
     self._bot.conn.client.register_plugin('xep_0033')
     message = self._bot.conn.client.Message()
     message['to'] = 'multicast.j4lp.com'
     message['body'] = req['body']
     for user in req['users']:
         message['addresses'].addAddress(atype='bcc', jid=user)
     message.send()
     return
Exemplo n.º 57
0
Arquivo: root.py Projeto: wiota/lime
def trowel_login(token=None):
    s = URLSafeSerializer(app.config['SECRET_KEY'])
    try:
        payload = s.loads(token)
    except BadSignature:
        abort(404)
    current_time = time.time()
    if current_time - 10 <= payload["stamp"] <= current_time + 10:
        login_user(User.objects.get(id=payload["id"]))
        return redirect(url_for("root.index"))
    abort(404)
Exemplo n.º 58
0
def confirmed_token(token, expiration = 36000):
    serialzer = URLSafeSerializer(SECRET_KEY)
    try:
        email = serialzer.loads(
            token,
            salt = SECURITY_PASSWORD_SALT,
            max_age = expiration
        )
    except:
        return False
    return email
Exemplo n.º 59
0
def login_get_next_url():
  if 'next' not in request.args:
    return None, None
  try:
    serializer = URLSafeSerializer(current_app.secret_key)
    goto_encrypted = request.args['next']
    goto = serializer.loads(goto_encrypted)
    goto = request.url_root + goto
    return goto, goto_encrypted
  except:
    return None, None
Exemplo n.º 60
0
def is_activation_token_valid(token):
    s = URLSafeSerializer(current_app.config["SECRET_KEY"])
    try:
        info = s.loads(token)
        expired_at = info[2]
        if expired_at < (datetime.now() - datetime(1970,1,1)).total_seconds():
            return False
        else:
            return True
    except:
        return False