Example #1
0
    def get_members(bank_id=None) -> BankMembersPage:
        """
        Get a page of bank members. Use the "continuation_token" from this
        response to get subsequent pages.
        """
        continuation_token = (
            bottle.request.query.continuation_token
            and json.loads(bottle.request.query.continuation_token) or None)

        try:
            content_type = get_content_type_for_name(
                bottle.request.query.content_type)

        except:
            bottle.abort(
                400, "content_type must be provided as a query parameter.")

        db_response = table_manager.get_all_bank_members_page(
            bank_id=bank_id,
            content_type=content_type,
            exclusive_start_key=continuation_token,
        )

        continuation_token = None
        if db_response.last_evaluated_key:
            continuation_token = uriencode(
                json.dumps(db_response.last_evaluated_key))

        return BankMembersPage(
            bank_members=with_preview_urls(db_response.items),
            continuation_token=continuation_token,
        )
Example #2
0
def log_out():
    browser.get(epic_logout_url + "?redirectUrl=" + uriencode(epic_store_url))
    wait_redirect_count = 0
    has_warned_logout = False
    while not re.search(epic_store_url, browser.current_url):
        if (wait_redirect_count >= 5) & (has_warned_logout == False):
            print("Still waiting to be redirected to store page after logout")
            has_warned_logout = True
        time.sleep(1)
        wait_redirect_count += 1
    print("Successfully logged out\n")
Example #3
0
def auth_uri():
    dest_uri = redirect_uri()
    state = set_state()
    nonce = set_nonce()
    session['state.path'] = request.path
    session['state.args'] = pickle.dumps(request.args)
    return current_app.config['AUTH_PROVIDER'] + '?' + \
       'client_id=' + current_app.config['CLIENT_ID'] + \
       '&response_type=code' + \
       '&scope=openid%20email%20profile' + \
       '&redirect_uri='+uriencode(dest_uri) + \
       '&state='+state + \
       '&nonce='+nonce
Example #4
0
def log_into_account(email, password, two_fa_key=None):
    # Loading login page and waiting until ready
    print("Logging into account " + email)
    browser.get(epic_login_url + "?redirectUrl=" + uriencode(epic_store_url))
    if not wait_until_xpath_presence_located("//*[@id='email']"):
        raise TypeError("Unable to find email input field")

    # Logging in into the account
    browser.find_element_by_id('email').send_keys(email)
    browser.find_element_by_id('password').send_keys(password)
    if not wait_until_xpath_clickable_then_click("//*[@id='login']"):
        raise TypeError("Unable to find login button")
    # 2FA
    if (two_fa_key != None):
        wait_located_count = 0
        has_warned_captcha = False
        while not wait_until_xpath_presence_located("//*[@id='code']", 1):
            if (wait_located_count >= 3) & (has_warned_captcha == False):
                print(
                    "Waiting - Cannot find 2FA input field - Possible captcha requiring completion"
                )
                has_warned_captcha = True
            wait_located_count += 1
        browser.find_element_by_id('code').send_keys(
            Keys.HOME)  # Make sure to be at beginning of field
        browser.find_element_by_id('code').send_keys(
            pyotp.TOTP(two_fa_key).now())  # 2FA login code
        if not wait_until_xpath_clickable_then_click("//*[@id='continue']"):
            raise TypeError("Unable to find 2FA continue button")

    # Waiting until redirected to store - captcha detection workaround
    wait_redirect_count = 0
    has_warned_captcha = False
    print("Waiting to be automatically redirected to store page")
    while not re.search(epic_store_url, browser.current_url):
        if (wait_redirect_count >= 5) & (has_warned_captcha == False):
            print("Still waiting - Possible captcha requiring completion")
            has_warned_captcha = True
        time.sleep(1)
        wait_redirect_count += 1
    print("Successfully logged in " + email)
    browser.get(
        epic_store_url)  # So it automatically waits until page is loaded
    wait_until_xpath_visible("//*[@id='siteNav']")
    time.sleep(1)
Example #5
0
def authenticated():
    logger = logging.getLogger(__name__)
    if request.args.get('state', '') != session.get('state'):
        logger.warning(
            'Unauthroized, session "{session_state}" did not match state "{state}".'
            .format(session_state=session.get('state'),
                    state=request.args.get('state', '')))
        abort(401)
    session.pop('state', None)

    info = exchange_code(request.args.get('code', ''))

    token = info['id_token']

    if logger.isEnabledFor(logging.DEBUG):
        logger.debug('Code exchanged for token {token}'.format(token=token))

    principal, profile = get_principal(token)
    if 'WHITELIST' in current_app.config:
        if principal not in current_app.config['WHITELIST']:
            logger.warning('Unauthorized, {user} not in whitelist.'.format(
                user=principal))
            abort(401)

    expiry = datetime.now() + timedelta(seconds=info['expires_in'])
    if logger.isEnabledFor(logging.DEBUG):
        logger.debug('Token {token} expires in {expiry}'.format(
            token=token, expiry=expiry.isoformat()))
    session['token'] = token
    session['expiry'] = expiry
    for property in profile_properties:
        session[property] = profile.get(property, '')
    path = session.pop('state.path', '/')
    prefix = current_app.config[
        'PREFIX'] if 'PREFIX' in current_app.config else ''
    if len(prefix) > 0 and prefix[-1] == '/':
        prefix = prefix[0:-1]
    args = (lambda x: pickle.loads(x)
            if x is not None else {})(session.pop('state.args', None))
    for index, name in enumerate(args):
        path = path + ('?' if index == 0 else '&') + name + '=' + uriencode(
            args[name])
    response = redirect(prefix + path)
    return response
Example #6
0
    async def on_reaction(self, data):
        emoji = uriencode(data["emoji"]["name"])
        if emoji == "%E2%97%80%EF%B8%8F":
            self.active_page -= 1
            await self.update()
            await self.remove_reaction("%E2%97%80%EF%B8%8F")
        elif emoji == "%E2%9D%A4%EF%B8%8F":
            if (int(self.ctx.message.member["permissions"])
                    & 0x20000000) != 0x20000000:
                await self.ctx.send(
                    f"<@{self.author}> Uh oh, you need manage webhooks permissions to add news!"
                )
                return
            try:
                page = self.results[self.active_page]
            except IndexError:
                await self.ctx.send(
                    f"<@{self.author}> Uh oh, theres no channel selected here."
                    " Select a channel and press the heart to add it!")
                return
            await self.expire()

            r = Route("POST",
                      "/channels/{news_channel_id}/followers",
                      news_channel_id=page["id"])
            try:
                await self.ctx.client.http.request(
                    r,
                    json={"webhook_channel_id": self.ctx.message.channel_id})
            except Forbidden:
                await self.ctx.send(
                    "I need manage webhooks permissions to work!")
        elif emoji == "%E2%9E%A1%EF%B8%8F":
            self.active_page += 1
            await self.update()
            await self.remove_reaction("%E2%9E%A1%EF%B8%8F")
Example #7
0
 def rename_entry(self,old_location, new_location, entry):
     entry.find("location").text = "file://" + uriencode(new_location)