Exemplo n.º 1
1
def test_override_token_post():
    responses.add(responses.POST, "https://slack.com/api/chat.postMessage")

    app = Flask(__name__)
    slack_bp = make_slack_blueprint(
        client_id="foo", client_secret="bar",
        backend=MemoryBackend({"access_token": "abcde"}),
    )
    app.register_blueprint(slack_bp, url_prefix="/login")

    with app.test_request_context("/"):
        app.preprocess_request()
        resp = slack.post("chat.postMessage", data={
            "token": "xyz",
            "channel": "#general",
            "text": "ping",
            "icon_emoji": ":robot_face:",
        })
    request_data = url_decode(resp.request.body)
    assert request_data["token"] == "xyz"
    assert request_data["channel"] == "#general"
    assert request_data["text"] == "ping"
    assert request_data["icon_emoji"] == ":robot_face:"
    # should not be present
    url = URLObject(resp.request.url)
    assert "token" not in url.query_dict
def qyAppSubscribe():
    sReqMsgSig = request.args.get('msg_signature')
    sReqTimeStamp = request.args.get('timestamp')
    sReqNonce = request.args.get('nonce')

    if request.method == 'GET':
        # wxcpt = WXBizMsgCrypt(TOKEN_QY, AESKEY_QY, APP_ID_QY)
        ret, sEchoStr = wxcpt.VerifyURL(
            url_decode(request.query_string)['msg_signature'],
            url_decode(request.query_string)['timestamp'],
            url_decode(request.query_string)['nonce'],
            url_decode(request.query_string)['echostr'])
        # print ret

        return sEchoStr

    # app.logger.info(request.data)
    # app.logger.info(sReqMsgSig)
    # app.logger.info(sReqTimeStamp)
    # app.logger.info(sReqNonce)

    ret, decodeXML = getDecryptMsg(request.data, sReqMsgSig, sReqTimeStamp,
                                   sReqNonce)
    # app.logger.info(str(ret))
    # app.logger.info(decodeXML)
    if decodeXML:
        userid = decodeXML.find("FromUserName").text
        my = decodeXML.find("ToUserName").text
        app.logger.info(userid)
        msgType = decodeXML.find("MsgType").text
        if msgType == 'event':
            event = decodeXML.find("Event").text
            if event == 'subscribe':
                userid = decodeXML.find("FromUserName").text
                detail = getPsnDetail(userid)
                if detail.has_key('weixinid'):
                    psn = wx_session.query(Document_psn).filter(
                        Document_psn.qywxid == userid).first()
                    psn.weixinid = detail['weixinid']
                    wx_session.merge(psn)
                    wx_session.commit()

                retXML = ''
                retXML += '<xml>'
                retXML += '<ToUserName><![CDATA[' + userid + ']]></ToUserName>'
                retXML += '<FromUserName><![CDATA[' + my + ']]></FromUserName>'
                retXML += '<CreateTime>' + str(int(
                    sysTime.time() * 1000)) + '</CreateTime>'
                retXML += '<MsgType><![CDATA[text]]></MsgType>'
                retXML += '<Content><![CDATA[欢迎关注国贸集团企业号,获取公司内部网信息,增进交流,提升工作效率。]]></Content>'
                retXML += '</xml>'
                retXML = retXML.replace('&lt;', '<').replace('&gt;', '>')

                ret, sEncryptMsg = wxcpt.EncryptMsg(retXML, sReqNonce,
                                                    sReqTimeStamp)

                return sEncryptMsg

    return ''
Exemplo n.º 3
0
    def test_redirect_to_records(self):

        self.company_A = self.env['res.company'].create({
            'name': 'Company A',
            'user_ids': [(4, self.ref('base.user_admin'))],
        })

        self.company_B = self.env['res.company'].create({
            'name': 'Company B',
        })

        self.multi_company_record = self.env['mail.test.multi.company'].create({
            'name': 'Multi Company Record',
            'company_id': self.company_A.id,
        })

        # Test Case 0
        # Not logged, redirect to web/login
        response = self.url_open('/mail/view?model=%s&res_id=%s' % (
            self.multi_company_record._name,
            self.multi_company_record.id), timeout=15)

        path = url_parse(response.url).path
        self.assertEqual(path, '/web/login')

        self.authenticate('admin', 'admin')

        # Test Case 1
        # Logged into company 1, try accessing record in company A
        # _redirect_to_record should add company A in allowed_company_ids
        response = self.url_open('/mail/view?model=%s&res_id=%s' % (
            self.multi_company_record._name,
            self.multi_company_record.id), timeout=15)

        self.assertEqual(response.status_code, 200)

        fragment = url_parse(response.url).fragment
        cids = url_decode(fragment)['cids']

        self.assertEqual(cids, '1,%s' % (self.company_A.id))

        # Test Case 2
        # Logged into company 1, try accessing record in company B
        # _redirect_to_record should redirect to messaging as the user
        # doesn't have any access for this company
        self.multi_company_record.company_id = self.company_B

        response = self.url_open('/mail/view?model=%s&res_id=%s' % (
            self.multi_company_record._name,
            self.multi_company_record.id), timeout=15)

        self.assertEqual(response.status_code, 200)

        fragment = url_parse(response.url).fragment
        action = url_decode(fragment)['action']

        self.assertEqual(action, 'mail.action_discuss')
