def print_vacation(self, request): """Uses OAuth to do... well nothing sophisticated, but hopefully you will get the point. If the access token doesn't exist, we initialize the process for obtaining it.""" if self.access_token is None: # The access token is required to gain access to the protected # resource. if self.request_token is None: self.fetch_request_token() # Redirect the user to the service provider's authorization # URL with the token key as payload; so that the service # provider can associate the user with a particular request # token. location = '?'.join([ AUTHORIZATION_URL, "oauth_token=%s" % self.request_token.key ]) response = HTTPFound(location=location) else: # okay... why are you here? O.o response = HTTPFound("%s/" % request.host_url) else: # Because we have an access token, we can now make a request to # the protected resource. client = self.get_client() resp, content = client.request(PROTECTED_RESOURCE_URL, "POST", urlencode(RESOURCE_PARAMETERS)) # Create the response body for this page based on the protected # resource data. body = "" resp_data = dict(parse_qsl(content)) # Display the protected resource's response data on the page. body += '<br />'.join([ "<div><b>%s</b></div>%s</div>" % (k, v) for k, v in resp_data.iteritems() ]) # Create a link back to the index page. body += """<br /><a href="/">Back to the index page.</a>""" body = template % body response = Response(body) return response
def next(self, request): url = make_url(request.request, node=self.model) if request.get('ajax'): return [ AjaxAction(url, 'leftcolumn', 'replace', '.left_column'), AjaxAction(url, 'rightcolumn', 'replace', '.right_column'), ] return HTTPFound(location=url)
def _load_repo(self): repo_obj = c.db_repo if repo_obj is None: h.not_mapped_error(c.repo_name) raise HTTPFound(location=url('repos')) return repo_obj
def after(self, context): context.__dict__['fixes'] = self.fixes[context.usertheme] context.__dict__['bfixes'] = self.bfixes[context.usertheme] if context.response.status_int == 403: """ If a page is not authorized, redirect to the login page """ context.response = HTTPFound(location='/admin/auth')
def index(self): c.came_from = safe_str(request.GET.get('came_from', '')) if c.came_from: if not self._validate_came_from(c.came_from): log.error('Invalid came_from (not server-relative): %r', c.came_from) raise HTTPBadRequest() else: c.came_from = url('home') ip_allowed = AuthUser.check_ip_allowed(request.authuser, request.ip_addr) # redirect if already logged in if request.authuser.is_authenticated and ip_allowed: raise HTTPFound(location=c.came_from) if request.POST: # import Login Form validator class login_form = LoginForm()() try: c.form_result = login_form.to_python(dict(request.POST)) # form checks for username/password, now we're authenticated username = c.form_result['username'] user = User.get_by_username_or_email(username, case_insensitive=True) except formencode.Invalid as errors: defaults = errors.value # remove password from filling in form again defaults.pop('password', None) return htmlfill.render( render('/login.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False) except UserCreationError as e: # container auth or other auth functions that create users on # the fly can throw this exception signaling that there's issue # with user creation, explanation should be provided in # Exception itself h.flash(e, 'error') else: log_in_user(user, c.form_result['remember'], is_external_auth=False) raise HTTPFound(location=c.came_from) return render('/login.html')
def challenge(self, environ, status, app_headers, forget_headers): if environ.has_key('rwpc.logout'): log.debug("Headers before logout: " + str(app_headers)) app_headers = [(a, b) for a, b in app_headers \ if a.lower() != 'location' ] log.debug("Headers after logout: " + str(app_headers)) headers = [('Location', self.path_logout)] headers = headers + app_headers + forget_headers log.debug("Logout headers: " + str(headers)) return HTTPFound(headers=headers) else: headers = [('Location', login_url)] cookies = [(h,v) for (h,v) in app_headers \ if h.lower() == 'set-cookie'] headers = headers + forget_headers + cookies return HTTPFound(headers=headers)
def create(self, repo_name): repo = c.db_repo try: _form = PullRequestForm(repo.repo_id)().to_python(request.POST) except formencode.Invalid as errors: log.error(traceback.format_exc()) log.error(str(errors)) msg = _('Error creating pull request: %s') % errors.msg h.flash(msg, 'error') raise HTTPBadRequest # heads up: org and other might seem backward here ... org_ref = _form[ 'org_ref'] # will have merge_rev as rev but symbolic name org_repo = Repository.guess_instance(_form['org_repo']) other_ref = _form[ 'other_ref'] # will have symbolic name and head revision other_repo = Repository.guess_instance(_form['other_repo']) reviewers = [] title = _form['pullrequest_title'] description = _form['pullrequest_desc'].strip() owner = User.get(request.authuser.user_id) try: cmd = CreatePullRequestAction(org_repo, other_repo, org_ref, other_ref, title, description, owner, reviewers) except CreatePullRequestAction.ValidationError as e: h.flash(e, category='error', logf=log.error) raise HTTPNotFound try: pull_request = cmd.execute() Session().commit() except Exception: h.flash(_('Error occurred while creating pull request'), category='error') log.error(traceback.format_exc()) raise HTTPFound( location=url('pullrequest_home', repo_name=repo_name)) h.flash(_('Successfully opened new pull request'), category='success') raise HTTPFound(location=pull_request.url())
def validate_form(request): form = get_form(request) try: data = form.validate(request) except formish.FormError: return {'form':form} username, password = data['username'], data['password'] return HTTPFound(location='thanks')
def redirect(*args, **kwargs): """Compose a URL using :func:`url_for` and raise a redirect. :raises: :class:`webob.exc.HTTPFound` """ url = url_for(*args, **kwargs) found = HTTPFound(location=url) raise found.exception
def delete_email(self, id): user = self._get_user_or_raise_if_default(id) email_id = request.POST.get('del_email_id') user_model = UserModel() user_model.delete_extra_email(id, email_id) Session().commit() h.flash(_("Removed email from user"), category='success') raise HTTPFound(location=url('edit_user_emails', id=id))
def redirect(location): """Return a response object that redirects to location. :param location: a URL to redirect to. :return: a :class:`webob.exc.HTTPFound` response object. You can return this from a view to redirect. """ return HTTPFound(location=location)
def post(self, repo_name, pull_request_id): pull_request = PullRequest.get_or_404(pull_request_id) if pull_request.is_closed(): raise HTTPForbidden() assert pull_request.other_repo.repo_name == repo_name # only owner or admin can update it owner = pull_request.owner_id == request.authuser.user_id repo_admin = h.HasRepoPermissionLevel('admin')(c.repo_name) if not (h.HasPermissionAny('hg.admin')() or repo_admin or owner): raise HTTPForbidden() _form = PullRequestPostForm()().to_python(request.POST) cur_reviewers = set(pull_request.get_reviewer_users()) new_reviewers = set(_get_reviewer(s) for s in _form['review_members']) old_reviewers = set( _get_reviewer(s) for s in _form['org_review_members']) other_added = cur_reviewers - old_reviewers other_removed = old_reviewers - cur_reviewers if other_added: h.flash( _('Meanwhile, the following reviewers have been added: %s') % (', '.join(u.username for u in other_added)), category='warning') if other_removed: h.flash( _('Meanwhile, the following reviewers have been removed: %s') % (', '.join(u.username for u in other_removed)), category='warning') if _form['updaterev']: return self.create_new_iteration(pull_request, _form['updaterev'], _form['pullrequest_title'], _form['pullrequest_desc'], new_reviewers) added_reviewers = new_reviewers - old_reviewers - cur_reviewers removed_reviewers = (old_reviewers - new_reviewers) & cur_reviewers old_description = pull_request.description pull_request.title = _form['pullrequest_title'] pull_request.description = _form['pullrequest_desc'].strip() or _( 'No description') pull_request.owner = User.get_by_username(_form['owner']) user = User.get(request.authuser.user_id) PullRequestModel().mention_from_description(user, pull_request, old_description) PullRequestModel().add_reviewers(user, pull_request, added_reviewers) PullRequestModel().remove_reviewers(user, pull_request, removed_reviewers) Session().commit() h.flash(_('Pull request updated'), category='success') raise HTTPFound(location=pull_request.url())
def edit_fields(self, repo_name): c.repo_info = self._load_repo() c.repo_fields = RepositoryField.query() \ .filter(RepositoryField.repository == c.repo_info).all() c.active = 'fields' if request.POST: raise HTTPFound(location=url('repo_edit_fields')) return render('admin/repos/repo_edit.html')
def post(self, *arg, **args): r = self._ctx.authenticate(self._ctx, identifier=args['username'], credential=args['password']) if r == True: self._ctx.session.username = args['username'] # Check if the spword field is empty. If so, force a password change result = self._ctx.db.query(self._ctx.Users.spword).filter( self._ctx.Users.uname == args['username']).one() if result.spword == '' or result.spword is None: return change_pw_template('Change Password', self._ctx, first_access=True) else: self._ctx.response = HTTPFound(location='/admin') if args['username'] == 'changepw': self._ctx.response = HTTPFound(location='/admin/changepw') return authtemplate("Login", self._ctx, [])
def add_api_key(self, id): c.user = self._get_user_or_raise_if_default(id) lifetime = safe_int(request.POST.get('lifetime'), -1) description = request.POST.get('description') ApiKeyModel().create(c.user.user_id, description, lifetime) Session().commit() h.flash(_("API key successfully created"), category='success') raise HTTPFound(location=url('edit_user_api_keys', id=c.user.user_id))
def delete(self, repo_name, pull_request_id): pull_request = PullRequest.get_or_404(pull_request_id) # only owner can delete it ! if pull_request.owner_id == request.authuser.user_id: PullRequestModel().delete(pull_request) Session().commit() h.flash(_('Successfully deleted pull request'), category='success') raise HTTPFound(location=url('my_pullrequests')) raise HTTPForbidden()
def __call__(self): if self.request.method == "POST": account = self.login() if account: came_from = self.request.POST.get("came_from") if came_from: response = HTTPFound(location=came_from) else: response = HTTPFound( location=route_url("dashboard", self.request)) loginUser(account, self.request, response) return response return render("login.pt", self.request, status_int=202 if self.request.method == "POST" else 200, login_url=route_url("login", self.request), form=self.form)
def edit(self, gist_id, format='html'): c.gist = Gist.get_or_404(gist_id) if c.gist.is_expired: log.error('Gist expired at %s', time_to_datetime(c.gist.gist_expires)) raise HTTPNotFound() try: c.file_changeset, c.files = GistModel().get_gist_files(gist_id) except VCSError: log.error(traceback.format_exc()) raise HTTPNotFound() self.__load_defaults(extra_values=('0', _('Unmodified'))) rendered = render('admin/gists/edit.html') if request.POST: rpost = request.POST nodes = {} for org_filename, filename, mimetype, content in zip( rpost.getall('org_files'), rpost.getall('files'), rpost.getall('mimetypes'), rpost.getall('contents')): nodes[org_filename] = { 'org_filename': org_filename, 'filename': filename, 'content': content, 'lexer': mimetype, } try: GistModel().update( gist=c.gist, description=rpost['description'], owner=c.gist.owner, # FIXME: request.authuser.user_id ? ip_addr=request.ip_addr, gist_mapping=nodes, gist_type=c.gist.gist_type, lifetime=rpost['lifetime']) Session().commit() h.flash(_('Successfully updated gist content'), category='success') except NodeNotChangedError: # raised if nothing was changed in repo itself. We anyway then # store only DB stuff for gist Session().commit() h.flash(_('Successfully updated gist data'), category='success') except Exception: log.error(traceback.format_exc()) h.flash(_('Error occurred during update of gist %s') % gist_id, category='error') raise HTTPFound(location=url('gist', gist_id=gist_id)) return rendered
def edit_account_view(context, request): confirmed = request.registry.queryAdapter(context, IRegistrations, name='confirmed') if confirmed is None: #pragma NO COVERAGE confirmed = ConfirmedRegistrations(context) identity = request.environ.get('repoze.who.identity') if identity is None: return HTTPUnauthorized() userid = identity['repoze.who.userid'] account_info = confirmed.get(userid) if account_info is None: return HTTPForbidden() appstruct = { 'login_name': account_info.login, 'email': account_info.email, 'security': { 'question': account_info.security_question or '', 'answer': account_info.security_answer or '', }, } schema = EditAccount().bind(current_login_name=account_info.login, confirmed=confirmed, old_password=account_info.password) form = Form(schema, buttons=('update', )) rendered_form = form.render(appstruct) if 'update' in request.POST: try: appstruct = form.validate(request.POST.items()) except ValidationFailure, e: rendered_form = e.render() else: login = appstruct['login_name'] email = appstruct['email'] pwd_mgr = SSHAPasswordManager() password = pwd_mgr.encodePassword(appstruct['password']) security_question = appstruct['security']['question'] security_answer = appstruct['security']['answer'] confirmed.set( userid, email=email, login=login, password=password, security_question=security_question, security_answer=security_answer, ) return HTTPFound(location=view_url( context, request, 'after_edit_url', request.view_name, ))
def Delete(context, request): if request.method == "POST": if not checkCSRF(request): raise Forbidden("Invalid CSRF token") if request.POST.get("action", "cancel") == "confirm": meta.Session.delete(context) return HTTPFound(location=route_url( "customer_view", request, id=context.customer_id)) return HTTPFound( location=route_url("invoice_view", request, id=context.id)) return render("invoice_delete.pt", request, context, status_int=202 if request.method == "POST" else 200, section="customers", action_url=route_url("invoice_delete", request, id=context.id))
def _redirect_to_login(message=None): """Return an exception that must be raised. It will redirect to the login page which will redirect back to the current URL after authentication. The optional message will be shown in a flash message.""" from kallithea.lib import helpers as h if message: h.flash(message, category='warning') p = request.path_qs log.debug('Redirecting to login page, origin: %s', p) return HTTPFound(location=url('login_home', came_from=p))
def add_ip(self, id): ip = request.POST.get('new_ip') user_model = UserModel() try: user_model.add_extra_ip(id, ip) Session().commit() h.flash(_("Added IP address %s to user whitelist") % ip, category='success') except formencode.Invalid as error: msg = error.error_dict['ip'] h.flash(msg, category='error') except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred while adding IP address'), category='error') if 'default_user' in request.POST: raise HTTPFound(location=url('admin_permissions_ips')) raise HTTPFound(location=url('edit_user_ips', id=id))
def page_view(request): page_name = request.urlvars['page_name'] edit_url = request.environ['webdispatch.urlgenerator'].generate( 'page_edit', page_name=page_name) try: page = DBSession.query(Page).filter(Page.page_name == page_name).one() tmpl = env.get_template('page.html') return tmpl.render(page=page, edit_url=edit_url) except NoResultFound: return HTTPFound(location=edit_url)
def my_account_ssh_keys_delete(self): fingerprint = request.POST.get('del_public_key_fingerprint') try: SshKeyModel().delete(fingerprint, request.authuser.user_id) Session().commit() SshKeyModel().write_authorized_keys() h.flash(_("SSH key successfully deleted"), category='success') except SshKeyModelException as e: h.flash(e.args[0], category='error') raise HTTPFound(location=url('my_account_ssh_keys'))
def delete_repo_field(self, repo_name, field_id): field = RepositoryField.get_or_404(field_id) try: Session().delete(field) Session().commit() except Exception as e: log.error(traceback.format_exc()) msg = _('An error occurred during removal of field') h.flash(msg, category='error') raise HTTPFound(location=url('edit_repo_fields', repo_name=repo_name))
def edit_permissions_update(self, repo_name): form = RepoPermsForm()().to_python(request.POST) RepoModel()._update_permissions(repo_name, form['perms_new'], form['perms_updates']) # TODO: implement this #action_logger(request.authuser, 'admin_changed_repo_permissions', # repo_name, request.ip_addr) Session().commit() h.flash(_('Repository permissions updated'), category='success') raise HTTPFound(location=url('edit_repo_perms', repo_name=repo_name))
def __call__(self): if self.request.method == "POST" and self.update(): return HTTPFound(location=route_url("home", self.request)) return render("profile.pt", self.request, context=self.context, status_int=202 if self.request.method == "POST" else 200, form=self.form, action_url=route_url("profile", self.request))
def logout_view(context, request): if 'logout' in request.POST: api = get_api(request.environ) headers = api.logout() after_logout_url = view_url(context, request, 'after_logout_url', '') return HTTPFound(location=after_logout_url, headers=headers) identity = request.environ.get('repoze.who.identity', {}) main_template = get_renderer('templates/main.pt') return {'userid': identity.get('repoze.who.userid'), 'main_template': main_template.implementation(), }
def my_account(self): c.active = 'profile' self.__load_data() c.perm_user = AuthUser(user_id=request.authuser.user_id) managed_fields = auth_modules.get_managed_fields(c.user) def_user_perms = User.get_default_user().AuthUser.permissions['global'] if 'hg.register.none' in def_user_perms: managed_fields.extend(['username', 'firstname', 'lastname', 'email']) c.readonly = lambda n: 'readonly' if n in managed_fields else None defaults = c.user.get_dict() update = False if request.POST: _form = UserForm(edit=True, old_data={'user_id': request.authuser.user_id, 'email': request.authuser.email})() form_result = {} try: post_data = dict(request.POST) post_data['new_password'] = '' post_data['password_confirmation'] = '' form_result = _form.to_python(post_data) # skip updating those attrs for my account skip_attrs = ['admin', 'active', 'extern_type', 'extern_name', 'new_password', 'password_confirmation', ] + managed_fields UserModel().update(request.authuser.user_id, form_result, skip_attrs=skip_attrs) h.flash(_('Your account was updated successfully'), category='success') Session().commit() update = True except formencode.Invalid as errors: return htmlfill.render( render('admin/my_account/my_account.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False) except Exception: log.error(traceback.format_exc()) h.flash(_('Error occurred during update of user %s') \ % form_result.get('username'), category='error') if update: raise HTTPFound(location='my_account') return htmlfill.render( render('admin/my_account/my_account.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def handle_submit(self, converted): session = DBSession() company = session.query(Company).first() changed = self._apply_data(company, converted) if changed: statusmessage.show(self.request, u"Changes saved.", "success") else: statusmessage.show(self.request, u"No changes saved.", "notice") return HTTPFound(location=route_url('company', self.request))