def test_get_authorize(self): rv = self.client.get('/oauth/authorize') assert 'Missing+client_id+parameter' in rv.location client = self.client rv = client.get('/oauth/authorize?client_id=ios&response_type=code') assert rv.status_code == 200 user = self.login() rv = client.get('/oauth/authorize?client_id=ios&response_type=code') assert rv.status_code == 200 assert to_bytes(user.username) in rv.data oauth_client = OAuthClient.query.first() rv = client.get('/oauth/authorize?%s' % url_encode({ 'client_id': oauth_client.client_id, 'response_type': 'code', 'scope': 'user', })) assert b'user:email' in rv.data assert b'user:write' in rv.data rv = client.get('/oauth/authorize?%s' % url_encode({ 'client_id': oauth_client.client_id, 'response_type': 'code', 'scope': 'user:email', })) assert b'user:email' in rv.data assert b'user:write' not in rv.data
def test_url_encoding(): strict_eq(urls.url_encode({"foo": "bar 45"}), "foo=bar+45") d = {"foo": 1, "bar": 23, "blah": u"Hänsel"} strict_eq(urls.url_encode(d, sort=True), "bar=23&blah=H%C3%A4nsel&foo=1") strict_eq( urls.url_encode(d, sort=True, separator=u";"), "bar=23;blah=H%C3%A4nsel;foo=1" )
def test_delete(self): admin_access_token = self.get_access_token_for_role('admin') other_access_token = self.get_access_token_for_role('user') # Create a second token to delete expire_time = datetime.now().replace(microsecond=0) token = model.auth.bearer_token.BearerToken(client=self.client, user=admin_access_token.user, token_type='bearer', access_token='Xqd8px7X6OO2gqc0vhlmJd1oUYaj2X', refresh_token='iRwV7aDH5VCwsvIZvJGWAui9O1wiP1', expires=expire_time, remote_address=None, user_agent='', _scopes='zway') db.session.add(token) token = model.auth.bearer_token.BearerToken.query.filter_by(user=admin_access_token.user, access_token='Xqd8px7X6OO2gqc0vhlmJd1oUYaj2X').first() db.session.commit() # Check that there are two sessions data = dict(access_token=admin_access_token.access_token) response = self.app.get('/api/v1/account/sessions?%s' % url_encode(data)) token_data = self.check_api_response(response) assert len(token_data['sessions']) == 2 # Delete session data = dict(access_token=admin_access_token.access_token) response = self.app.delete('/api/v1/account/sessions/%s?%s' % (token.id, url_encode(data))) token_data = self.check_api_response(response) assert token_data['session']['user']['username'] == admin_access_token.user.username # Get sessions info data = dict(access_token=admin_access_token.access_token) response = self.app.get('/api/v1/account/sessions?%s' % url_encode(data)) token_data = self.check_api_response(response) assert len(token_data['sessions']) == 1 # Try to delete session of another user data = dict(access_token=admin_access_token.access_token) response = self.app.delete('/api/v1/account/sessions/%s?%s' % (other_access_token.id, url_encode(data))) token_data = self.check_api_response(response, 404)
def test_grant_type_password(self): # Build ACL InitCommand.build_acl() # Create client client = InitCommand.save_client('Test', 'Py Test Client', 'test') # Create user user = UserCommand.save_user('admin', 'Admin', 'adminpwd', '*****@*****.**', 'admin') username = user.username email = user.email # Request token data = dict(grant_type='password', password='******', username=user.username, scope='test', client_id=client.client_id, client_secret=client.client_secret) response = self.app.get('/api/v1/auth?%s' % url_encode(data)) token_data = self.check_api_response(response) assert token_data['token_type'] == 'Bearer' assert token_data['scope'] == 'test' # Get user info data = dict(access_token=token_data['access_token']) response = self.app.get('/api/v1/account?%s' % url_encode(data)) user_data = self.check_api_response(response) assert user_data['account']['email'] == email assert user_data['account']['username'] == username
def test_put_password(self): admin_access_token = self.get_access_token_for_role('admin') # Update password data = dict(access_token=admin_access_token.access_token) post_data = dict(old_password='******', new_password='******', password_repeat='newpwd', options='password') response = self.app.put('/api/v1/account?%s' % url_encode(data), data=json.dumps(post_data), content_type='application/json') user_data = self.check_api_response(response) assert user_data['account']['email'] == admin_access_token.user.email assert user_data['account']['username'] == admin_access_token.user.username assert user_data['account']['fullname'] == admin_access_token.user.fullname user = model.auth.user.User.query.first() assert user.check_password('newpwd') # Try to update with wrong old password data = dict(access_token=admin_access_token.access_token) post_data = dict(old_password='******', new_password='******', password_repeat='newpwd', options='password') response = self.app.put('/api/v1/account?%s' % url_encode(data), data=json.dumps(post_data), content_type='application/json') user_data = self.check_api_response(response, 409) user = model.auth.user.User.query.first() assert user.check_password('newpwd') # Try to update with wrong repeated password data = dict(access_token=admin_access_token.access_token) post_data = dict(old_password='******', new_password='******', password_repeat='wrongnewpwd', options='password') response = self.app.put('/api/v1/account?%s' % url_encode(data), data=json.dumps(post_data), content_type='application/json') user_data = self.check_api_response(response, 409) user = model.auth.user.User.query.first() assert user.check_password('newpwd')
def test_get(self): user_access_token = self.get_access_token_for_role('user') admin_access_token = self.get_access_token_for_role('admin') device_1 = model.zwave.device.Device(zway_id=5, name='test_device', description='Test device 1') db.session.add(device_1) device_1 = model.zwave.device.Device.query.filter_by(zway_id=5).first() device_2 = model.zwave.device.Device(zway_id=3, name='test_device_2', description='Test device 2') db.session.add(device_2) device_2 = model.zwave.device.Device.query.filter_by(zway_id=3).first() user_access_token.user.devices = [device_1] db.session.commit() # Get device info data = dict(access_token=user_access_token.access_token) response = self.app.get('/api/v1/zwave/devices/%d?%s' % (device_1.id, url_encode(data))) devices_data = self.check_api_response(response) assert devices_data['device']['zway_id'] == 5 assert devices_data['device']['name'] == 'test_device' assert devices_data['device']['description'] == 'Test device 1' response = self.app.get('/api/v1/zwave/devices/%d?%s' % (device_2.id, url_encode(data))) self.check_api_response(response, 404) data = dict(access_token=admin_access_token.access_token) response = self.app.get('/api/v1/zwave/devices/%d?%s' % (device_2.id, url_encode(data))) devices_data = self.check_api_response(response) assert devices_data['device']['zway_id'] == 3 assert devices_data['device']['name'] == 'test_device_2' assert devices_data['device']['description'] == 'Test device 2'
def test_get_redirect_url_with_query_string(self, url, qs): instance = core.RedirectView(url=url, query_string=True) result = url_parse(url).replace(query=url_encode(qs)).to_url() with patch.object(core, 'request') as m: m.environ = {'QUERY_STRING': url_encode(qs)} assert instance.get_redirect_url() == result
def test_quoting(self): self.assert_strict_equal(urls.url_quote(u'\xf6\xe4\xfc'), '%C3%B6%C3%A4%C3%BC') self.assert_strict_equal(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6') self.assert_strict_equal(urls.url_quote_plus('foo bar'), 'foo+bar') self.assert_strict_equal(urls.url_unquote_plus('foo+bar'), u'foo bar') self.assert_strict_equal(urls.url_encode({b'a': None, b'b': b'foo bar'}), 'b=foo+bar') self.assert_strict_equal(urls.url_encode({u'a': None, u'b': u'foo bar'}), 'b=foo+bar') self.assert_strict_equal(urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'), 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)')
def with_qs(url, **args): """Updates query string part from the ``url``. Parameters to update are given by keywords. """ try: pos = url.index('?') except ValueError: return url + '?' + url_encode(args) pos += 1 query = url_decode(url[pos:], cls=dict) query.update(args) return url[:pos] + url_encode(query)
def test_quoting(): strict_eq(urls.url_quote(u'\xf6\xe4\xfc'), '%C3%B6%C3%A4%C3%BC') strict_eq(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6') strict_eq(urls.url_quote_plus('foo bar'), 'foo+bar') strict_eq(urls.url_unquote_plus('foo+bar'), u'foo bar') strict_eq(urls.url_quote_plus('foo+bar'), 'foo%2Bbar') strict_eq(urls.url_unquote_plus('foo%2Bbar'), u'foo+bar') strict_eq(urls.url_encode({b'a': None, b'b': b'foo bar'}), 'b=foo+bar') strict_eq(urls.url_encode({u'a': None, u'b': u'foo bar'}), 'b=foo+bar') strict_eq(urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'), 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)') strict_eq(urls.url_quote_plus(42), '42') strict_eq(urls.url_quote(b'\xff'), '%FF')
def url_for_page(self, pagenum): current_args = flask.request.args args_dict = current_args.to_dict() if pagenum != 1: args_dict['page'] = pagenum elif 'page' in args_dict: del args_dict['page'] encoded = url_encode(args_dict) if encoded: url = "".join([flask.request.path, "?",url_encode(args_dict)]) return url else: return flask.request.path
def test_quoting(): strict_eq(urls.url_quote(u"\xf6\xe4\xfc"), "%C3%B6%C3%A4%C3%BC") strict_eq(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6') strict_eq(urls.url_quote_plus("foo bar"), "foo+bar") strict_eq(urls.url_unquote_plus("foo+bar"), u"foo bar") strict_eq(urls.url_quote_plus("foo+bar"), "foo%2Bbar") strict_eq(urls.url_unquote_plus("foo%2Bbar"), u"foo+bar") strict_eq(urls.url_encode({b"a": None, b"b": b"foo bar"}), "b=foo+bar") strict_eq(urls.url_encode({u"a": None, u"b": u"foo bar"}), "b=foo+bar") strict_eq( urls.url_fix(u"http://de.wikipedia.org/wiki/Elf (Begriffsklärung)"), "http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)", ) strict_eq(urls.url_quote_plus(42), "42") strict_eq(urls.url_quote(b"\xff"), "%FF")
def test_sorted_url_encode(): strict_eq( urls.url_encode( {u"a": 42, u"b": 23, 1: 1, 2: 2}, sort=True, key=lambda i: text_type(i[0]) ), "1=1&2=2&a=42&b=23", ) strict_eq( urls.url_encode( {u"A": 1, u"a": 2, u"B": 3, "b": 4}, sort=True, key=lambda x: x[0].lower() + x[0], ), "A=1&a=2&B=3&b=4", )
def build(self, values, append_unknown=True): tmp = [] add = tmp.append processed = set(self.arguments) for is_dynamic, data in self._trace: if is_dynamic: try: add(self._converters[data].to_url(values[data])) except ValidationError: return processed.add(data) else: add(data) subdomain, url = u"".join(tmp).split("|", 1) if append_unknown: query_vars = MultiDict(values) for key in processed: if key in query_vars: del query_vars[key] if query_vars: url += "?" + url_encode( query_vars, self.map.charset, sort=self.map.sort_parameters, key=self.map.sort_key ) return (subdomain, url)
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)
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)
def fb_request(self, original_url): conf_ = conf['fb'] original_url = oauth_base + conf_['callback_base'] + url_quote(original_url) uri = conf_['token_url'] + '?' + url_encode({'client_id': conf_['consumer_key'], 'redirect_uri': original_url}) self.redirect(uri)
def ccavenue_form_generate_values(self, values): self.ensure_one() base_url = self.env['ir.config_parameter'].get_param('web.base.url') ccavenue_values = dict(access_code=self.ccavenue_access_code, merchant_id=self.ccavenue_merchant_id, order_id=values.get('reference'), currency=values.get('currency').name, amount=values.get('amount'), redirect_url=urls.url_join(base_url, CCAvenueController._return_url), cancel_url=urls.url_join(base_url, CCAvenueController._cancel_url), language='EN', customer_identifier=values.get('partner_email'), delivery_name=values.get('partner_name'), delivery_address=values.get('partner_address'), delivery_city=values.get('partner_city'), delivery_state=values.get('partner_state').name, delivery_zip=values.get('partner_zip'), delivery_country=values.get('partner_country').name, delivery_tel=values.get('partner_phone'), billing_name=values.get('billing_partner_name'), billing_address=values.get('billing_partner_address'), billing_city=values.get('billing_partner_city'), billing_state=values.get('billing_partner_state').name, billing_zip=values.get('billing_partner_zip'), billing_country=values.get('billing_partner_country').name, billing_tel=values.get('billing_partner_phone'), billing_email=values.get('billing_partner_email'), ) ccavenue_values['encRequest'] = self._ccavenue_encrypt_text(urls.url_encode(ccavenue_values)) return ccavenue_values
def url_for(endpoint, **values): if endpoint == 'admin.static': filename = values.pop('filename') query = url_encode(values) url_prefix = current_app.config['ADMIN_STATIC_URL'] return '{}?{}'.format(url_join(url_prefix, filename), query) return flask_url_for(endpoint, **values)
def _get_share_url(self, redirect=False, signup_partner=False, pid=None): """ Build the url of the record that will be sent by mail and adds additional parameters such as access_token to bypass the recipient's rights, signup_partner to allows the user to create easily an account, hash token to allow the user to be authenticated in the chatter of the record portal view, if applicable :param redirect : Send the redirect url instead of the direct portal share url :param signup_partner: allows the user to create an account with pre-filled fields. :param pid: = partner_id - when given, a hash is generated to allow the user to be authenticated in the portal chatter, if any in the target page, if the user is redirected to the portal instead of the backend. :return: the url of the record with access parameters, if any. """ self.ensure_one() params = { 'model': self._name, 'res_id': self.id, } if hasattr(self, 'access_token'): params['access_token'] = self._portal_ensure_token() if pid: params['pid'] = pid params['hash'] = self._sign_token(pid) if signup_partner and hasattr(self, 'partner_id') and self.partner_id: params.update(self.partner_id.signup_get_auth_param()[self.partner_id.id]) return '%s?%s' % ('/mail/view' if redirect else self.access_url, url_encode(params))
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)
def reddit_handle_oauth2_response(): access_args = { 'code': flask.request.args.get('code'), 'client_id': reddit.consumer_key, 'redirect_uri': flask.session.get('%s_oauthredir' % reddit.name), } access_args.update(reddit.access_token_params) auth = 'Basic ' + b64encode( ('%s:%s' % (reddit.consumer_key, reddit.consumer_secret)).encode( 'latin1')).strip().decode('latin1') response, content = reddit.http_request( reddit.expand_url(reddit.access_token_url), method=reddit.access_token_method, data=urls.url_encode(access_args), headers={ 'Authorization': auth, 'User-Agent': config.USER_AGENT, }, ) data = oauth.parse_response(response, content) if response.code not in (200, 201): raise oauth.OAuthException( 'Invalid response from %s' % reddit.name, type='invalid_response', data=data, ) return data
def get_environ(self): """返回内置环境。""" input_stream = self.input_stream content_length = self.content_length content_type = self.content_type if input_stream is not None: start_pos = input_stream.tell() input_stream.seek(0, 2) end_pos = input_stream.tell() input_stream.seek(start_pos) content_length = end_pos - start_pos elif content_type == "multipart/form-data": values = CombinedMultiDict([self.form, self.files]) input_stream, content_length, boundary = stream_encode_multipart(values, charset=self.charset) content_type += '; boundary="%s"' % boundary elif content_type == "application/x-www-form-urlencoded": # py2v3 review values = url_encode(self.form, charset=self.charset) values = values.encode("ascii") content_length = len(values) input_stream = BytesIO(values) else: input_stream = _empty_stream result = {} if self.environ_base: result.update(self.environ_base) def _path_encode(x): return wsgi_encoding_dance(url_unquote(x, self.charset), self.charset) qs = wsgi_encoding_dance(self.query_string) result.update( { "REQUEST_METHOD": self.method, "SCRIPT_NAME": _path_encode(self.script_root), "PATH_INFO": _path_encode(self.path), "QUERY_STRING": qs, "SERVER_NAME": self.server_name, "SERVER_PORT": str(self.server_port), "HTTP_HOST": self.host, "SERVER_PROTOCOL": self.server_protocol, "CONTENT_TYPE": content_type or "", "CONTENT_LENGTH": str(content_length or "0"), "wsgi.version": self.wsgi_version, "wsgi.url_scheme": self.url_scheme, "wsgi.input": input_stream, "wsgi.errors": self.errors_stream, "wsgi.multithread": self.multithread, "wsgi.multiprocess": self.multiprocess, "wsgi.run_once": self.run_once, } ) for key, value in self.headers.to_wsgi_list(): result["HTTP_%s" % key.upper().replace("-", "_")] = value if self.environ_overrides: result.update(self.environ_overrides) return result
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)
def decorated_function(*args, **kwargs): if session.get('logged_in',False) is False: flash('You must login first!','alert-danger') ## TODO take the next code from sysman - much improved over this. args = url_encode(request.args) return redirect(url_for('login', next=request.script_root + request.path + "?" + args)) return f(*args, **kwargs)
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)
def login_box(request): from kay.auth import login next = unquote_plus(request.values.get("next")) owned_domain_hack = request.values.get("owned_domain_hack") message = "" form = LoginBoxForm() if request.method == "POST": if form.validate(request.form): result = login(request, user_name=form.data['user_name'], password=form.data['password']) if result: if owned_domain_hack == 'True': original_host_url = unquote_plus( request.values.get("original_host_url")) url = original_host_url[:-1] + url_for("auth/post_session") url += '?' + url_encode({'session_id': result.key().name(), 'next': next}) return redirect(url) else: return redirect(next) else: message = _("Failed to login.") return render_to_response("auth/loginform.html", {"form": form.as_widget(), "message": message})
def login(request): from kay.auth import login if settings.AUTH_POST_LOGIN_SUCCESS_DEFAULT_URL: next = unquote_plus(request.values.get("next", settings.AUTH_POST_LOGIN_SUCCESS_DEFAULT_URL)) else: next = unquote_plus(request.values.get("next", "/")) owned_domain_hack = request.values.get("owned_domain_hack") message = "" form = LoginForm() if request.method == "POST": if form.validate(request.form): result = login(request, user_name=form.data['user_name'], password=form.data['password']) if result: if owned_domain_hack == 'True': original_host_url = unquote_plus( request.values.get("original_host_url")) url = original_host_url[:-1] + url_for("auth/post_session") url += '?' + url_encode({'session_id': result.key().name(), 'next': next}) return redirect(url) else: return redirect(next) else: message = _("Failed to login successfully with those credentials, try another or click the 'Forgot Password' link below.") return render_to_response("auth/loginform.html", {"form": form.as_widget(), "message": message})
def yahoo_handle_oauth2_response(args): access_args = { 'code': args.get('code'), 'client_id': yahoo.consumer_key, 'client_secret': yahoo.consumer_secret, 'redirect_uri': flask.session.get('%s_oauthredir' % yahoo.name), 'state': args.get('state'), } access_args.update(yahoo.access_token_params) auth_header = 'Basic %s' % base64.b64encode( ('%s:%s' % (yahoo.consumer_key, yahoo.consumer_secret)).encode('latin1') ).strip().decode('latin1') response, content = yahoo.http_request( yahoo.expand_url(yahoo.access_token_url), method=yahoo.access_token_method, data=urls.url_encode(access_args), headers={ 'Authorization': auth_header, 'User-Agent': config.USER_AGENT, 'Content-Type': 'application/x-www-form-urlencoded', }, ) data = client.parse_response(response, content) if response.code not in (200, 201): raise client.OAuthException( 'Invalid response from %s' % yahoo.name, type='invalid_response', data=data, ) return data
def _redirect_to_record(cls, model, res_id, access_token=None, **kwargs): """ If the current user doesn't have access to the document, but provided a valid access token, redirect him to the front-end view. If the partner_id and hash parameters are given, add those parameters to the redirect url to authentify the recipient in the chatter, if any. :param model: the model name of the record that will be visualized :param res_id: the id of the record :param access_token: token that gives access to the record bypassing the rights and rules restriction of the user. :param kwargs: Typically, it can receive a partner_id and a hash (sign_token). If so, those two parameters are used to authentify the recipient in the chatter, if any. :return: """ if issubclass(type(request.env[model]), request.env.registry['portal.mixin']): uid = request.session.uid or request.env.ref('base.public_user').id record_sudo = request.env[model].sudo().browse(res_id).exists() try: record_sudo.sudo(uid).check_access_rights('read') record_sudo.sudo(uid).check_access_rule('read') except AccessError: if record_sudo.access_token and access_token and consteq(record_sudo.access_token, access_token): record_action = record_sudo.with_context(force_website=True).get_access_action() if record_action['type'] == 'ir.actions.act_url': pid = kwargs.get('pid') hash = kwargs.get('hash') url = record_action['url'] if pid and hash: url = urls.url_parse(url) url_params = url.decode_query() url_params.update([("pid", pid), ("hash", hash)]) url = url.replace(query=urls.url_encode(url_params)).to_url() return werkzeug.utils.redirect(url) return super(MailController, cls)._redirect_to_record(model, res_id, access_token=access_token)
def _generate_action_url(self, email, action): """Generate the confirmation URL to subscribe / unsubscribe from the mailing list.""" if action not in ['subscribe', 'unsubscribe']: raise ValueError(_('Invalid action for URL generation (%s)', action)) self.ensure_one() confirm_action_url = '/groups/subscribe?%s' % urls.url_encode({ 'group_id': self.id, 'email': email, 'token': self._generate_action_token(email, action), 'action': action, }) base_url = self.get_base_url() confirm_action_url = urls.url_join(base_url, confirm_action_url) return confirm_action_url
def digest_set_periodicity(self, digest_id, periodicity='weekly'): if not request.env.user.has_group('base.group_erp_manager'): raise Forbidden() if periodicity not in ('daily', 'weekly', 'monthly', 'quarterly'): raise ValueError(_('Invalid periodicity set on digest')) digest = request.env['digest.digest'].browse(digest_id).exists() digest.action_set_periodicity(periodicity) url_params = { 'model': digest._name, 'id': digest.id, 'active_id': digest.id, } return request.redirect('/web?#%s' % url_encode(url_params))
def _compute_redirected_url(self): for tracker in self: parsed = urls.url_parse(tracker.url) utms = {} for key, field_name, cook in self.env['utm.mixin'].tracking_fields( ): field = self._fields[field_name] attr = getattr(tracker, field_name) if field.type == 'many2one': attr = attr.name if attr: utms[key] = attr utms.update(parsed.decode_query()) tracker.redirected_url = parsed.replace( query=urls.url_encode(utms)).to_url()
def redirect_on_record(self): for activity in self: if activity.model and activity.res_id: params = { 'model': activity.model, 'res_id': activity.res_id, } record = self.env[activity.model].browse(activity.res_id) return { 'type': 'ir.actions.act_url', 'url': '/mail/view?' + url_encode(params), 'target': 'self', 'target_type': 'public', 'res_id': record.id, }
def _compute_url(self): base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url') for source in self: source.url = urls.url_join( base_url, "%s?%s" % (source.job_id.website_url, urls.url_encode({ 'utm_campaign': self.env.ref('hr_recruitment.utm_campaign_job').name, 'utm_medium': self.env.ref('utm.utm_medium_website').name, 'utm_source': source.source_id.name })))
def _notify_download(self, url): ''' Notifies Unsplash from an image download. (API requirement) :param url: the download_url of the image to be notified This method won't return anything. This endpoint should just be pinged with a simple GET request for Unsplash to increment the image view counter. ''' try: if not url.startswith('https://api.unsplash.com/photos/'): raise Exception(_("ERROR: Unknown Unsplash notify URL!")) access_key = self._get_access_key() requests.get(url, params=url_encode({'client_id': access_key})) except Exception as e: logger.exception("Unsplash download notification failed: " + str(e))
def open_record(self): for log in self: if log.model and log.res_id: params = { "model": log.model, "res_id": log.res_id, } record = self.env[log.model].browse(log.res_id) return { "type": "ir.actions.act_url", "url": "/mail/view?" + url_encode(params), "target": "self", "target_type": "public", "res_id": record.id, }
def test_get_datasets_by_species(self): payload = {'species': 'Goat'} response = self.client.get( "?".join([self.test_endpoint, url_encode(payload)]), headers=self.headers ) test = response.json self.assertEqual(test['total'], 1) self.assertIsInstance(test['items'], list) self.assertEqual(len(test['items']), 1) self.assertListEqual(test['items'], self.goats_data) self.assertEqual(response.status_code, 200)
def oauth2_authorize(): client_id = request.args.get('client_id') if not client_id: raise MissingFieldError('client_id') # Check that the user allowed the client if not DbUserClient.query.filter_by(user_id=request.user.id, client_id=client_id).count(): # Redirect users to consent page if the client was not confirmed yet dashboard_prefix = app.config.get("DASHBOARD_PREFIX") args = url_encode(dict(client_id=client_id, next=request.url)) return redirect('{dashboard_prefix}/oauth2/consent?{args}'.format( dashboard_prefix=dashboard_prefix, args=args)) return oauth_server.create_authorization_response(grant_user=request.user)
def test_handler_api_gateway_base_path(mock_wsgi_app_file, mock_app, event, wsgi): event["headers"]["Host"] = "custom.domain.com" event["path"] = "/prod/some/path" os.environ.update(API_GATEWAY_BASE_PATH="prod") wsgi.handler(event, {}) assert wsgi.wsgi_app.last_environ == { "API_GATEWAY_AUTHORIZER": {"principalId": "wile_e_coyote"}, "CONTENT_LENGTH": "0", "CONTENT_TYPE": "", "HTTP_ACCEPT": "*/*", "HTTP_ACCEPT_ENCODING": "gzip, deflate", "HTTP_CACHE_CONTROL": "no-cache", "HTTP_CLOUDFRONT_FORWARDED_PROTO": "https", "HTTP_CLOUDFRONT_IS_DESKTOP_VIEWER": "true", "HTTP_CLOUDFRONT_IS_MOBILE_VIEWER": "false", "HTTP_CLOUDFRONT_IS_SMARTTV_VIEWER": "false", "HTTP_CLOUDFRONT_IS_TABLET_VIEWER": "false", "HTTP_CLOUDFRONT_VIEWER_COUNTRY": "DK", "HTTP_COOKIE": "CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001", "HTTP_HOST": "custom.domain.com", "HTTP_POSTMAN_TOKEN": "778a706e-d6b0-48d5-94dd-9e98c22f12fe", "HTTP_USER_AGENT": "PostmanRuntime/3.0.11-hotfix.2", "HTTP_VIA": "1.1 b8fa.cloudfront.net (CloudFront)", "HTTP_X_AMZN_TRACE_ID": "Root=1-58d534a5-1e7cffe644b086304dce7a1e", "HTTP_X_AMZ_CF_ID": "jx0Bvz9rm--Mz3wAj4i46FdOQQK3RHF4H0moJjBsQ==", "HTTP_X_FORWARDED_FOR": "76.20.166.147, 205.251.218.72", "HTTP_X_FORWARDED_PORT": "443", "HTTP_X_FORWARDED_PROTO": "https", "PATH_INFO": "/some/path", "QUERY_STRING": url_encode(event["queryStringParameters"]), "REMOTE_ADDR": "76.20.166.147", "REMOTE_USER": "******", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "/prod", "SERVER_NAME": "custom.domain.com", "SERVER_PORT": "443", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.errors": wsgi.wsgi_app.last_environ["wsgi.errors"], "wsgi.input": wsgi.wsgi_app.last_environ["wsgi.input"], "wsgi.multiprocess": False, "wsgi.multithread": False, "wsgi.run_once": False, "wsgi.url_scheme": "https", "wsgi.version": (1, 0), "context": {}, "event": event, }
def authenticate(self, state, requested_redirect_url: str, wsgi_environ: Mapping[str, object]) -> Identity: logger = self.logger.getChild('authenticate') req = Request(wsgi_environ, populate_request=False, shallow=True) args = cast(ImmutableMultiDict, req.args) try: code = args['code'] if args['state'] != state: raise AuthenticationError() except KeyError: raise AuthenticationError() data = url_encode({ 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': requested_redirect_url, 'grant_type': 'authorization_code', }).encode() try: response = urllib.request.urlopen(self.access_token_url, data) except urllib.error.HTTPError as e: logger.debug('Response of POST %s (with/ %r): %s\n%s', self.access_token_url, data, e.code, e.read()) raise assert isinstance(response, http.client.HTTPResponse), \ 'isinstance(response, {0.__module__}.{0.__qualname__})'.format( type(response)) headers = getattr(response, 'headers') # workaround mypy content_type = headers['Content-Type'] mimetype, options = parse_options_header(content_type) if mimetype == 'application/x-www-form-urlencoded': token_data = url_decode_stream(response) elif mimetype == 'application/json': charset = options.get('charset', 'utf-8') token_data = json.load( io.TextIOWrapper(cast(IO[bytes], response), encoding=charset)) else: response.close() raise AuthenticationError( '{} sent unsupported content type: {}'.format( self.access_token_url, content_type)) response.close() identity = self.determine_identity(token_data['access_token']) if self.authorize(identity): return identity raise AuthenticationError( self.unauthorized_identity_message_format.format(identity=identity, team=self))
def test_handler_custom_domain(mock_wsgi_app_file, mock_app, event): import wsgi # noqa: F811 event['headers']['Host'] = 'custom.domain.com' wsgi.handler(event, {}) assert wsgi.wsgi_app.last_environ == { 'API_GATEWAY_AUTHORIZER': {'principalId': 'wile_e_coyote'}, 'CONTENT_LENGTH': '0', 'CONTENT_TYPE': '', 'HTTP_ACCEPT': '*/*', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_CLOUDFRONT_FORWARDED_PROTO': 'https', 'HTTP_CLOUDFRONT_IS_DESKTOP_VIEWER': 'true', 'HTTP_CLOUDFRONT_IS_MOBILE_VIEWER': 'false', 'HTTP_CLOUDFRONT_IS_SMARTTV_VIEWER': 'false', 'HTTP_CLOUDFRONT_IS_TABLET_VIEWER': 'false', 'HTTP_CLOUDFRONT_VIEWER_COUNTRY': 'DK', 'HTTP_COOKIE': 'CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001', 'HTTP_HOST': 'custom.domain.com', 'HTTP_POSTMAN_TOKEN': '778a706e-d6b0-48d5-94dd-9e98c22f12fe', 'HTTP_USER_AGENT': 'PostmanRuntime/3.0.11-hotfix.2', 'HTTP_VIA': '1.1 b8fa.cloudfront.net (CloudFront)', 'HTTP_X_AMZN_TRACE_ID': 'Root=1-58d534a5-1e7cffe644b086304dce7a1e', 'HTTP_X_AMZ_CF_ID': 'jx0Bvz9rm--Mz3wAj4i46FdOQQK3RHF4H0moJjBsQ==', 'HTTP_X_FORWARDED_FOR': '76.20.166.147, 205.251.218.72', 'HTTP_X_FORWARDED_PORT': '443', 'HTTP_X_FORWARDED_PROTO': 'https', 'PATH_INFO': '/some/path', 'QUERY_STRING': url_encode(event['queryStringParameters']), 'REMOTE_ADDR': '76.20.166.147', 'REMOTE_USER': '******', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'custom.domain.com', 'SERVER_PORT': '443', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.errors': wsgi.wsgi_app.last_environ['wsgi.errors'], 'wsgi.input': wsgi.wsgi_app.last_environ['wsgi.input'], 'wsgi.multiprocess': False, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'https', 'wsgi.version': (1, 0), 'context': {}, 'event': event }
def account(self): ICP = request.env['ir.config_parameter'].sudo() params = { 'response_type': 'token', 'client_id': ICP.get_param('database.uuid') or '', 'state': json.dumps({ 'd': request.db, 'u': ICP.get_param('web.base.url') }), 'scope': 'userinfo', } return 'https://accounts.odoo.com/oauth2/auth?' + url_encode(params)
def stripe_return_from_onboarding(self, acquirer_id, menu_id): """ Redirect the user to the acquirer form of the onboarded Stripe account. The user is redirected to this route by Stripe after or during (if the user clicks on a dedicated button) the onboarding. :param str acquirer_id: The acquirer linked to the Stripe account being onboarded, as a `payment.acquirer` id :param str menu_id: The menu from which the user started the onboarding step, as an `ir.ui.menu` id """ stripe_acquirer = request.env['payment.acquirer'].browse(int(acquirer_id)) stripe_acquirer.company_id._mark_payment_onboarding_step_as_done() action = request.env.ref('payment_stripe.action_payment_acquirer_onboarding') get_params_string = url_encode({'action': action.id, 'id': acquirer_id, 'menu_id': menu_id}) return request.redirect(f'/web?#{get_params_string}')
def gen_survey_url(language_tag, survey_redirect_url): if not survey_redirect_url: raise BadRequest("Food Frequency Questionnaire Requires " "survey_redirect_url") regcode = SERVER_CONFIG["vioscreen_regcode"] url = SERVER_CONFIG["vioscreen_endpoint"] + "/remotelogin.aspx?%s" % \ url_encode( { b"Key": encrypt_key(secrets.token_hex(8), language_tag, survey_redirect_url), b"RegCode": regcode.encode() }, charset='utf-16' ) return url
def sync_status_name(self, journal, state, **kw): provider_identifier = kw.get('JSONcallBackStatus', '') # read action id and redirect to it with correct parameters if provider_identifier != '': action_id = request.env.ref('account_yodlee.yodlee_widget').id else: action_id = request.env.ref( 'account.open_account_journal_dashboard_kanban').id params = { 'action': action_id, 'state': state, 'journal_id': journal, 'provider_identifier': provider_identifier } url = '/web#' + url_encode(params) return werkzeug.utils.redirect(url, 303)
def send_forum_validation_email(self, forum_id=None): if not self.email: return False token = self._generate_forum_token(self.id, self.email) activation_template = self.env.ref('website_forum.validation_email') if activation_template: params = { 'token': token, 'id': self.id, 'email': self.email} if forum_id: params['forum_id'] = forum_id base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') token_url = base_url + '/forum/validate_email?%s' % urls.url_encode(params) activation_template.sudo().with_context(token_url=token_url).send_mail(self.id, force_send=True) return True
def _send_profile_validation_email(self, **kwargs): if not self.email: return False token = self._generate_profile_token(self.id, self.email) activation_template = self.env.ref('website_profile.validation_email') if activation_template: params = {'token': token, 'user_id': self.id, 'email': self.email} params.update(kwargs) token_url = self.get_base_url( ) + '/profile/validate_email?%s' % urls.url_encode(params) with self._cr.savepoint(): activation_template.sudo().with_context( token_url=token_url).send_mail(self.id, force_send=True, raise_exception=True) return True
def _build_url_w_params(url_string, query_params, remove_duplicates=True): """ Rebuild a string url based on url_string and correctly compute query parameters using those present in the url and those given by query_params. Having duplicates in the final url is optional. For example: * url_string = '/my?foo=bar&error=pay' * query_params = {'foo': 'bar2', 'alice': 'bob'} * if remove duplicates: result = '/my?foo=bar2&error=pay&alice=bob' * else: result = '/my?foo=bar&foo=bar2&error=pay&alice=bob' """ url = urls.url_parse(url_string) url_params = url.decode_query() if remove_duplicates: # convert to standard dict instead of werkzeug multidict to remove duplicates automatically url_params = url_params.to_dict() url_params.update(query_params) return url.replace(query=urls.url_encode(url_params)).to_url()
def build_url(self, **query_params): print >> open( '/tmp/log', 'a' ), "indico_search_json/engine.py/JSONSearchEngine.build_url query_params = %s" % query_params params = { 'isFrame': unicode(int(self.use_iframe)), 'autologin': unicode(int(not current_plugin.only_public)), 'showRefiners': '0' if self.obj_type == 'event' else '1', 'showDialogs': '0' if self.obj_type == 'event' else '1' } out = '{}?{}'.format(current_plugin.settings.get('search_url'), url_encode(dict(params, **query_params))) print >> open( '/tmp/log', 'a' ), "indico_search_json/engine.py/JSONSearchEngine.build_url out = %s" % out return out
def test_get_with_variables(self): self.authenticate("admin", "admin") query = """ query myQuery($companiesOnly: Boolean) { allPartners(companiesOnly: $companiesOnly) { name } } """ variables = {"companiesOnly": True} data = {"query": query, "variables": json.dumps(variables)} r = self.url_open("/graphql/demo?" + url_encode(data)) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self._check_all_partners(r.json()["data"]["allPartners"], companies_only=True)
def wrapper(*args, **kw): try: user_id = authenticate(roles).id # if not request.args.get('identity_confirmed') and \ # kwargs.get('confirm_identity'): # # verify that the user wants to continue with the currently # # authenticated user account # next_url = request.base_url + request.query_string + \ # '&identity_confirmed' # return redirect(url_for('confirm_identity', next=next_url)) except NotAuthenticatedError: if kwargs.get('allow_redirect'): dashboard_prefix = app.config.get("DASHBOARD_PREFIX") args = url_encode(dict(next=request.url)) return redirect('{dashboard_prefix}/login?{args}'.format( dashboard_prefix=dashboard_prefix, args=args)) raise try: result = fn(*args, **kw) # handle rendered responses which are strings if isinstance(result, str): result = make_response(result) # Update access cookie if present in request access_token = request.cookies.get('afterglow_core_access_token') if access_token: result = set_access_cookies(result, user_id, access_token=access_token) return result finally: # Close the possible data file db session; don't import at module # level because of a circular dependency from .resources import data_files # noinspection PyBroadException try: with data_files.data_file_thread_lock: data_files.data_file_engine[data_files.get_root(user_id), os.getpid()][1].remove() except Exception: pass
def login(): """ Login End Point. Authentication button points here. A `redirect` param can be used to define the redirect after login. http://www.pigeonpy.com/login?redirect=#!/buckets """ redirect_url = request.args.get('redirect', '/') params = { 'client_id': app.config['FORGE_CLIENT_ID'], 'redirect_uri': app.config['FORGE_CALLBACK'], 'scope': SCOPE_USER, 'state': redirect_url, 'response_type': 'code' } url = 'https://developer.api.autodesk.com/authentication/v1/authorize?{}'.format( url_encode(params)) return redirect(url, code=303)
def build_falcon(params: Dict[str, Any]) -> falcon.Request: """ Builds falcon.request.Request :param params: :return: """ return falcon.Request({ "QUERY_STRING": url_encode(params), # avoid errors while printing "wsgi.input": None, "wsgi.errors": None, "wsgi.url_scheme": "https://", "REQUEST_METHOD": "GET", "PATH_INFO": "test", "SERVER_NAME": "qvaltests", "SERVER_PORT": "433", })
def url_for_author_search(forename: str, surname: str) -> str: # If we are in an archive-specific context, we want to preserve that # when generating URLs for author queries in search results. archives = request.view_args.get('archives') if archives: target = url_for('ui.search', archives=archives) else: target = url_for('ui.search') parts = url_parse(target) forename_part = ' '.join([part[0] for part in forename.split()]) name = f'{surname}, {forename_part}' if forename_part else surname parts = parts.replace(query=url_encode({ 'searchtype': 'author', 'query': name })) url: str = url_unparse(parts) return url
def facebook_account_callback(self, access_token, is_extended_token=False): if not request.env.user.has_group('social.group_social_manager'): return 'unauthorized' """ Facebook returns to the callback URL with all its own arguments as hash parameters. We use this very handy 'fragment_to_query_string' decorator to convert them to server readable parameters. """ media = request.env.ref('social_facebook.social_media_facebook') self._create_facebook_accounts(access_token, media, is_extended_token) url_params = { 'action': request.env.ref('social.action_social_stream_post').id, 'view_type': 'kanban', 'model': 'social.stream.post', } url = '/web?#%s' % url_encode(url_params) return werkzeug.utils.redirect(url)
def recaptcha_html(self, public_key): html = current_app.config.get("RECAPTCHA_HTML") if html: return Markup(html) params = current_app.config.get("RECAPTCHA_PARAMETERS") script = current_app.config.get("RECAPTCHA_SCRIPT") if not script: script = RECAPTCHA_SCRIPT_DEFAULT if params: script += "?" + url_encode(params) attrs = current_app.config.get("RECAPTCHA_DATA_ATTRS", {}) attrs["sitekey"] = public_key snippet = " ".join(f'data-{k}="{attrs[k]}"' for k in attrs) div_class = current_app.config.get("RECAPTCHA_DIV_CLASS") if not div_class: div_class = RECAPTCHA_DIV_CLASS_DEFAULT return Markup(RECAPTCHA_TEMPLATE % (script, div_class, snippet))
def dispatch_url(self, url_string): url, url_adapter, query_args = self.parse_url(url_string) try: endpoint, kwargs = url_adapter.match() except NotFound: raise NotSupported(url_string) except RequestRedirect as e: new_url = "{0.new_url}?{1}".format(e, url_encode(query_args)) return self.dispatch_url(new_url) try: handler = import_string(endpoint) request = Request(url=url, args=query_args) return handler(request, **kwargs) except RequestRedirect as e: return self.dispatch_url(e.new_url)
def _compute_share_link(self): for record in self: target_url = '{base}/coupon/{code}?{query}'.format( base=record.website_id.get_base_url(), code=record.promo_code, query=url_encode({'r': record.redirect}), ) if record.env.context.get('use_short_link'): tracker = self.env['link.tracker'].search( [('url', '=', target_url)], limit=1) if not tracker: tracker = self.env['link.tracker'].create( {'url': target_url}) record.share_link = tracker.short_url else: record.share_link = target_url
def create(self, vals): if vals.get('user_id'): user = self.env['res.users'].browse(vals['user_id']) vals.update(self._sync_user(user, bool(vals.get('image_1920')))) vals['name'] = vals.get('name', user.name) employee = super(HrEmployeePrivate, self).create(vals) url = '/web#%s' % url_encode({ 'action': 'hr.plan_wizard_action', 'active_id': employee.id, 'active_model': 'hr.employee', 'menu_id': self.env.ref('hr.menu_hr_root').id, }) employee._message_log(body=_('<b>Congratulations!</b> May I recommend you to setup an <a href="%s">onboarding plan?</a>') % (url)) if employee.department_id: self.env['mail.channel'].sudo().search([ ('subscription_department_ids', 'in', employee.department_id.id) ])._subscribe_users() return employee