def qyApp3receive():
    sReqMsgSig = request.args.get('msg_signature')
    sReqTimeStamp = request.args.get('timestamp')
    sReqNonce = request.args.get('nonce')

    if request.method == 'GET':
        # wxcpt = WXBizMsgCrypt(TOKEN_QY, AESKEY_QY, APP_ID_QY)
        ret, sEchoStr = wxcpt.VerifyURL(url_decode(request.query_string)['msg_signature'],
                                        url_decode(request.query_string)['timestamp'],
                                        url_decode(request.query_string)['nonce'],
                                        url_decode(request.query_string)['echostr'])
        # print ret

        return sEchoStr

    retXML = ''

    ret, decodeXML = getDecryptMsg(request.data, sReqMsgSig, sReqTimeStamp, sReqNonce)
    if decodeXML:
        userid = decodeXML.find("FromUserName").text
        my = decodeXML.find("ToUserName").text

        retXML += '<xml>'
        retXML += '<ToUserName><![CDATA[' + userid + ']]></ToUserName>'
        retXML += '<FromUserName><![CDATA[' + my + ']]></FromUserName>'
        retXML += '<CreateTime>' + str(int(sysTime.time() * 1000)) + '</CreateTime>'
        retXML += '<MsgType><![CDATA[text]]></MsgType>'
        retXML += '<Content><![CDATA[%s]]></Content>'
        retXML += '</xml>'
        retXML = retXML.replace('&lt;', '<').replace('&gt;', '>')

        msgType = decodeXML.find("MsgType").text
        if msgType == 'text':
            content = decodeXML.find("Content").text
            if content != '':
                userid = decodeXML.find("FromUserName").text
                app.logger.info(content)
                ret = getPsnPhoneVOs(u'oGWhot6q83jPLENglsitEv1xjYCw', content)
                if ret['code'] != 0:
                    retXML = retXML % ret['msg'].encode('utf-8')
                else:
                    rsMsg = ''
                    for psn in ret['psn']:
                        rsMsg += '【' + str(psn['psnname']) + '】\n'
                        rsMsg += ((psn['email'] == 'null' or psn['email'] == '') and '' or (
                            u'\U00002709'.encode('utf-8') + str(psn['email']) + '\n'))
                        if (psn['yglb'] != "0001V410000000001OPY"):
                            rsMsg += ((psn['officephone'] == 'null' or psn['officephone'] == '') and '' or (
                                u'\U0000260E'.encode('utf-8') + str(psn['officephone']) + '\n'))
                            rsMsg += ((psn['mobile'] == 'null' or psn['mobile'] == '') and '' or (
                                u'\U0001F4F1'.encode('utf-8') + str(psn['mobile']) + '\n'))

                    retXML = retXML % rsMsg

    ret, sEncryptMsg = wxcpt.EncryptMsg(retXML, sReqNonce, sReqTimeStamp)

    return sEncryptMsg
