def authorize(self, callback=None, extra_params={}): """Returns a redirect response to the remote authorization URL with the signed callback given. The callback must be `None` in which case the application will most likely switch to PIN based authentication or use a remotely stored callback URL. Alternatively it's an URL on the system that has to be decorated as :meth:`authorized_handler`. You may also pass extra parameters via the dictionary extra_params (e.g. state for google oauth2) """ if self.request_token_url: token = self.generate_request_token(callback)[0] url = '%s?oauth_token=%s' % (self.expand_url( self.authorize_url), url_quote(token)) else: assert callback is not None, 'Callback is required OAuth2' # This is for things like facebook's oauth. Since we need the # callback for the access_token_url we need to keep it in the # session. params = dict(self.request_token_params) params['redirect_uri'] = callback params['client_id'] = self.consumer_key params['response_type'] = 'code' if extra_params: params.update(extra_params) session[self.name + '_oauthredir'] = callback url = add_query(self.expand_url(self.authorize_url), params) return redirect(url)
def authorize(self, callback=None): """Returns a redirect response to the remote authorization URL with the signed callback given. The callback must be `None` in which case the application will most likely switch to PIN based authentication or use a remotely stored callback URL. Alternatively it's an URL on the system that has to be decorated as :meth:`authorized_handler`. """ if self.request_token_url: token = self.generate_request_token(callback)[0] url = '%s?oauth_token=%s' % (self.expand_url( self.authorize_url), url_quote(token)) #print "uuuurrrrrllllllll"+str(url) else: assert callback is not None, 'Callback is required OAuth2' # This is for things like facebook's oauth. Since we need the # callback for the access_token_url we need to keep it in the # session. #callback="http://sirius.unbxdapi.com/oauth2callback" params = dict(self.request_token_params) params['redirect_uri'] = callback params['client_id'] = self.consumer_key params['response_type'] = 'code' session[self.name + '_oauthredir'] = callback url = add_query(self.expand_url(self.authorize_url), params) print "###############" print url print params['redirect_uri'] print session[self.name + '_oauthredir'] print session print "###############" return redirect(url)
def load_zine_reddit(): """Load the zine reddit.""" reddit_url = 'http://www.reddit.com' reddit_zine_url = reddit_url + '/r/zine' response = open_url(reddit_zine_url + '.json') try: data = load_json(response.data) finally: response.close() result = [] for item in islice(data['data']['children'], 20): d = item['data'] if not d['url'].startswith("http"): d['url'] = reddit_url + d['url'] result.append({ 'author': d['author'], 'created': datetime.utcfromtimestamp(d['created']), 'score': d['score'], 'title': d['title'], 'comments': d['num_comments'], 'url': d['url'], 'domain': d['domain'], 'author_url': reddit_url + '/user/%s/' % url_quote(d['author']), 'comment_url': '%s/comments/%s' % (reddit_zine_url, d['id']) }) return result
def render(title): """Serve a thumbnail or otherwise rendered content.""" p = page.get_page(request, title) try: cache_filename, cache_mime = p.render_mime() render_func = p.render_cache if not current_app.cache: raise NotImplementedError() except (AttributeError, NotImplementedError): return download(title) cache_key = '/render/%s_%s' % (werkzeug.url_quote(title, safe=''), cache_filename) rev, dt, author, comment = current_app.storage.page_meta(title) cache_file = current_app.cache.open(cache_key, 'r') if (cache_file and dt > cache_file.modified) or not cache_file: cache_file = current_app.cache.open(cache_key, 'w') try: result_file = render_func(cache_file) except error.UnsupportedMediaTypeErr: return download(title) else: cache_file = current_app.cache.open(cache_key, 'r') resp = response.response(request, title, werkzeug.wrap_file(request.environ, cache_file), '/render', cache_mime, size=cache_file.length) resp.direct_passthrough = True return resp
def ogone_s2s_create(self, **post): error = '' acq = request.env['payment.acquirer'].browse( int(post.get('acquirer_id'))) try: token = acq.s2s_process(post) except Exception as e: # synthax error: 'CHECK ERROR: |Not a valid date\n\n50001111: None' token = False error = str(e).splitlines()[0].split('|')[-1] or '' if token and post.get('verify_validity'): baseurl = request.env['ir.config_parameter'].sudo().get_param( 'web.base.url') params = { 'accept_url': baseurl + '/payment/ogone/validate/accept', 'decline_url': baseurl + '/payment/ogone/validate/decline', 'exception_url': baseurl + '/payment/ogone/validate/exception', 'return_url': post.get('return_url', baseurl) } tx = token.validate(**params) if tx and tx.html_3ds: return tx.html_3ds return werkzeug.utils.redirect( post.get('return_url', '/') + (error and '#error=%s' % werkzeug.url_quote(error) or ''))
def url_for(endpoint, **values): """Returns a URL for a given endpoint with some interpolation.""" external = values.pop('_external', False) if hasattr(endpoint, 'get_url_values'): endpoint, values = endpoint.get_url_values(**values) request = Request.current anchor = values.pop('_anchor', None) assert request is not None, 'no active request' for endpoint_choice in iter_endpoint_choices(endpoint, request.endpoint): real_values = inject_lang_code(request, endpoint_choice, values) if real_values is None: continue try: url = request.url_adapter.build(endpoint_choice, real_values, force_external=external) except BuildError: continue view = get_view(endpoint) if is_exchange_token_protected(view): xt = get_exchange_token(request) url = '%s%s_xt=%s' % (url, '?' in url and '&' or '?', xt) if anchor is not None: url += '#' + url_quote(anchor) return url raise BuildError(endpoint, values, 'GET')
def authorize(self, callback=None): """ Returns a redirect response to the remote authorization URL with the signed callback given. """ if self.request_token_url: token = self.generate_request_token(callback)[0] url = '%s?oauth_token=%s' % (self.expand_url( self.authorize_url), url_quote(token)) else: assert callback is not None, 'Callback is required OAuth2' params = dict(self.request_token_params) client = self.make_client() scope = params.pop('scope') if isinstance(scope, str): # oauthlib need unicode scope = _encode(scope, self.encoding) session['%s_oauthredir' % self.name] = callback url = client.prepare_request_uri(self.expand_url( self.authorize_url), redirect_uri=callback, scope=scope, **params) return redirect(url)
def encode_rfc2231(value, coding='UTF-8', lang=''): """ Encode a value according to RFC2231/5987. :param value: the value to encode. must be either unicode or encoded in <coding>. :param coding: the coding (charset) to use. it is a good idea to use 'UTF-8'. :param lang: the language to use. defaults to empty string (no language given). """ return "{0}'{1}'{2}".format(coding, lang, url_quote(value, charset=coding))
def _compute_image_src(self): for attachment in self: if attachment.mimetype not in ['image/gif', 'image/jpe', 'image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/svg+xml']: attachment.image_src = False else: attachment.image_src = attachment.url or '/web/image/%s/%s' % ( attachment.id, url_quote(attachment.name or ''), )
def response(self, request, title, content, etag='', mime='text/html', rev=None, size=None): """Create a WikiResponse for a page.""" response = WikiResponse(content, mimetype=mime) if rev is None: inode, _size, mtime = self.storage.page_file_meta(title) response.set_etag(u'%s/%s/%d-%d' % (etag, werkzeug.url_quote(title), inode, mtime)) if size == -1: size = _size else: response.set_etag(u'%s/%s/%s' % (etag, werkzeug.url_quote(title), rev)) if size: response.content_length = size response.make_conditional(request) return response
def authorize(self, callback=None, state=None, **kwargs): """ Returns a redirect response to the remote authorization URL with the signed callback given. :param callback: a redirect url for the callback :param state: an optional value to embed in the OAuth request. Use this if you want to pass around application state (e.g. CSRF tokens). :param kwargs: add optional key/value pairs to the query string """ params = dict(self.request_token_params) or {} params.update(**kwargs) if self.request_token_url: token = self.generate_request_token(callback)[0] url = '%s?oauth_token=%s' % ( self.expand_url(self.authorize_url), url_quote(token) ) if params: url += '&' + url_encode(params) else: assert callback is not None, 'Callback is required for OAuth2' client = self.make_client() if 'scope' in params: scope = params.pop('scope') else: scope = None if isinstance(scope, str): # oauthlib need unicode scope = _encode(scope, self.encoding) if 'state' in params: if not state: state = params.pop('state') else: # remove state in params params.pop('state') if callable(state): # state can be function for generate a random string state = state() session['%s_oauthredir' % self.name] = callback url = client.prepare_request_uri( self.expand_url(self.authorize_url), redirect_uri=callback, scope=scope, state=state, **params ) return redirect(url)
def href(*args, **kw): """ Simple function for URL generation. Position arguments are used for the URL path and keyword arguments are used for the url parameters. """ result = [(request and request.script_root or '') + '/'] for idx, arg in enumerate(args): result.append((idx and '/' or '') + url_quote(arg)) if kw: result.append('?' + url_encode(kw)) return ''.join(result)
def authorize(self, callback=None): """Returns a redirect response to the remote authorization URL with the signed callback given. The callback must be `None` in which case the application will most likely switch to PIN based authentication or use a remotely stored callback URL. Alternatively it's an URL on the system that has to be decorated as :meth:`authorized_handler`. """ token = self.generate_request_token(callback)[0] url = '%s?oauth_token=%s' % (self.expand_url( self.authorize_url), url_quote(token)) return redirect(url)
def response(request, title, content, etag='', mime='text/html', rev=None, size=None): """Create a WikiResponse for a page.""" response = WikiResponse(content, content_type=mime) if rev is None: rev, date, author, comment = current_app.storage.page_meta(title) response.set_etag('%s/%s/%d-%s' % (etag, url_quote(title), rev, date.isoformat())) # add a modified date for better conditional requests response.last_modified = date else: response.set_etag('%s/%s/%s' % (etag, url_quote(title), rev)) if size: response.content_length = size response.make_conditional(request) return response
def ogone_s2s_create(self, **post): error = '' acq = request.env['payment.acquirer'].browse( int(post.get('acquirer_id'))) try: acq.s2s_process(post) except Exception as e: # synthax error: 'CHECK ERROR: |Not a valid date\n\n50001111: None' error = str(e).splitlines()[0].split('|')[-1] or '' return werkzeug.utils.redirect( post.get('return_url', '/') + (error and '#error=%s' % werkzeug.url_quote(error) or ''))
def handle_login(request, userobj=None, username=None, password=None, attended=True, openid_identifier=None, stage=None): """ Process a 'login' request by going through the configured authentication methods in turn. The passable keyword arguments are explained in more detail at the top of this file. """ params = { 'username': username, 'password': password, 'attended': attended, 'openid_identifier': openid_identifier, 'multistage': (stage and True) or None } for authmethod in request.cfg.auth: #logging.info('CURRENT STAGE: %s, %s' % (params, authmethod.name)) if stage and authmethod.name != stage: continue if openid_identifier and authmethod.name != 'openidqw': continue ret = authmethod.login(request, userobj, **params) userobj = ret.user_obj cont = ret.continue_flag if stage: stage = None del params['multistage'] if ret.multistage: request._login_multistage = ret.multistage request._login_multistage_name = authmethod.name return userobj if ret.redirect_to: nextstage = get_multistage_continuation_url( request, authmethod.name) url = ret.redirect_to url = url.replace('%return_form', url_quote_plus(nextstage)) url = url.replace('%return', url_quote(nextstage)) abort(redirect(url)) msg = ret.message if msg and not msg in request._login_messages: request._login_messages.append(msg) if not cont: break return userobj
def _title_to_file(self, title): title = unicode(title).strip() filename = werkzeug.url_quote(title, safe='') # Escape special windows filenames and dot files _windows_device_files = ('CON', 'AUX', 'COM1', 'COM2', 'COM3', 'COM4', 'LPT1', 'LPT2', 'LPT3', 'PRN', 'NUL') if (filename.split('.')[0].upper() in _windows_device_files or filename.startswith('_') or filename.startswith('.')): filename = '_' + filename if page.page_mime(title) == 'text/x-wiki' and self.extension: filename += self.extension return os.path.join(self.repo_prefix, filename)
def url_for(self, endpoint, _full=False, _method=None, _anchor=None, **kwargs): """Builds and returns a URL for a named :class:`Rule`. For example, if you have these rules registered in the application: .. code-block:: Rule('/', endoint='home/main' handler='handlers.MyHomeHandler') Rule('/wiki', endoint='wiki/start' handler='handlers.WikiHandler') Here are some examples of how to generate URLs for them: >>> url = url_for('home/main') >>> '/' >>> url = url_for('home/main', _full=True) >>> 'http://localhost:8080/' >>> url = url_for('wiki/start') >>> '/wiki' >>> url = url_for('wiki/start', _full=True) >>> 'http://localhost:8080/wiki' >>> url = url_for('wiki/start', _full=True, _anchor='my-heading') >>> 'http://localhost:8080/wiki#my-heading' :param endpoint: The rule endpoint. :param _full: If True, returns an absolute URL. Otherwise, returns a relative one. :param _method: The rule request method, in case there are different rules for different request methods. :param _anchor: An anchor to add to the end of the URL. :param kwargs: Keyword arguments to build the URL. :return: An absolute or relative URL. """ url = self.url_adapter.build(endpoint, force_external=_full, method=_method, values=kwargs) if _anchor: url += '#' + url_quote(_anchor) return url
class OgoneController(http.Controller): _accept_url = '/payment/ogone/test/accept' _decline_url = '/payment/ogone/test/decline' _exception_url = '/payment/ogone/test/exception' _cancel_url = '/payment/ogone/test/cancel' @http.route([ '/payment/ogone/accept', '/payment/ogone/test/accept', '/payment/ogone/decline', '/payment/ogone/test/decline', '/payment/ogone/exception', '/payment/ogone/test/exception', '/payment/ogone/cancel', '/payment/ogone/test/cancel', ], type='http', auth='none') def ogone_form_feedback(self, **post): """ Ogone contacts using GET, at least for accept """ _logger.info('Ogone: entering form_feedback with post data %s', pprint.pformat(post)) # debug request.env['payment.transaction'].sudo().form_feedback(post, 'ogone') return werkzeug.utils.redirect(post.pop('return_url', '/')) @http.route(['/payment/ogone/s2s/create_json'], type='json', auth='public', csrf=False) def ogone_s2s_create_json(self, **kwargs): new_id = request.env['payment.acquirer'].browse( int(kwargs.get('acquirer_id'))).s2s_process(kwargs) return new_id @http.route(['/payment/ogone/s2s/create'], type='http', auth='public', methods=["POST"], csrf=False) def ogone_s2s_create(self, **post): error = '' acq = request.env['payment.acquirer'].browse( int(post.get('acquirer_id'))) try: acq.s2s_process(post) except Exception, e: # synthax error: 'CHECK ERROR: |Not a valid date\n\n50001111: None' error = e.message.splitlines()[0].split('|')[-1] or '' return werkzeug.utils.redirect( post.get('return_url', '/') + (error and '#error=%s' % werkzeug.url_quote(error) or ''))
def _load_xsd_files(cr, registry, url): fname = url.split('/')[-1] try: response = requests.get(url, timeout=10) response.raise_for_status() except requests.exceptions.HTTPError: logging.getLogger(__name__).info( 'I cannot connect with the given URL.') return '' try: res = objectify.fromstring(response.content) except etree.XMLSyntaxError as e: logging.getLogger(__name__).info( 'You are trying to load an invalid xsd file.\n%s', e) return '' namespace = {'xs': 'http://www.w3.org/2001/XMLSchema'} if fname == 'cfdv33.xsd': # This is the xsd root res = _load_xsd_complements(cr, registry, res) sub_urls = res.xpath('//xs:import', namespaces=namespace) for s_url in sub_urls: s_url_catch = _load_xsd_files(cr, registry, s_url.get('schemaLocation')) s_url.attrib['schemaLocation'] = url_quote(s_url_catch) try: xsd_string = etree.tostring(res, pretty_print=True) except etree.XMLSyntaxError: logging.getLogger(__name__).info('XSD file downloaded is not valid') return '' env = api.Environment(cr, SUPERUSER_ID, {}) xsd_fname = 'xsd_cached_%s' % fname.replace('.', '_') attachment = env.ref('l10n_mx_edi.%s' % xsd_fname, False) filestore = tools.config.filestore(cr.dbname) if attachment: return join(filestore, attachment.store_fname) attachment = env['ir.attachment'].create({ 'name': xsd_fname, 'datas_fname': fname, 'datas': base64.encodestring(xsd_string), }) # Forcing the triggering of the store_fname attachment._inverse_datas() cr.execute( """INSERT INTO ir_model_data (name, res_id, module, model) VALUES (%s, %s, 'l10n_mx_edi', 'ir.attachment')""", (xsd_fname, attachment.id)) return join(filestore, attachment.store_fname)
def handle_login(userobj, **kw): """ Process a 'login' request by going through the configured authentication methods in turn. The passable keyword arguments are explained in more detail at the top of this file. """ stage = kw.get('stage') params = { 'username': kw.get('login_username'), 'password': kw.get('login_password'), 'openid': kw.get('login_openid'), 'multistage': (stage and True) or None, 'attended': True } # add the other parameters from the form for param in kw.keys(): params[param] = kw.get(param) for authmethod in app.cfg.auth: if stage and authmethod.name != stage: continue ret = authmethod.login(userobj, **params) userobj = ret.user_obj cont = ret.continue_flag if stage: stage = None del params['multistage'] if ret.multistage: flaskg._login_multistage = ret.multistage flaskg._login_multistage_name = authmethod.name return userobj if ret.redirect_to: nextstage = get_multistage_continuation_url(authmethod.name) url = ret.redirect_to url = url.replace('%return_form', url_quote_plus(nextstage)) url = url.replace('%return', url_quote(nextstage)) abort(redirect(url)) msg = ret.message if msg and not msg in flaskg._login_messages: flaskg._login_messages.append(msg) if not cont: break return userobj
def _title_to_file(self, title): """ Modified escaping allowing (some) slashes and spaces. If the entry is a directory, use an index file. """ title = unicode(title).strip() escaped = werkzeug.url_quote(title, safe='/ ') escaped = self.periods_re.sub('%2E', escaped) escaped = self.slashes_re.sub('%2F', escaped) path = os.path.join(self.repo_prefix, escaped) if os.path.isdir(os.path.join(self.repo_path, path)): path = os.path.join(path, self.index) if page.page_mime(title) == 'text/x-wiki' and self.extension: path += self.extension return path
def join_wiki(wikiurl, wikitail): """ Add a (url_quoted) page name to an interwiki url. Note: We can't know what kind of URL quoting a remote wiki expects. We just use a utf-8 encoded string with standard URL quoting. @param wikiurl: wiki url, maybe including a $PAGE placeholder @param wikitail: page name @rtype: string @return: generated URL of the page in the other wiki """ wikitail = url_quote(wikitail, charset=config.charset, safe='/') if '$PAGE' in wikiurl: return wikiurl.replace('$PAGE', wikitail) else: return wikiurl + wikitail
def build(self, request, name, kwargs): """Returns a URL for a named :class:`Rule`. This is the central place to build URLs for an app. It is used by :meth:`RequestHandler.url_for`, which conveniently pass the request object so you don't have to. :param request: The current request object. :param name: The rule name. :param kwargs: Values to build the URL. All variables not set in the rule default values must be passed and must conform to the format set in the rule. Extra keywords are appended as query arguments. A few keywords have special meaning: - **_full**: If True, builds an absolute URL. - **_method**: Uses a rule defined to handle specific request methods, if any are defined. - **_scheme**: URL scheme, e.g., `http` or `https`. If defined, an absolute URL is always returned. - **_netloc**: Network location, e.g., `www.google.com`. If defined, an absolute URL is always returned. - **_anchor**: If set, appends an anchor to generated URL. :returns: An absolute or relative URL. """ full = kwargs.pop('_full', False) method = kwargs.pop('_method', None) scheme = kwargs.pop('_scheme', None) netloc = kwargs.pop('_netloc', None) anchor = kwargs.pop('_anchor', None) if scheme or netloc: full = False url = request.url_adapter.build(name, values=kwargs, method=method, force_external=full) if scheme or netloc: url = '%s://%s%s' % (scheme or 'http', netloc or request.host, url) if anchor: url += '#%s' % url_quote(anchor) return url
def to_filename(request): secure = url_quote(request.full_path[1:].replace('/', ' ').replace( '?', '_').replace('=', '-').replace('&', '_'), safe=' ') key = hashlib.sha256(namespace + secure).hexdigest() file_name_old = '{}_{}.json'.format(secure[:min(128, len(secure))], key) file_name = '{}_{}.json'.format( secure[:min(64, len(secure))], key ) # use a shorter filename for restCache, to avoid file system errors with too long file names return { "file_name_128": file_name_old.replace( '%', '_' ), # file_name_128 = file name with 128 characters in front of the hash "file_name_64": file_name.replace( '%', '_' ) # file_name_64 = file name with 64 characters in front of the hash }
def path_func(page_name): """If one uses wiki-links they are relative to the blog root.""" root = get_application().cfg['blog_url'] if not root.endswith('/'): root += '/' return urljoin(root, url_quote(page_name))
def _encode(self, key): """ we need to get rid of slashes in revids because we put them into URLs and it would confuse the URL routing. """ return url_quote(key, safe='')
def path_func(page_name): root = get_request().script_root if not root.endswith('/'): root += '/' return urljoin(root, url_quote(page_name))
def save(title): _ = current_app.gettext page.check_lock(current_app, title) url = current_app.get_url(title) if request.form.get('cancel'): if title not in current_app.storage: url = current_app.get_url(current_app.front_page) if request.form.get('preview'): text = request.form.get("text") if text is not None: lines = text.split('\n') else: lines = [werkzeug.html.p(werkzeug.html( _('No preview for binaries.')))] return edit(title, preview=lines) elif request.form.get('save'): if captcha and current_app.recaptcha_private_key: resp = captcha.submit( request.form.get('recaptcha_challenge_field', ''), request.form.get('recaptcha_response_field', ''), current_app.recaptcha_private_key, request.remote_addr) if not resp.is_valid: text = request.form.get("text", '') return edit(request, title, preview=text.split('\n'), captcha_error=response.error_code) comment = request.form.get("comment", "") if 'href="' in comment or 'http:' in comment: raise error.ForbiddenErr() author = request.get_author() text = request.form.get("text") try: parent = int(request.form.get("parent")) except (ValueError, TypeError): parent = None p = page.get_page(request, title) if text is not None: if title == current_app.locked_page: for link, label in p.extract_links(text): if title == link: raise error.ForbiddenErr( _("This page is locked.")) if text.strip() == '': current_app.storage.delete_page(title, author, comment) url = current_app.get_url(current_app.front_page) else: current_app.storage.save_text(title, text, author, comment, parent) else: text = '' upload = request.files.get('data') if upload and upload.stream and upload.filename: f = upload.stream current_app.storage.save_data(title, f.read(), author, comment, parent) else: current_app.storage.delete_page(title, author, comment) url = current_app.get_url(current_app.front_page) current_app.index.update(current_app) resp = response.redirect(url, code=303) resp.set_cookie('author', werkzeug.url_quote(request.get_author()), max_age=604800) return resp
def pypi(self): return 'http://pypi.python.org/pypi/%s' % url_quote(self.name)