def __call__(self, environ, start_response): req = Request(environ) if self._no_redirect_re.match(environ['PATH_INFO']): return req.get_response(self.app)(environ, start_response) resp = None try: request_uri = req.url request_uri.decode('ascii') except UnicodeError: resp = exc.HTTPNotFound() secure = req.url.startswith('https://') srv_path = req.url.split('://', 1)[-1] # This SFUSER check is SourceForge-specific (to require all logged-in users to use https) # BUT has the additional affect of not forcing SSL for regular Allura instances # This is important for local development, at least. When we remove SFUSER (perhaps by requiring SSL everywhere), # we can use `no_redirect.pattern = .` for local development to work without SSL force_ssl = req.cookies.get('SFUSER') or self._force_ssl_re.match( environ['PATH_INFO']) if not secure and force_ssl: resp = exc.HTTPFound(location='https://' + srv_path) elif secure and not force_ssl: resp = exc.HTTPFound(location='http://' + srv_path) if not resp: resp = self.app return resp(environ, start_response)
def __call__(self, environ, start_response): req = Request(environ) if self._no_redirect_re.match(environ['PATH_INFO']): return req.get_response(self.app)(environ, start_response) resp = None try: request_uri = req.url request_uri.decode('ascii') except UnicodeError: resp = exc.HTTPNotFound() secure = req.url.startswith('https://') srv_path = req.url.split('://', 1)[-1] # allura-loggedin is a non-secure cookie as a flag to know that the user has a session over on https force_ssl = (self._force_ssl_logged_in and req.cookies.get('allura-loggedin')) \ or self._force_ssl_re.match(environ['PATH_INFO']) if req.environ.get('pylons.original_request'): # if an error occurs, then /error/document is fetched (denoted by pylons.original_request) # and we don't want to do any redirects within that sub-request pass elif not secure and force_ssl: resp = exc.HTTPFound(location='https://' + srv_path) elif secure and not force_ssl: resp = exc.HTTPFound(location='http://' + srv_path) if not resp: resp = self.app return resp(environ, start_response)
def application(environ, start_response): req = webob.Request(environ) resp = webob.Response() if req.method == 'GET': filename = req.path_info.strip('/') or 'index.html' if filename in ('302',): redirect = req.params['redirect'] resp = exc.HTTPFound(location=redirect) return resp(environ, start_response) if filename.isdigit(): resp.status = filename filename = 'index.html' filename = os.path.join(files, 'html', filename) if os.path.isfile(filename): kw = dict(message=req.params.get('message', ''), redirect=req.params.get('redirect', '')) resp.unicode_body = u(open(filename).read()) % kw _, ext = os.path.splitext(filename) if ext == '.html': resp.content_type = 'text/html' elif ext == '.js': resp.content_type = 'text/javascript' elif ext == '.json': resp.content_type = 'application/json' else: redirect = req.params.get('redirect', '') if redirect: resp = exc.HTTPFound(location=redirect) else: resp.body = req.body return resp(environ, start_response)
def save_file(self, req, filename): content = req.POST['content'] f = open(filename, 'wb') f.write(content) f.close() return exc.HTTPFound( location=self.edit_url(req, filename))
def do_capture(self, req): """ Take a new image with the camera and add it to the library """ self.library.capture() raise exc.HTTPFound( location=self.router.path_for('template', page='library'))
def process(self, req): wll = self._create_wll() action = req.POST['action'] finished = False if action == 'delauth': user = wll.processToken(req.session['user_token']) del req.session['user_token'] consenttoken = wll.processConsent(req.POST) finished = True else: consenttoken = None user = wll.processLogin(req.POST) if not self.offers: finished = True if not finished: req.session['user_token'] = user.getToken() req.session.save() return exc.HTTPFound(location=wll.getConsentUrl(self.offers)) profile = {} profile['providerName'] = 'Live' profile['identifier'] = 'http://live.com/%s' % user.getId() result_data = {'status': 'ok', 'profile': profile} if consenttoken: result_data['credentials'] = {'consentToken': consenttoken.getToken()} return self._success_redirect(result_data, req.session['end_point'])
def login(self, req): end_point = req.POST['end_point'] # Create the consumer and client, make the request client = oauth.Client(self._consumer) params = {'oauth_callback': req.link('process', qualified=True)} # We go through some shennanigans here to specify a callback url request = oauth.Request.from_consumer_and_token(self._consumer, http_url=REQUEST_URL, parameters=params) request.sign_request(self._sigmethod, self._consumer, None) resp, content = httplib2.Http.request(client, REQUEST_URL, method='GET', headers=request.to_header()) if resp['status'] != '200': log.debug("Identi.ca oauth failed: %r %r", resp, content) return self._error_redirect(3, end_point) request_token = oauth.Token.from_string(content) req.session['token'] = content req.session['end_point'] = end_point req.session.save() # Send the user to identica to authorize us request = oauth.Request.from_token_and_callback(token=request_token, http_url=AUTHORIZE_URL) return exc.HTTPFound(location=request.to_url())
def do_delete(self, req, image): """ Delete the selected images from library """ self.library.remove(image) raise exc.HTTPFound( location=self.router.path_for('template', page='library'))
def dispatch(self, request, response): """Main routing method called by every request.""" # TODO(user): memoize this and override match, so that we don't # have to rematch again in the super default_dispatcher call. route, unused_args, unused_kwargs = self.match(request) # SSL redirect handling. Must come before auth handling. require_secure = getattr(route, 'require_secure', False) if require_secure and not request.scheme == 'https': redirect_url = 'https://{}{}'.format(request.server_name, request.path_qs) raise webob_exceptions.HTTPMovedPermanently(location=redirect_url) # Maybe redirect to login or raise 403 Forbidden for non-admins. require_login = getattr(route, 'require_login', False) require_admin = getattr(route, 'require_admin', False) if require_login or require_admin: user = users.get_current_user(oauth_scopes=users.OAUTH_SCOPES) if not user: login_url = users.create_login_url(dest_url=request.url) raise webob_exceptions.HTTPFound(location=login_url) elif require_admin and not user.is_admin: raise webob_exceptions.HTTPForbidden return super(_RouterWithMiddleware, self).default_dispatcher(request, response)
def _auth(rej, res): try: if creds == Nothing: # if credentials not in cache, # redirect to the flow authorize URL (step 1 of OAuth dance) # rej( exc.HTTPFound( location=str(flow.step1_get_authorize_url()))) else: # if credentials are in cache, # resolve to (http, authurl, req) where # - http is an httplib2 client authorized with the credentials. # - authurl is the flow authorize URL # # Note that oauth2client.client.AccessTokenRefreshError should be # caught by downstream tasks where the authorized http is used, and # redirect to authurl. This is less than ideal. # res((authorized_http(creds.value), flow.step1_get_authorize_url(), req)) except Exception as e: rej(err.wrap(e))
def __call__(self, environ, start_response): request = Request(environ) path_info = request.path_info route_match = routing.mapping.match(path_info) if route_match is None: # If there's an equivalent URL that ends with /, redirect # to that. if not path_info.endswith('/') \ and request.method == 'GET' \ and routing.mapping.match(path_info + '/'): new_path_info = path_info + '/' if request.GET: new_path_info = '%s?%s' % (new_path_info, urllib.urlencode(request.GET)) redirect = exc.HTTPFound(location=new_path_info) return request.get_response(redirect)(environ, start_response) # Return a 404 response = util.generate_404_response(request, routing, environ, self.staticdirector) return response(environ, start_response) controller = load_controller(route_match['controller']) request.start_response = start_response request.matchdict = route_match request.urlgen = routes.URLGenerator(routing.mapping, environ) request.staticdirect = self.staticdirector return controller(request)(environ, start_response)
def do_reset(self, req): """ Reset all settings to their defaults """ self.library.camera_reset() self.flashes.append('Camera settings reset to defaults') raise exc.HTTPFound( location=self.router.path_for('template', page='library'))
def do_send(self, req): """ Send the library as a set of attachments to an email """ self.library.send() self.flashes.append('Email sent to %s' % library.email) raise exc.HTTPFound( location=self.router.path_for('template', page='library'))
def do_logout(self, req): """ Clear the library of all images, reset all settings """ self.library.clear() self.library.user_reset() self.library.camera_reset() raise exc.HTTPFound( location=self.router.path_for('template', page='settings'))
def application(environ, start_response): req = Request(environ) if req.path_info == '/redirect': req.path_info = '/path' resp = exc.HTTPFound(location=req.path) else: resp = Response() resp.body = '<html><body><a href="%s">link</a></body></html>' % req.path return resp(environ, start_response)
def login(self, req): req.session['end_point'] = req.POST['end_point'] req.session.save() scope = req.POST.get('scope', '') return_to = self._get_return_to(req) url = req.link(AUTHORIZE_URL, client_id=self.app_id, scope=scope, redirect_uri=return_to) return exc.HTTPFound(location=url)
def new_controller_func(request, *args, **kwargs): if not request.user or not request.user.get('status') == u'active': # TODO: Indicate to the user that they were redirected # here because an *active* user is required. return exc.HTTPFound( location="%s?next=%s" % ( request.urlgen("mediagoblin.auth.login"), request.path_info)) return controller(request, *args, **kwargs)
def login(request): """ MediaGoblin login view. If you provide the POST with 'next', it'll redirect to that view. """ login_form = auth_forms.LoginForm(request.POST) login_failed = False if request.method == 'POST' and login_form.validate(): user = request.db.User.one({'username': request.POST['username']}) if user and user.check_login(request.POST['password']): # set up login in session request.session['user_id'] = unicode(user['_id']) request.session.save() if request.POST.get('next'): return exc.HTTPFound(location=request.POST['next']) else: return exc.HTTPFound(location=request.urlgen("index")) else: # Prevent detecting who's on this system by testing login # attempt timings auth_lib.fake_login_attempt() login_failed = True # render template = request.template_env.get_template('mediagoblin/auth/login.html') return Response( template.render({ 'request': request, 'login_form': login_form, 'next': request.GET.get('next') or request.POST.get('next'), 'login_failed': login_failed }))
def __call__(self, environ, start_response): req = Request(environ) if self._no_redirect_re.match(environ['PATH_INFO']): return req.get_response(self.app)(environ, start_response) resp = None try: request_uri = req.url request_uri.decode('ascii') except UnicodeError: resp = exc.HTTPNotFound() secure = req.environ.get('HTTP_X_SFINC_SSL', 'false') == 'true' srv_path = req.url.split('://', 1)[-1] if req.cookies.get('SFUSER'): if not secure: resp = exc.HTTPFound(location='https://' + srv_path) elif secure: resp = exc.HTTPFound(location='http://' + srv_path) if not resp: resp = self.app return resp(environ, start_response)
def submit_start(request): """ First view for submitting a file. """ submit_form = submit_forms.SubmitStartForm(request.POST) if request.method == 'POST' and submit_form.validate(): if not (request.POST.has_key('file') and isinstance(request.POST['file'], FieldStorage) and request.POST['file'].file): submit_form.file.errors.append(u'You must provide a file.') else: # create entry and save in database entry = request.db.MediaEntry() entry['title'] = request.POST['title'] entry['description'] = request.POST.get(['description']) entry['media_type'] = u'image' # heh entry['uploader'] = request.user # Save, just so we can get the entry id for the sake of using # it to generate the file path entry.save(validate=False) # Now store generate the queueing related filename queue_filepath = request.app.queue_store.get_unique_filepath([ 'media_entries', unicode(request.user['_id']), unicode(entry['_id']), secure_filename(request.POST['file'].filename) ]) # queue appropriately queue_file = request.app.queue_store.get_file(queue_filepath, 'wb') with queue_file: queue_file.write(request.POST['file'].file.read()) # Add queued filename to the entry entry.setdefault('queue_files', []).append(queue_filepath) entry.save(validate=True) # redirect return exc.HTTPFound( location=request.urlgen("mediagoblin.submit.success")) # render template = request.template_env.get_template( 'mediagoblin/submit/start.html') return Response( template.render({ 'request': request, 'submit_form': submit_form }))
def lookup(self, req, stack_name): """ Redirect to the canonical URL for a stack """ try: identity = self.engine_rpcapi.identify_stack( req.context, stack_name) except rpc_common.RemoteError as ex: return self._remote_error(ex) raise exc.HTTPFound(location=stack_url(req, identity))
def lookup(self, req, stack_name, path='', body=None): """ Redirect to the canonical URL for a stack """ try: identity = dict(identifier.HeatIdentifier.from_arn(stack_name)) except ValueError: identity = self.engine.identify_stack(req.context, stack_name) location = util.make_url(req, identity) if path: location = '/'.join([location, path]) raise exc.HTTPFound(location=location)
def lookup(self, req, stack_name, path='', body=None): """Redirect to the canonical URL for a stack.""" try: identity = dict(identifier.HeatIdentifier.from_arn(stack_name)) except ValueError: identity = self.rpc_client.identify_stack(req.context, stack_name) location = util.make_url(req, identity) if path: location = '/'.join([location, path]) params = req.params if params: location += '?%s' % parse.urlencode(params, True) raise exc.HTTPFound(location=location)
def lookup(self, req, stack_name, path='', body=None): """ Redirect to the canonical URL for a stack """ try: identity = self.engine_rpcapi.identify_stack( req.context, stack_name) except rpc_common.RemoteError as ex: return util.remote_error(ex) location = util.make_url(req, identity) if path: location = '/'.join([location, path]) raise exc.HTTPFound(location=location)
def __call__(self, environ, start_response): status, headers, app_iter, exc_info = call_wsgi_application(self.app, environ) is_api_request = environ.get('PATH_INFO', '').startswith(str('/rest/')) if status[:3] == '401' and not is_api_request: login_url = tg.config.get('auth.login_url', '/auth/') if environ['REQUEST_METHOD'] == 'GET': return_to = environ['PATH_INFO'] if environ.get('QUERY_STRING'): return_to += '?' + environ['QUERY_STRING'] location = tg.url(login_url, dict(return_to=return_to)) else: # Don't try to re-post; the body has been lost. location = tg.url(login_url) r = exc.HTTPFound(location=location) return r(environ, start_response) start_response(status, headers, exc_info) return app_iter
def __call__(self, environ, start_response): request = Request(environ) path_info = request.path_info ## Routing / controller loading stuff route_match = self.routing.match(path_info) # No matching page? if route_match is None: # Try to do see if we have a match with a trailing slash # added and if so, redirect if not path_info.endswith('/') \ and request.method == 'GET' \ and self.routing.match(path_info + '/'): new_path_info = path_info + '/' if request.GET: new_path_info = '%s?%s' % (new_path_info, urllib.urlencode(request.GET)) redirect = exc.HTTPFound(location=new_path_info) return request.get_response(redirect)(environ, start_response) # Okay, no matches. 404 time! return exc.HTTPNotFound()(environ, start_response) controller = util.import_component(route_match['controller']) request.start_response = start_response ## Attach utilities to the request object request.matchdict = route_match request.urlgen = routes.URLGenerator(self.routing, environ) # Do we really want to load this via middleware? Maybe? request.session = request.environ['beaker.session'] # Attach self as request.app # Also attach a few utilities from request.app for convenience? request.app = self request.locale = util.get_locale_from_request(request) request.template_env = util.get_jinja_env(self.template_loader, request.locale) request.db = self.db request.staticdirect = self.staticdirector util.setup_user_in_request(request) return controller(request)(environ, start_response)
def save_create(self, req, dir): file = req.POST.get('file') if file is None or file == '': content = req.POST['content'] filename = req.POST['filename'] else: content = file.value filename = req.POST.get('filename') or file.filename filename = filename.replace('\\', '/') filename = os.path.basename(os.path.normpath(filename)) filename = os.path.join(dir, filename) if os.path.exists(filename): return exc.HTTPForbidden( "The file %s already exists, you cannot upload over it" % filename) f = open(filename, 'wb') f.write(content) f.close() return exc.HTTPFound( location=self.edit_url(req, filename))
def internal(self, req): if (self.require_devauth and not req.environ.get('x-wsgiorg.developer_user')): raise exc.HTTPForbidden('You must login') if req.method == 'POST': if req.params.get('clear'): name = self.file.name self.file.close() self.file = open(name, 'wb') else: false_req = Request.blank('/') false_resp = Response('', status='200 Internal Note') false_resp.write(req.params['note']) self.write_record(false_req, false_resp) raise exc.HTTPFound(req.url) if req.params.get('download'): if req.params['download'] == 'doctest': text = self.doctest(req) else: text = self.function_unittest(req) return Response(text, content_type='text/plain') return Response(self._intercept_template.substitute(req=req, s=self))
def register(request): """ Your classic registration view! """ register_form = auth_forms.RegistrationForm(request.POST) if request.method == 'POST' and register_form.validate(): # TODO: Make sure the user doesn't exist already users_with_username = \ request.db.User.find({'username': request.POST['username']}).count() if users_with_username: register_form.username.errors.append( u'Sorry, a user with that name already exists.') else: # Create the user entry = request.db.User() entry['username'] = request.POST['username'] entry['email'] = request.POST['email'] entry['pw_hash'] = auth_lib.bcrypt_gen_password_hash( request.POST['password']) entry.save(validate=True) # TODO: Send email authentication request # Redirect to register_success return exc.HTTPFound( location=request.urlgen("mediagoblin.auth.register_success")) # render template = request.template_env.get_template( 'mediagoblin/auth/register.html') return Response( template.render({ 'request': request, 'register_form': register_form }))
def publicdomain_result(request): target_lang = util.get_target_lang_from_request(request) request_form = request.GET or request.POST # make sure the user selected "confirm" if request_form.get('understand', False) != 'confirm': return exc.HTTPFound(location='%s?%s' % ('./publicdomain-3', urlencode(request.GET))) work_info = _work_info(request_form) license_html = PUBLICDOMAIN_HTML_FORMATTER.format( cc.license.by_code('publicdomain'), work_info, target_lang) context = _base_context(request, target_lang) context.update({ 'request_form': request_form, 'license_html': license_html }) return Response( util.render_template(request, target_lang, 'chooser_pages/publicdomain/publicdomain-4.html', context))