def qyAppSubscribe():
    sReqMsgSig = request.args.get('msg_signature')
    sReqTimeStamp = request.args.get('timestamp')
    sReqNonce = request.args.get('nonce')

    if request.method == 'GET':
        # wxcpt = WXBizMsgCrypt(TOKEN_QY, AESKEY_QY, APP_ID_QY)
        ret, sEchoStr = wxcpt.VerifyURL(url_decode(request.query_string)['msg_signature'],
                                        url_decode(request.query_string)['timestamp'],
                                        url_decode(request.query_string)['nonce'],
                                        url_decode(request.query_string)['echostr'])
        # print ret

        return sEchoStr

    # app.logger.info(request.data)
    # app.logger.info(sReqMsgSig)
    # app.logger.info(sReqTimeStamp)
    # app.logger.info(sReqNonce)

    ret, decodeXML = getDecryptMsg(request.data, sReqMsgSig, sReqTimeStamp, sReqNonce)
    # app.logger.info(str(ret))
    # app.logger.info(decodeXML)
    if decodeXML:
        userid = decodeXML.find("FromUserName").text
        my = decodeXML.find("ToUserName").text
        app.logger.info(userid)
        msgType = decodeXML.find("MsgType").text
        if msgType == 'event':
            event = decodeXML.find("Event").text
            if event == 'subscribe':
                userid = decodeXML.find("FromUserName").text
                detail = getPsnDetail(userid)
                if detail.has_key('weixinid'):
                    psn = wx_session.query(Document_psn).filter(Document_psn.qywxid == userid).first()
                    psn.weixinid = detail['weixinid']
                    wx_session.merge(psn)
                    wx_session.commit()

                retXML = ''
                retXML += '<xml>'
                retXML += '<ToUserName><![CDATA[' + userid + ']]></ToUserName>'
                retXML += '<FromUserName><![CDATA[' + my + ']]></FromUserName>'
                retXML += '<CreateTime>' + str(int(sysTime.time() * 1000)) + '</CreateTime>'
                retXML += '<MsgType><![CDATA[text]]></MsgType>'
                retXML += '<Content><![CDATA[欢迎关注国贸集团企业号,获取公司内部网信息,增进交流,提升工作效率。]]></Content>'
                retXML += '</xml>'
                retXML = retXML.replace('&lt;', '<').replace('&gt;', '>')

                ret, sEncryptMsg = wxcpt.EncryptMsg(retXML, sReqNonce, sReqTimeStamp)

                return sEncryptMsg

    return ''
Exemplo n.º 6
0
    def test_url_decoding(self):
        x = urls.url_decode("foo=42&bar=23&uni=H%C3%A4nsel")
        assert x["foo"] == "42"
        assert x["bar"] == "23"
        assert x["uni"] == u"Hänsel"

        x = urls.url_decode("foo=42;bar=23;uni=H%C3%A4nsel", separator=";")
        assert x["foo"] == "42"
        assert x["bar"] == "23"
        assert x["uni"] == u"Hänsel"

        x = urls.url_decode("%C3%9Ch=H%C3%A4nsel", decode_keys=True)
        assert x[u"Üh"] == u"Hänsel"
Exemplo n.º 7
0
    def test_url_decoding(self):
        x = urls.url_decode(b'foo=42&bar=23&uni=H%C3%A4nsel')
        self.assert_strict_equal(x['foo'], u'42')
        self.assert_strict_equal(x['bar'], u'23')
        self.assert_strict_equal(x['uni'], u'Hänsel')

        x = urls.url_decode(b'foo=42;bar=23;uni=H%C3%A4nsel', separator=b';')
        self.assert_strict_equal(x['foo'], u'42')
        self.assert_strict_equal(x['bar'], u'23')
        self.assert_strict_equal(x['uni'], u'Hänsel')

        x = urls.url_decode(b'%C3%9Ch=H%C3%A4nsel', decode_keys=True)
        self.assert_strict_equal(x[u'Üh'], u'Hänsel')
Exemplo n.º 8
0
def test_url_decoding():
    x = urls.url_decode(b"foo=42&bar=23&uni=H%C3%A4nsel")
    strict_eq(x["foo"], u"42")
    strict_eq(x["bar"], u"23")
    strict_eq(x["uni"], u"Hänsel")

    x = urls.url_decode(b"foo=42;bar=23;uni=H%C3%A4nsel", separator=b";")
    strict_eq(x["foo"], u"42")
    strict_eq(x["bar"], u"23")
    strict_eq(x["uni"], u"Hänsel")

    x = urls.url_decode(b"%C3%9Ch=H%C3%A4nsel", decode_keys=True)
    strict_eq(x[u"Üh"], u"Hänsel")
Exemplo n.º 9
0
    def test_url_decoding(self):
        x = urls.url_decode('foo=42&bar=23&uni=H%C3%A4nsel')
        assert x['foo'] == '42'
        assert x['bar'] == '23'
        assert x['uni'] == u'Hänsel'

        x = urls.url_decode('foo=42;bar=23;uni=H%C3%A4nsel', separator=';')
        assert x['foo'] == '42'
        assert x['bar'] == '23'
        assert x['uni'] == u'Hänsel'

        x = urls.url_decode('%C3%9Ch=H%C3%A4nsel', decode_keys=True)
        assert x[u'Üh'] == u'Hänsel'
Exemplo n.º 10
0
    def test_url_decoding(self):
        x = urls.url_decode('foo=42&bar=23&uni=H%C3%A4nsel')
        assert x['foo'] == '42'
        assert x['bar'] == '23'
        assert x['uni'] == u'Hänsel'

        x = urls.url_decode('foo=42;bar=23;uni=H%C3%A4nsel', separator=';')
        assert x['foo'] == '42'
        assert x['bar'] == '23'
        assert x['uni'] == u'Hänsel'

        x = urls.url_decode('%C3%9Ch=H%C3%A4nsel', decode_keys=True)
        assert x[u'Üh'] == u'Hänsel'
Exemplo n.º 11
0
def _validate(arg_name, validator, required_args):
    if isinstance(validator, ArgumentValidator):
        validator.application = current_app
        try:
            if not len(request.form) and not len(
                    request.args) and request.data:
                from werkzeug.urls import url_decode

                args = url_decode(request.data)
                if arg_name not in args:
                    raise KeyError(arg_name)
                value = args[arg_name]
            else:
                value = request.form[
                    arg_name] if arg_name in request.form else request.args[
                        arg_name]
            if not validator.validate(value):
                raise errors.InvalidParameterValue(arg_name)
        except KeyError:
            if validator.required:
                raise errors.MissingRequiredParameter(arg_name)
            value = validator.default_value
        required_args[arg_name] = validator.get_value(
            value) if value is not None else None
    else:
        raise ValueError(
            "Invalid parameter in argument validator description: %s" %
            str(validator))
Exemplo n.º 12
0
def getParams():

    params = url_decode(
        getattr(flask.request, 'environ').get('QUERY_STRING', ''))
    reg = re.compile('^[a-z0-9_\.]+$')

    current = temp = {}
    for param, value in sorted(params.iteritems()):

        nest = re.split("([\[\]]+)", param)
        if len(nest) > 1:
            nested = []
            for key in nest:
                if reg.match(key):
                    nested.append(key)

            current = temp

            for item in nested:
                if item is nested[-1]:
                    current[item] = toUnicode(unquote(value))
                else:
                    try:
                        current[item]
                    except:
                        current[item] = {}

                    current = current[item]
        else:
            temp[param] = toUnicode(unquote(value))

    return dictToList(temp)
Exemplo n.º 13
0
def receive_verifier(oauth_token,
                     oauth_verifier,
                     consumer_key=None,
                     consumer_secret=None):
    temp_token = OAuthToken.query.get(oauth_token)
    if not temp_token:
        raise Exception("OAuth token has expired")
    twitter = Twitter(auth=OAuth(temp_token.token, temp_token.token_secret,
                                 consumer_key, consumer_secret),
                      format='',
                      api_version=None)
    resp = url_decode(
        twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    db.session.delete(temp_token)
    new_token = OAuthToken(token=resp['oauth_token'],
                           token_secret=resp['oauth_token_secret'])
    new_token = db.session.merge(new_token)
    new_twitter = Twitter(auth=OAuth(new_token.token, new_token.token_secret,
                                     consumer_key, consumer_secret))
    remote_acct = new_twitter.account.verify_credentials()
    acct = account_from_api_user_object(remote_acct)
    acct = db.session.merge(acct)

    new_token.account = acct
    db.session.commit()

    return new_token
Exemplo n.º 14
0
 def _parse_urlencoded(self, stream, mimetype, content_length, options):
     if self.max_form_memory_size is not None and \
        content_length > self.max_form_memory_size:
         raise RequestEntityTooLarge()
     form = url_decode(stream.read(), self.charset,
                       errors=self.errors, cls=self.cls)
     return _empty_stream, form, self.cls()
Exemplo n.º 15
0
def parse_form_data(environ, stream_factory = None, charset = 'utf-8', errors = 'ignore', max_form_memory_size = None, max_content_length = None, cls = None, silent = True):
    content_type, extra = parse_options_header(environ.get('CONTENT_TYPE', ''))
    try:
        content_length = int(environ['CONTENT_LENGTH'])
    except (KeyError, ValueError):
        content_length = 0

    if cls is None:
        cls = MultiDict
    if max_content_length is not None and content_length > max_content_length:
        raise RequestEntityTooLarge()
    stream = _empty_stream
    files = ()
    if content_type == 'multipart/form-data':
        try:
            form, files = parse_multipart(environ['wsgi.input'], extra.get('boundary'), content_length, stream_factory, charset, errors, max_form_memory_size=max_form_memory_size)
        except ValueError as e:
            if not silent:
                raise 
            form = cls()
        else:
            form = cls(form)

    elif content_type == 'application/x-www-form-urlencoded' or content_type == 'application/x-url-encoded':
        if max_form_memory_size is not None and content_length > max_form_memory_size:
            raise RequestEntityTooLarge()
        form = url_decode(environ['wsgi.input'].read(content_length), charset, errors=errors, cls=cls)
    else:
        form = cls()
        stream = LimitedStream(environ['wsgi.input'], content_length)
    return (stream, form, cls(files))
Exemplo n.º 16
0
 def parse_url(self, url_string):
     url = urllib.parse.urlparse(url_string)
     url_adapter = self.url_map.bind(server_name=url.hostname,
                                     url_scheme=url.scheme,
                                     path_info=url.path)
     query_args = url_decode(url.query)
     return url, url_adapter, query_args
Exemplo n.º 17
0
def index():
    if request.args.has_key("magnet"):
        magnet = url_unquote(request.args["magnet"]).encode(request.charset)
        magnet_xt = url_decode(magnet[magnet.index("?") + 1 :])["xt"]
        torrent = cache.get(magnet_xt)
        if not torrent:
            try:
                handle = lt.add_magnet_uri(
                    ses,
                    magnet,
                    {"save_path": "./invalid", "paused": False, "auto_managed": False, "duplicate_is_error": False},
                )
                while not handle.has_metadata():
                    time.sleep(0.01)
                handle.pause()
                info = handle.get_torrent_info()
                torrent = create_torrent(info)
                cache.set(magnet_xt, torrent)
                ses.remove_torrent(handle, lt.options_t.delete_files)
            except:
                torrent = cache.get(magnet_xt)
        response = Response(response=torrent[1], mimetype="application/x-bittorrent")
        response.headers.add("Content-Disposition", "attachment", filename=torrent[0])
        return response
    return render_template("index.html")
Exemplo n.º 18
0
Arquivo: wrappers.py Projeto: Reve/eve
 def args(self):
     return url_decode(
         self.environ.get("QUERY_STRING", ""),
         self.url_charset,
         errors=self.encoding_errors,
         cls=self.parameter_storage_class,
     )
Exemplo n.º 19
0
def callback():
    """Callback from Twitter."""
    try:
        resource_owner_key = cookie.pop('twitter_oauth_token')
        resource_owner_secret = cookie.pop('twitter_oauth_token_secret')
    except KeyError:
        abort(401)
    config = current_app.config
    oauth = OAuth1(config['TWITTER_API_KEY'],
                   client_secret=config['TWITTER_API_SECRET'],
                   resource_owner_key=resource_owner_key,
                   resource_owner_secret=resource_owner_secret,
                   verifier=request.args['oauth_verifier'])
    r = requests.post(url=config['TWITTER_ACCESS_TOKEN_URL'], auth=oauth)
    response = url_decode(r.content)
    user = session.query(User) \
        .filter_by(twitter_user_id=response['user_id']).first()
    if not user:
        user = User(twitter_user_id=response['user_id'])
        session.add(user)
    user.twitter_oauth_token = response['oauth_token']
    user.twitter_oauth_token_secret = response['oauth_token_secret']
    user.screen_name = response['screen_name']
    session.commit()
    cookie['user_id'] = user.id
    return redirect(url_for('.home'))
Exemplo n.º 20
0
    def _get_specific_rendering_values(self, processing_values):
        """ Override of payment to return Mollie-specific rendering values.

        Note: self.ensure_one() from `_get_processing_values`

        :param dict processing_values: The generic and specific processing values of the transaction
        :return: The dict of acquirer-specific rendering values
        :rtype: dict
        """
        res = super()._get_specific_rendering_values(processing_values)
        if self.provider != 'mollie':
            return res

        payload = self._mollie_prepare_payment_request_payload()
        _logger.info("sending '/payments' request for link creation:\n%s", pprint.pformat(payload))
        payment_data = self.acquirer_id._mollie_make_request('/payments', data=payload)

        # The acquirer reference is set now to allow fetching the payment status after redirection
        self.acquirer_reference = payment_data.get('id')

        # Extract the checkout URL from the payment data and add it with its query parameters to the
        # rendering values. Passing the query parameters separately is necessary to prevent them
        # from being stripped off when redirecting the user to the checkout URL, which can happen
        # when only one payment method is enabled on Mollie and query parameters are provided.
        checkout_url = payment_data['_links']['checkout']['href']
        parsed_url = urls.url_parse(checkout_url)
        url_params = urls.url_decode(parsed_url.query)
        return {'api_url': checkout_url, 'url_params': url_params}
Exemplo n.º 21
0
 def __call__(self, environ, start_response):
     if '__method__' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('__method__')
         if method:
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemplo n.º 22
0
def login_url(login_view, next_url=None, next_field='next'):
    '''
    Creates a URL for redirecting to a login page. If only `login_view` is
    provided, this will just return the URL for it. If `next_url` is provided,
    however, this will append a ``next=URL`` parameter to the query string
    so that the login view can redirect back to that URL.

    :param login_view: The name of the login view. (Alternately, the actual
                       URL to the login view.)
    :type login_view: str
    :param next_url: The URL to give the login view for redirection.
    :type next_url: str
    :param next_field: What field to store the next URL in. (It defaults to
                       ``next``.)
    :type next_field: str
    '''
    base = expand_login_view(login_view)

    if next_url is None:
        return base

    parsed_result = urlparse(base)
    md = url_decode(parsed_result.query)
    md[next_field] = make_next_param(base, next_url)
    parsed_result = parsed_result._replace(query=url_encode(md, sort=True))
    return urlunparse(parsed_result)
Exemplo n.º 23
0
 def parse_redirect(self, location, parse_fragment=False):
     from werkzeug.urls import url_parse, url_decode, url_unparse
     scheme, netloc, script_root, qs, anchor = url_parse(location)
     return (
         url_unparse((scheme, netloc, script_root, '', '')),
         url_decode(anchor if parse_fragment else qs)
     )
Exemplo n.º 24
0
def login_url(login_view, next_url=None, next_field='next'):
    '''
    Creates a URL for redirecting to a login page. If only `login_view` is
    provided, this will just return the URL for it. If `next_url` is provided,
    however, this will append a ``next=URL`` parameter to the query string
    so that the login view can redirect back to that URL.

    :param login_view: The name of the login view. (Alternately, the actual
                       URL to the login view.)
    :type login_view: str
    :param next_url: The URL to give the login view for redirection.
    :type next_url: str
    :param next_field: What field to store the next URL in. (It defaults to
                       ``next``.)
    :type next_field: str
    '''
    base = expand_login_view(login_view)

    if next_url is None:
        return base

    parsed_result = urlparse(base)
    md = url_decode(parsed_result.query)
    md[next_field] = make_next_param(base, next_url)
    parsed_result = parsed_result._replace(query=url_encode(md, sort=True))
    return urlunparse(parsed_result)
Exemplo n.º 25
0
def test_auto_token_get():
    responses.add(responses.GET, "https://slack.com/api/chat.postMessage")

    app = Flask(__name__)
    slack_bp = make_slack_blueprint(
        client_id="foo",
        client_secret="bar",
        backend=MemoryBackend({"access_token": "abcde"}),
    )
    app.register_blueprint(slack_bp, url_prefix="/login")

    with app.test_request_context("/"):
        app.preprocess_request()
        resp = slack.get("chat.postMessage",
                         data={
                             "channel": "#general",
                             "text": "ping",
                             "icon_emoji": ":robot_face:",
                         })
    request_data = url_decode(resp.request.body)
    assert request_data["channel"] == "#general"
    assert request_data["text"] == "ping"
    assert request_data["icon_emoji"] == ":robot_face:"
    # the `token` parameter should have been automatically added
    assert request_data["token"] == "abcde"
Exemplo n.º 26
0
def login_url(login_view, next_url=None, next_field='next'):
    '''
    Creates a URL for redirecting to a login page. If only `login_view` is
    provided, this will just return the URL for it. If `next_url` is provided,
    however, this will append a ``next=URL`` parameter to the query string
    so that the login view can redirect back to that URL. Flask-Login's default
    unauthorized handler uses this function when redirecting to your login url.
    To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This
    prevents from redirecting to external sites if request headers Host or
    X-Forwarded-For are present.

    :param login_view: The name of the login view. (Alternately, the actual
                       URL to the login view.)
    :type login_view: str
    :param next_url: The URL to give the login view for redirection.
    :type next_url: str
    :param next_field: What field to store the next URL in. (It defaults to
                       ``next``.)
    :type next_field: str
    '''
    base = expand_login_view(login_view)

    if next_url is None:
        return base

    parsed_result = urlparse(base)
    md = url_decode(parsed_result.query)
    md[next_field] = make_next_param(base, next_url)
    netloc = current_app.config.get('FORCE_HOST_FOR_REDIRECTS') or \
        parsed_result.netloc
    parsed_result = parsed_result._replace(netloc=netloc,
                                           query=url_encode(md, sort=True))
    return urlunparse(parsed_result)
Exemplo n.º 27
0
def auth():
    try:
        back = request.args['back']
    except KeyError:
        redirect_uri = url_for('auth', _external=True)
        initial = True
    else:
        redirect_uri = url_for('auth', back=back, _external=True)
        initial = False
    params = {
        'client_id': current_app.config['CLIENT_ID'],
        'client_secret': current_app.config['CLIENT_SECRET'],
        'redirect_uri': redirect_uri,
        'code': request.args['code'],
        'state': get_oauth_state()
    }
    response = urllib2.urlopen('https://github.com/login/oauth/access_token',
                               url_encode(params))
    auth_data = url_decode(response.read())
    response.close()
    token = auth_data['access_token']
    if initial:
        with open_token_file('w') as f:
            f.write(token)
        current_app.config['ACCESS_TOKEN'] = token
        return_url = url_for('home')
    else:
        return_url = base64.urlsafe_b64decode(str(back))
    session['login'] = token
    return redirect(return_url)
Exemplo n.º 28
0
    def __call__(self, rev, contenttype=None, arguments=None):
        item_name = rev.item.name
        query_keys = {'do': 'get', 'rev': rev.revid}
        attrib = {}
        if arguments:
            query = arguments.keyword.get(xinclude.href)
            if query and query.query:
                # query.query value is similar to  "w=75" given a transclusion "{{jpeg||&w=75 class="top"}}"
                query_keys.update(url_decode(query.query))
            attrib = arguments.keyword

        query = url_encode(query_keys, charset=CHARSET, encode_keys=True)

        attrib.update({
            moin_page.type_:
            str(self.input_type),
            xlink.href:
            Iri(scheme='wiki',
                authority='',
                path='/' + rev.item.fqname.fullname,
                query=query),
        })
        if rev.meta.get(SUMMARY) and html.alt not in attrib:
            attrib[html.alt] = rev.meta[SUMMARY]

        obj = moin_page.object_(attrib=attrib, children=[
            item_name,
        ])
        body = moin_page.body(children=(obj, ))
        return moin_page.page(children=(body, ))
Exemplo n.º 29
0
 def __call__(self, environ, start_response):
     if '__method__' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('__method__')
         if method:
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemplo n.º 30
0
    def connect(self, sid, environ):
        """
        Called on new client connection.
        Client must identify itself using the query string parameter 'user'

        :param str sid: socketio's socket identifier
        :param dict environ: wsgi environment

        :returns: True if connection is accepted False otherwise
        """
        params = urls.url_decode(environ['QUERY_STRING'])
        if 'user' not in params:
            return False

        username = params['user']

        if username in self.users:
            return False
        if sid in self.connections:
            return False

        self.users[username] = sid
        self.connections[sid] = username

        logger.info('New connection from %s', username)

        return True
Exemplo n.º 31
0
def getParams():

    params = url_decode(getattr(flask.request, 'environ').get('QUERY_STRING', ''))
    reg = re.compile('^[a-z0-9_\.]+$')

    current = temp = {}
    for param, value in sorted(params.iteritems()):

        nest = re.split("([\[\]]+)", param)
        if len(nest) > 1:
            nested = []
            for key in nest:
                if reg.match(key):
                    nested.append(key)

            current = temp

            for item in nested:
                if item is nested[-1]:
                    current[item] = toUnicode(unquote(value))
                else:
                    try:
                        current[item]
                    except:
                        current[item] = {}

                    current = current[item]
        else:
            temp[param] = toUnicode(unquote(value))

    return dictToList(temp)
Exemplo n.º 32
0
def login_url(login_view, next_url=None, next_field='next'):
    '''
    Creates a URL for redirecting to a login page. If only `login_view` is
    provided, this will just return the URL for it. If `next_url` is provided,
    however, this will append a ``next=URL`` parameter to the query string
    so that the login view can redirect back to that URL.

    :param login_view: The name of the login view. (Alternately, the actual
                       URL to the login view.)
    :type login_view: str
    :param next_url: The URL to give the login view for redirection.
    :type next_url: str
    :param next_field: What field to store the next URL in. (It defaults to
                       ``next``.)
    :type next_field: str
    '''
    if login_view.startswith(('https://', 'http://', '/')):
        base = login_view
    else:
        base = url_for(login_view)

    if next_url is None:
        return base

    parts = list(urlparse(base))
    md = url_decode(parts[4])
    md[next_field] = make_next_param(base, next_url)
    parts[4] = url_encode(md, sort=True)
    return urlunparse(parts)
Exemplo n.º 33
0
    def twitter_request(self, original_url):
        conf_ = conf['twitter']
        original_url = oauth_base + conf_['callback_base'] + url_quote(original_url)

        consumer = oauth2.Consumer(conf_['consumer_key'], conf_['consumer_secret'])
        client = oauth2.Client(consumer)

        q, content = client.request(conf_['token_url'], "POST",
                                    body = url_encode({'oauth_callback':original_url}))

        if q['status'] != "200":
            stderr.write("Login error twitter auth:\n    %s\n" % q.content)
            return self.redirect('/?msg=2')
        del q

        oauth_data = url_decode(content)
        oauth_token = oauth_data['oauth_token']
        oauth_token_secret = oauth_data['oauth_token_secret']

        del content
        del oauth_data

        f = open(oauth_secrets_path_prefix + oauth_token, 'w')
        f.write(oauth_token_secret)
        f.close()

        self.redirect(conf_['authenticate'] + "?oauth_token=" + oauth_token)
Exemplo n.º 34
0
def auth():
    try:
        back = request.args['back']
    except KeyError:
        redirect_uri = url_for('auth', _external=True)
        initial = True
    else:
        redirect_uri = url_for('auth', back=back, _external=True)
        initial = False
    params = {
        'client_id': current_app.config['CLIENT_ID'],
        'client_secret': current_app.config['CLIENT_SECRET'],
        'redirect_uri': redirect_uri,
        'code': request.args['code'],
        'state': get_oauth_state()
    }
    response = urllib2.urlopen(
        'https://github.com/login/oauth/access_token',
        url_encode(params)
    )
    auth_data = url_decode(response.read())
    response.close()
    token = auth_data['access_token']
    if initial:
        with open_token_file('w') as f:
            f.write(token)
        current_app.config['ACCESS_TOKEN'] = token
        return_url = url_for('home')
    else:
        return_url = base64.urlsafe_b64decode(str(back))
    session['login'] = token
    return redirect(return_url)
Exemplo n.º 35
0
 def __call__(self, environ, start_response):
     if '_method' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('_method')
         if method:
             method = method.encode('ascii', 'replace')
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemplo n.º 36
0
 def dispatch_request(self, request):
     adapter = self.routes.bind_to_environ(request.environ)
     request.GET = url_decode(request.environ['QUERY_STRING'])
     try:
         endpoint, values = adapter.match()
         return getattr(self, endpoint)(request, **values)
     except NotFound, e:
         return self.error_404()
Exemplo n.º 37
0
 def __call__(self, environ, start_response):
     if self.method_param_q in environ.get("QUERY_STRING", ""):
         args = url_decode(environ["QUERY_STRING"])
         method = args.pop(self.method_param, None)
         if method:
             method = method.upper().encode("ascii", "replace")
             environ["REQUEST_METHOD"] = method
             environ["QUERY_STRING"] = url_encode(args)
     return self.app(environ, start_response)
Exemplo n.º 38
0
 def POST(self):
     if self.route.is_flask():
         return self.request.form or self.request.args or url_decode(self.request.data)
     elif self.route.is_django():
         return self.request.POST
     elif self.route.is_appengine():
         return self.request.REQUEST
     elif self.route.is_dummy() or self.route.is_standalone():
         return self.request.data
     raise NotImplementedError
Exemplo n.º 39
0
    def test_signing_in_redirects_me_to_signon(self):
        response = self.client.get('/sign-in')

        params = url_decode(response.headers['Location'].split('?')[1])

        assert_that(response, has_status(302))
        assert_that(params, has_entry('response_type', 'code'))
        assert_that(params, has_entry('redirect_uri',
                                      'http://backdrop-admin.dev.gov.uk/authorized'))
        assert_that(params, has_entry('client_id',
                                      app.app.config['OAUTH_CLIENT_ID']))
Exemplo n.º 40
0
 def REQUEST(self):
     if self.route.is_flask():
         return self.request.form or self.request.args or url_decode(self.request.data)
     elif self.route.is_django():
         return self.request.REQUEST
     elif self.route.is_appengine():
         return dict(map(lambda i: (i, self.request.get(i)), \
             self.request.arguments()))
     elif self.route.is_dummy() or self.route.is_standalone():
         return self.request.data
     raise NotImplementedError
Exemplo n.º 41
0
def login_url(login_view, next_url=None, next_field="next"):
    if login_view.startswith(("https://", "http://", "/")):
        base = login_view
    else:
        base = url_for(login_view)
    if next_url is None:
        return base
    parts = list(urlparse(base))
    md = url_decode(parts[4])
    md[next_field] = make_next_param(base, next_url)
    parts[4] = url_encode(md, sort=True)
    return urlunparse(parts)
Exemplo n.º 42
0
 def preprocess_request(self, request):
     request_header_validator = valid.DictValidator({
         'Content-Length': valid.IntegerValidator(max=MAX_BODY_LENGTH),
         'Content-Type': valid.ConstValidator('application/json'),
     })
     if request.method in ['POST', 'PUT'] and\
             not re.match(self.storage_url, request.path):
         request_header_validator(dict(request.headers))
         #TODO: FIXME GK
     if request.method == 'GET':
         data = url_decode(request.query_string, cls=dict)
         request.data = json.dumps(data)