def fork_create(self, repo_name): self.__load_defaults() c.repo_info = Repository.get_by_repo_name(repo_name) _form = RepoForkForm(old_data={'repo_type': c.repo_info.repo_type}, repo_groups=c.repo_groups, landing_revs=c.landing_revs_choices)() form_result = {} task_id = None try: form_result = _form.to_python(dict(request.POST)) # an approximation that is better than nothing if not Ui.get_by_key('hooks', Ui.HOOK_UPDATE).ui_active: form_result['update_after_clone'] = False # create fork is done sometimes async on celery, db transaction # management is handled there. task = RepoModel().create_fork(form_result, request.authuser.user_id) task_id = task.task_id except formencode.Invalid as errors: return htmlfill.render( render('forks/fork.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(_('An error occurred during repository forking %s') % repo_name, category='error') raise HTTPFound(location=h.url('repo_creating_home', repo_name=form_result['repo_name_full'], task_id=task_id))
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.author.user_id == c.authuser.user_id repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name) if not (h.HasPermissionAny('hg.admin') or repo_admin or owner): raise HTTPForbidden() _form = PullRequestPostForm()().to_python(request.POST) reviewers_ids = [int(s) for s in _form['review_members']] if _form['updaterev']: return self.create_update(pull_request, _form['updaterev'], _form['pullrequest_title'], _form['pullrequest_desc'], reviewers_ids) old_description = pull_request.description pull_request.title = _form['pullrequest_title'] pull_request.description = _form['pullrequest_desc'].strip() or _('No description') PullRequestModel().mention_from_description(pull_request, old_description) PullRequestModel().update_reviewers(pull_request_id, reviewers_ids) Session().commit() h.flash(_('Pull request updated'), category='success') return redirect(pull_request.url())
def delete_perms(self, group_name): try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) if not request.authuser.is_admin: if obj_type == 'user' and request.authuser.user_id == obj_id: msg = _('Cannot revoke permission for yourself as admin') h.flash(msg, category='warning') raise Exception('revoke admin permission on self') recursive = request.POST.get('recursive', 'none') if obj_type == 'user': RepoGroupModel().delete_permission(repo_group=group_name, obj=obj_id, obj_type='user', recursive=recursive) elif obj_type == 'user_group': RepoGroupModel().delete_permission(repo_group=group_name, obj=obj_id, obj_type='user_group', recursive=recursive) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError()
def update_perms(self, id): user = self._get_user_or_raise_if_default(id) try: form = CustomDefaultPermissionsForm()() form_result = form.to_python(request.POST) user_model = UserModel() defs = UserToPerm.query() \ .filter(UserToPerm.user == user) \ .all() for ug in defs: Session().delete(ug) if form_result['create_repo_perm']: user_model.grant_perm(id, 'hg.create.repository') else: user_model.grant_perm(id, 'hg.create.none') if form_result['create_user_group_perm']: user_model.grant_perm(id, 'hg.usergroup.create.true') else: user_model.grant_perm(id, 'hg.usergroup.create.false') if form_result['fork_repo_perm']: user_model.grant_perm(id, 'hg.fork.repository') else: user_model.grant_perm(id, 'hg.fork.none') h.flash(_("Updated permissions"), category='success') Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during permissions saving'), category='error') raise HTTPFound(location=url('edit_user_perms', id=id))
def delete_perms(self, id): try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) if not request.authuser.is_admin: if obj_type == 'user' and request.authuser.user_id == obj_id: msg = _('Cannot revoke permission for yourself as admin') h.flash(msg, category='warning') raise Exception('revoke admin permission on self') if obj_type == 'user': UserGroupModel().revoke_user_permission(user_group=id, user=obj_id) elif obj_type == 'user_group': UserGroupModel().revoke_user_group_permission(target_user_group=id, user_group=obj_id) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError()
def _index(self, revision, method): c.anchor_url = anchor_url c.ignorews_url = _ignorews_url c.context_url = _context_url c.fulldiff = fulldiff = request.GET.get('fulldiff') #get ranges of revisions if preset rev_range = revision.split('...')[:2] enable_comments = True c.cs_repo = c.db_repo try: if len(rev_range) == 2: enable_comments = False rev_start = rev_range[0] rev_end = rev_range[1] rev_ranges = c.db_repo_scm_instance.get_changesets(start=rev_start, end=rev_end) else: rev_ranges = [c.db_repo_scm_instance.get_changeset(revision)] c.cs_ranges = list(rev_ranges) if not c.cs_ranges: raise RepositoryError('Changeset range returned empty result') except(ChangesetDoesNotExistError,), e: log.error(traceback.format_exc()) msg = _('Such revision does not exist for this repository') h.flash(msg, category='error') raise HTTPNotFound()
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.author.user_id == c.authuser.user_id repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name) if not (h.HasPermissionAny('hg.admin') or repo_admin or owner): raise HTTPForbidden() _form = PullRequestPostForm()().to_python(request.POST) reviewers_ids = [int(s) for s in _form['review_members']] if _form['updaterev']: return self.create_update(pull_request, _form['updaterev'], _form['pullrequest_title'], _form['pullrequest_desc'], reviewers_ids) old_description = pull_request.description pull_request.title = _form['pullrequest_title'] pull_request.description = _form['pullrequest_desc'].strip() or _( 'No description') PullRequestModel().mention_from_description(pull_request, old_description) PullRequestModel().update_reviewers(pull_request_id, reviewers_ids) Session().commit() h.flash(_('Pull request updated'), category='success') return redirect(pull_request.url())
def _index(self, revision, method): c.anchor_url = anchor_url c.ignorews_url = _ignorews_url c.context_url = _context_url c.fulldiff = fulldiff = request.GET.get('fulldiff') #get ranges of revisions if preset rev_range = revision.split('...')[:2] enable_comments = True c.cs_repo = c.db_repo try: if len(rev_range) == 2: enable_comments = False rev_start = rev_range[0] rev_end = rev_range[1] rev_ranges = c.db_repo_scm_instance.get_changesets( start=rev_start, end=rev_end) else: rev_ranges = [c.db_repo_scm_instance.get_changeset(revision)] c.cs_ranges = list(rev_ranges) if not c.cs_ranges: raise RepositoryError('Changeset range returned empty result') except (ChangesetDoesNotExistError, ), e: log.error(traceback.format_exc()) msg = _('Such revision does not exist for this repository') h.flash(msg, category='error') raise HTTPNotFound()
def settings_mapping(self): """GET /admin/settings/mapping: All items in the collection""" # url('admin_settings_mapping') c.active = 'mapping' if request.POST: rm_obsolete = request.POST.get('destroy', False) install_git_hooks = request.POST.get('hooks', False) invalidate_cache = request.POST.get('invalidate', False) log.debug('rescanning repo location with destroy obsolete=%s and ' 'install git hooks=%s' % (rm_obsolete,install_git_hooks)) if invalidate_cache: log.debug('invalidating all repositories cache') for repo in Repository.get_all(): ScmModel().mark_for_invalidation(repo.repo_name, delete=True) filesystem_repos = ScmModel().repo_scan() added, removed = repo2db_mapper(filesystem_repos, rm_obsolete, install_git_hook=install_git_hooks, user=c.authuser.username) h.flash(h.literal(_('Repositories successfully rescanned. Added: %s. Removed: %s.') % (', '.join(h.link_to(safe_unicode(repo_name), h.url('summary_home', repo_name=repo_name)) for repo_name in added) or '-', ', '.join(h.escape(safe_unicode(repo_name)) for repo_name in removed) or '-')), category='success') return redirect(url('admin_settings_mapping')) defaults = Setting.get_app_settings() defaults.update(self._get_hg_ui_settings()) return htmlfill.render( render('admin/settings/settings.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def update_perms(self, group_name): """ Update permissions for given repository group :param group_name: """ c.repo_group = RepoGroupModel()._get_repo_group(group_name) valid_recursive_choices = ['none', 'repos', 'groups', 'all'] form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python( request.POST) if not c.authuser.is_admin: if self._revoke_perms_on_yourself(form_result): msg = _('Cannot revoke permission for yourself as admin') h.flash(msg, category='warning') return redirect( url('edit_repo_group_perms', group_name=group_name)) recursive = form_result['recursive'] # iterate over all members(if in recursive mode) of this groups and # set the permissions ! # this can be potentially heavy operation RepoGroupModel()._update_permissions(c.repo_group, form_result['perms_new'], form_result['perms_updates'], recursive) #TODO: implement this #action_logger(self.authuser, 'admin_changed_repo_permissions', # repo_name, self.ip_addr, self.sa) Session().commit() h.flash(_('Repository Group permissions updated'), category='success') return redirect(url('edit_repo_group_perms', group_name=group_name))
def __wrapper(self, func, *fargs, **fkwargs): cls = fargs[0] self.user = cls.authuser self.user_perms = self.user.permissions log.debug('checking %s permissions %s for %s %s', self.__class__.__name__, self.required_perms, cls, self.user) if self.check_permissions(): log.debug('Permission granted for %s %s' % (cls, self.user)) return func(*fargs, **fkwargs) else: log.debug('Permission denied for %s %s' % (cls, self.user)) anonymous = self.user.username == User.DEFAULT_USER if anonymous: p = url.current() import kallithea.lib.helpers as h h.flash(_('You need to be signed in to ' 'view this page'), category='warning') return redirect(url('login_home', came_from=p)) else: # redirect with forbidden ret code return abort(403)
def my_account_emails_delete(self): email_id = request.POST.get('del_email_id') user_model = UserModel() user_model.delete_extra_email(self.authuser.user_id, email_id) Session().commit() h.flash(_("Removed email from user"), category='success') raise HTTPFound(location=url('my_account_emails'))
def my_account_api_keys_add(self): lifetime = safe_int(request.POST.get('lifetime'), -1) description = request.POST.get('description') ApiKeyModel().create(self.authuser.user_id, description, lifetime) Session().commit() h.flash(_("API key successfully created"), category='success') raise HTTPFound(location=url('my_account_api_keys'))
def edit_permissions_revoke(self, repo_name): try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) else: assert False if obj_type == 'user': RepoModel().revoke_user_permission(repo=repo_name, user=obj_id) elif obj_type == 'user_group': RepoModel().revoke_user_group_permission(repo=repo_name, group_name=obj_id) else: assert False # TODO: implement this #action_logger(request.authuser, 'admin_revoked_repo_permissions', # repo_name, request.ip_addr) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError() return []
def my_account_password(self): c.active = 'password' self.__load_data() managed_fields = auth_modules.get_managed_fields(c.user) c.can_change_password = '******' not in managed_fields if request.POST and c.can_change_password: _form = PasswordChangeForm(self.authuser.username)() try: form_result = _form.to_python(request.POST) UserModel().update(self.authuser.user_id, form_result) Session().commit() h.flash(_("Successfully updated password"), category='success') 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 password'), category='error') return render('admin/my_account/my_account.html')
def my_account_password(self): c.active = 'password' self.__load_data() managed_fields = auth_modules.get_managed_fields(c.user) c.can_change_password = '******' not in managed_fields if request.POST and c.can_change_password: _form = PasswordChangeForm(request.authuser.username)() try: form_result = _form.to_python(request.POST) UserModel().update(request.authuser.user_id, form_result) Session().commit() h.flash(_("Successfully updated password"), category='success') 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 password'), category='error') return render('admin/my_account/my_account.html')
def edit_statistics(self, repo_name): """GET /repo_name/settings: Form to edit an existing item""" # url('edit_repo', repo_name=ID) c.repo_info = self._load_repo(repo_name) repo = c.repo_info.scm_instance if c.repo_info.stats: # this is on what revision we ended up so we add +1 for count last_rev = c.repo_info.stats.stat_on_revision + 1 else: last_rev = 0 c.stats_revision = last_rev c.repo_last_rev = repo.count() if repo.revisions else 0 if last_rev == 0 or c.repo_last_rev == 0: c.stats_percentage = 0 else: c.stats_percentage = '%.2f' % ((float((last_rev)) / c.repo_last_rev) * 100) c.active = 'statistics' if request.POST: try: RepoModel().delete_stats(repo_name) Session().commit() except Exception, e: log.error(traceback.format_exc()) h.flash(_('An error occurred during deletion of repository stats'), category='error') return redirect(url('edit_repo_statistics', repo_name=c.repo_name))
def edit_statistics(self, repo_name): c.repo_info = self._load_repo() repo = c.repo_info.scm_instance if c.repo_info.stats: # this is on what revision we ended up so we add +1 for count last_rev = c.repo_info.stats.stat_on_revision + 1 else: last_rev = 0 c.stats_revision = last_rev c.repo_last_rev = repo.count() if repo.revisions else 0 if last_rev == 0 or c.repo_last_rev == 0: c.stats_percentage = 0 else: c.stats_percentage = '%.2f' % ((float( (last_rev)) / c.repo_last_rev) * 100) c.active = 'statistics' if request.POST: try: RepoModel().delete_stats(repo_name) Session().commit() except Exception as e: log.error(traceback.format_exc()) h.flash( _('An error occurred during deletion of repository stats'), category='error') raise HTTPFound( location=url('edit_repo_statistics', repo_name=c.repo_name)) return render('admin/repos/repo_edit.html')
def __load_data(self): c.user = User.get(self.authuser.user_id) if c.user.username == User.DEFAULT_USER: h.flash(_("You can't edit this user since it's" " crucial for entire application"), category='warning') raise HTTPFound(location=url('users')) c.EXTERN_TYPE_INTERNAL = EXTERN_TYPE_INTERNAL
def my_account_emails_delete(self): email_id = request.POST.get('del_email_id') user_model = UserModel() user_model.delete_extra_email(self.authuser.user_id, email_id) Session().commit() h.flash(_("Removed email from user"), category='success') return redirect(url('my_account_emails'))
def edit_statistics(self, repo_name): c.repo_info = self._load_repo() repo = c.repo_info.scm_instance if c.repo_info.stats: # this is on what revision we ended up so we add +1 for count last_rev = c.repo_info.stats.stat_on_revision + 1 else: last_rev = 0 c.stats_revision = last_rev c.repo_last_rev = repo.count() if repo.revisions else 0 if last_rev == 0 or c.repo_last_rev == 0: c.stats_percentage = 0 else: c.stats_percentage = '%.2f' % ((float((last_rev)) / c.repo_last_rev) * 100) c.active = 'statistics' if request.POST: try: RepoModel().delete_stats(repo_name) Session().commit() except Exception as e: log.error(traceback.format_exc()) h.flash(_('An error occurred during deletion of repository stats'), category='error') raise HTTPFound(location=url('edit_repo_statistics', repo_name=c.repo_name)) return render('admin/repos/repo_edit.html')
def create(self): """POST /repo_groups: Create a new item""" # url('repos_groups') self.__load_defaults() # permissions for can create group based on parent_id are checked # here in the Form repo_group_form = RepoGroupForm(available_groups= map(lambda k: unicode(k[0]), c.repo_groups))() try: form_result = repo_group_form.to_python(dict(request.POST)) RepoGroupModel().create( group_name=form_result['group_name'], group_description=form_result['group_description'], parent=form_result['group_parent_id'], owner=self.authuser.user_id, copy_permissions=form_result['group_copy_permissions'] ) Session().commit() h.flash(_('Created repository group %s') \ % form_result['group_name'], category='success') #TODO: in futureaction_logger(, '', '', '', self.sa) except formencode.Invalid, errors: return htmlfill.render( render('admin/repo_groups/repo_group_add.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False)
def create(self): """POST /users_groups: Create a new item""" # url('users_groups') users_group_form = UserGroupForm()() try: form_result = users_group_form.to_python(dict(request.POST)) ug = UserGroupModel().create(name=form_result['users_group_name'], description=form_result['user_group_description'], owner=self.authuser.user_id, active=form_result['users_group_active']) gr = form_result['users_group_name'] action_logger(self.authuser, 'admin_created_users_group:%s' % gr, None, self.ip_addr, self.sa) h.flash(h.literal(_('Created user group %s') % h.link_to(h.escape(gr), url('edit_users_group', id=ug.users_group_id))), category='success') Session().commit() except formencode.Invalid, errors: return htmlfill.render( render('admin/user_groups/user_group_add.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False)
def create(self): """POST /repo_groups: Create a new item""" # url('repos_groups') self.__load_defaults() # permissions for can create group based on parent_id are checked # here in the Form repo_group_form = RepoGroupForm( available_groups=map(lambda k: unicode(k[0]), c.repo_groups))() try: form_result = repo_group_form.to_python(dict(request.POST)) RepoGroupModel().create( group_name=form_result['group_name'], group_description=form_result['group_description'], parent=form_result['group_parent_id'], owner=self.authuser.user_id, copy_permissions=form_result['group_copy_permissions']) Session().commit() h.flash(_('Created repository group %s') \ % form_result['group_name'], category='success') #TODO: in futureaction_logger(, '', '', '', self.sa) except formencode.Invalid, errors: return htmlfill.render( render('admin/repo_groups/repo_group_add.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False)
def password_reset(self): settings = Setting.get_app_settings() captcha_private_key = settings.get('captcha_private_key') c.captcha_active = bool(captcha_private_key) c.captcha_public_key = settings.get('captcha_public_key') if request.POST: password_reset_form = PasswordResetForm()() try: form_result = password_reset_form.to_python(dict(request.POST)) if c.captcha_active: from kallithea.lib.recaptcha import submit response = submit(request.POST.get('recaptcha_challenge_field'), request.POST.get('recaptcha_response_field'), private_key=captcha_private_key, remoteip=self.ip_addr) if c.captcha_active and not response.is_valid: _value = form_result _msg = _('bad captcha') error_dict = {'recaptcha_field': _msg} raise formencode.Invalid(_msg, _value, None, error_dict=error_dict) UserModel().reset_password_link(form_result) h.flash(_('Your password reset link was sent'), category='success') return redirect(url('login_home')) except formencode.Invalid, errors: return htmlfill.render( render('/password_reset.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False)
def delete_perms(self, id): """ DELETE an existing repository group permission user :param group_name: """ try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) if not c.authuser.is_admin: if obj_type == 'user' and c.authuser.user_id == obj_id: msg = _('Cannot revoke permission for yourself as admin') h.flash(msg, category='warning') raise Exception('revoke admin permission on self') if obj_type == 'user': UserGroupModel().revoke_user_permission(user_group=id, user=obj_id) elif obj_type == 'user_group': UserGroupModel().revoke_user_group_permission( target_user_group=id, user_group=obj_id) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError()
def delete(self, repo_name): repo_model = RepoModel() repo = repo_model.get_by_repo_name(repo_name) if not repo: h.not_mapped_error(repo_name) raise HTTPFound(location=url('repos')) try: _forks = repo.forks.count() handle_forks = None if _forks and request.POST.get('forks'): do = request.POST['forks'] if do == 'detach_forks': handle_forks = 'detach' h.flash(_('Detached %s forks') % _forks, category='success') elif do == 'delete_forks': handle_forks = 'delete' h.flash(_('Deleted %s forks') % _forks, category='success') repo_model.delete(repo, forks=handle_forks) action_logger(request.authuser, 'admin_deleted_repo', repo_name, request.ip_addr) ScmModel().mark_for_invalidation(repo_name) h.flash(_('Deleted repository %s') % repo_name, category='success') Session().commit() except AttachedForksError: h.flash(_('Cannot delete repository %s which still has forks') % repo_name, category='warning') except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during deletion of %s') % repo_name, category='error') if repo.group: raise HTTPFound(location=url('repos_group_home', group_name=repo.group.group_name)) raise HTTPFound(location=url('repos'))
def create(self): users_group_form = UserGroupForm()() try: form_result = users_group_form.to_python(dict(request.POST)) ug = UserGroupModel().create(name=form_result['users_group_name'], description=form_result['user_group_description'], owner=request.authuser.user_id, active=form_result['users_group_active']) gr = form_result['users_group_name'] action_logger(request.authuser, 'admin_created_users_group:%s' % gr, None, request.ip_addr) h.flash(h.literal(_('Created user group %s') % h.link_to(h.escape(gr), url('edit_users_group', id=ug.users_group_id))), category='success') Session().commit() except formencode.Invalid as errors: return htmlfill.render( render('admin/user_groups/user_group_add.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 creation of user group %s') \ % request.POST.get('users_group_name'), category='error') raise HTTPFound(location=url('users_groups'))
def __load_data(self): c.user = User.get(request.authuser.user_id) if c.user.is_default_user: h.flash(_("You can't edit this user since it's" " crucial for entire application"), category='warning') raise HTTPFound(location=url('users'))
def create(self): self.__load_defaults() # permissions for can create group based on parent_id are checked # here in the Form repo_group_form = RepoGroupForm(repo_groups=c.repo_groups) try: form_result = repo_group_form.to_python(dict(request.POST)) gr = RepoGroupModel().create( group_name=form_result['group_name'], group_description=form_result['group_description'], parent=form_result['parent_group_id'], owner=request.authuser.user_id, # TODO: make editable copy_permissions=form_result['group_copy_permissions'] ) Session().commit() #TODO: in future action_logger(, '', '', '') except formencode.Invalid as errors: return htmlfill.render( render('admin/repo_groups/repo_group_add.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 creation of repository group %s') \ % request.POST.get('group_name'), category='error') parent_group_id = form_result['parent_group_id'] #TODO: maybe we should get back to the main view, not the admin one raise HTTPFound(location=url('repos_groups', parent_group=parent_group_id)) h.flash(_('Created repository group %s') % gr.group_name, category='success') raise HTTPFound(location=url('repos_group_home', group_name=gr.group_name))
def update(self, id): _form = DefaultsForm()() try: form_result = _form.to_python(dict(request.POST)) for k, v in form_result.items(): setting = Setting.create_or_update(k, v) Session().commit() h.flash(_('Default settings updated successfully'), category='success') except formencode.Invalid as errors: defaults = errors.value return htmlfill.render( render('admin/defaults/defaults.html'), defaults=defaults, 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 defaults'), category='error') raise HTTPFound(location=url('defaults'))
def update(self, id): _form = DefaultsForm()() try: form_result = _form.to_python(dict(request.POST)) for k, v in form_result.iteritems(): setting = Setting.create_or_update(k, v) Session().commit() h.flash(_('Default settings updated successfully'), category='success') except formencode.Invalid as errors: defaults = errors.value return htmlfill.render( render('admin/defaults/defaults.html'), defaults=defaults, 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 defaults'), category='error') raise HTTPFound(location=url('defaults'))
def auth_settings(self): """POST create and store auth settings""" self.__load_defaults() _form = AuthSettingsForm(c.enabled_plugins)() log.debug("POST Result: %s" % formatted_json(dict(request.POST))) try: form_result = _form.to_python(dict(request.POST)) for k, v in form_result.items(): if k == 'auth_plugins': # we want to store it comma separated inside our settings v = ','.join(v) log.debug("%s = %s" % (k, str(v))) setting = Setting.create_or_update(k, v) Session().add(setting) Session().commit() h.flash(_('Auth settings updated successfully'), category='success') except formencode.Invalid, errors: log.error(traceback.format_exc()) e = errors.error_dict or {} return self.index( defaults=errors.value, errors=e, prefix_error=False)
def _basic_security_checks(): """Perform basic security/sanity checks before processing the request.""" # Only allow the following HTTP request methods. if request.method not in ['GET', 'HEAD', 'POST']: raise webob.exc.HTTPMethodNotAllowed() # Also verify the _method override - no longer allowed. if request.params.get('_method') is None: pass # no override, no problem else: raise webob.exc.HTTPMethodNotAllowed() # Make sure CSRF token never appears in the URL. If so, invalidate it. if secure_form.token_key in request.GET: log.error('CSRF key leak detected') session.pop(secure_form.token_key, None) session.save() from kallithea.lib import helpers as h h.flash(_('CSRF token leak has been detected - all form tokens have been expired'), category='error') # WebOb already ignores request payload parameters for anything other # than POST/PUT, but double-check since other Kallithea code relies on # this assumption. if request.method not in ['POST', 'PUT'] and request.POST: log.error('%r request with payload parameters; WebOb should have stopped this', request.method) raise webob.exc.HTTPBadRequest()
def update_perms(self, group_name): """ Update permissions for given repository group :param group_name: """ c.repo_group = RepoGroupModel()._get_repo_group(group_name) valid_recursive_choices = ['none', 'repos', 'groups', 'all'] form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(request.POST) if not c.authuser.is_admin: if self._revoke_perms_on_yourself(form_result): msg = _('Cannot revoke permission for yourself as admin') h.flash(msg, category='warning') return redirect(url('edit_repo_group_perms', group_name=group_name)) recursive = form_result['recursive'] # iterate over all members(if in recursive mode) of this groups and # set the permissions ! # this can be potentially heavy operation RepoGroupModel()._update_permissions(c.repo_group, form_result['perms_new'], form_result['perms_updates'], recursive) #TODO: implement this #action_logger(self.authuser, 'admin_changed_repo_permissions', # repo_name, self.ip_addr, self.sa) Session().commit() h.flash(_('Repository Group permissions updated'), category='success') return redirect(url('edit_repo_group_perms', group_name=group_name))
def create(self): users_group_form = UserGroupForm()() try: form_result = users_group_form.to_python(dict(request.POST)) ug = UserGroupModel().create( name=form_result['users_group_name'], description=form_result['user_group_description'], owner=request.authuser.user_id, active=form_result['users_group_active']) gr = form_result['users_group_name'] action_logger(request.authuser, 'admin_created_users_group:%s' % gr, None, request.ip_addr) h.flash( h.HTML(_('Created user group %s')) % h.link_to(gr, url('edit_users_group', id=ug.users_group_id)), category='success') Session().commit() except formencode.Invalid as errors: return htmlfill.render( render('admin/user_groups/user_group_add.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 creation of user group %s') % request.POST.get('users_group_name'), category='error') raise HTTPFound(location=url('users_groups'))
def create(self): """POST /users_groups: Create a new item""" # url('users_groups') users_group_form = UserGroupForm()() try: form_result = users_group_form.to_python(dict(request.POST)) ug = UserGroupModel().create( name=form_result['users_group_name'], description=form_result['user_group_description'], owner=self.authuser.user_id, active=form_result['users_group_active']) gr = form_result['users_group_name'] action_logger(self.authuser, 'admin_created_users_group:%s' % gr, None, self.ip_addr, self.sa) h.flash(h.literal( _('Created user group %s') % h.link_to(h.escape(gr), url('edit_users_group', id=ug.users_group_id))), category='success') Session().commit() except formencode.Invalid, errors: return htmlfill.render( render('admin/user_groups/user_group_add.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False)
def create(self): self.__load_defaults() try: # CanWriteGroup validators checks permissions of this POST form_result = RepoForm(repo_groups=c.repo_groups, landing_revs=c.landing_revs_choices)() \ .to_python(dict(request.POST)) except formencode.Invalid as errors: log.info(errors) return htmlfill.render(render('admin/repos/repo_add.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, force_defaults=False, encoding="UTF-8") try: # create is done sometimes async on celery, db transaction # management is handled there. task = RepoModel().create(form_result, request.authuser.user_id) task_id = task.task_id except Exception: log.error(traceback.format_exc()) msg = (_('Error creating repository %s') % form_result.get('repo_name')) h.flash(msg, category='error') raise HTTPFound(location=url('home')) raise HTTPFound(location=h.url('repo_creating_home', repo_name=form_result['repo_name_full'], task_id=task_id))
def create(self): self.__load_defaults() form_result = {} try: # CanWriteGroup validators checks permissions of this POST form_result = RepoForm(repo_groups=c.repo_groups, landing_revs=c.landing_revs_choices)() \ .to_python(dict(request.POST)) # create is done sometimes async on celery, db transaction # management is handled there. task = RepoModel().create(form_result, request.authuser.user_id) task_id = task.task_id except formencode.Invalid as errors: log.info(errors) return htmlfill.render( render('admin/repos/repo_add.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, force_defaults=False, encoding="UTF-8") except Exception: log.error(traceback.format_exc()) msg = (_('Error creating repository %s') % form_result.get('repo_name')) h.flash(msg, category='error') raise HTTPFound(location=url('home')) raise HTTPFound(location=h.url('repo_creating_home', repo_name=form_result['repo_name_full'], task_id=task_id))
def edit_statistics(self, repo_name): """GET /repo_name/settings: Form to edit an existing item""" # url('edit_repo', repo_name=ID) c.repo_info = self._load_repo(repo_name) repo = c.repo_info.scm_instance if c.repo_info.stats: # this is on what revision we ended up so we add +1 for count last_rev = c.repo_info.stats.stat_on_revision + 1 else: last_rev = 0 c.stats_revision = last_rev c.repo_last_rev = repo.count() if repo.revisions else 0 if last_rev == 0 or c.repo_last_rev == 0: c.stats_percentage = 0 else: c.stats_percentage = '%.2f' % ((float( (last_rev)) / c.repo_last_rev) * 100) c.active = 'statistics' if request.POST: try: RepoModel().delete_stats(repo_name) Session().commit() except Exception, e: log.error(traceback.format_exc()) h.flash( _('An error occurred during deletion of repository stats'), category='error') return redirect(url('edit_repo_statistics', repo_name=c.repo_name))
def my_account_api_keys_add(self): lifetime = safe_int(request.POST.get('lifetime'), -1) description = request.POST.get('description') ApiKeyModel().create(self.authuser.user_id, description, lifetime) Session().commit() h.flash(_("Api key successfully created"), category='success') return redirect(url('my_account_api_keys'))
def my_account(self): """ GET /_admin/my_account Displays info about my account """ # url('my_account') c.active = 'profile' self.__load_data() c.perm_user = AuthUser(user_id=self.authuser.user_id) c.ip_addr = self.ip_addr 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': self.authuser.user_id, 'email': self.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(self.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 index(self, repo_name, revision, f_path, annotate=False): # redirect to given revision from form if given post_revision = request.POST.get('at_rev', None) if post_revision: cs = self.__get_cs(post_revision) # FIXME - unused! c.revision = revision c.changeset = self.__get_cs(revision) c.branch = request.GET.get('branch', None) c.f_path = f_path c.annotate = annotate cur_rev = c.changeset.revision # prev link try: prev_rev = c.db_repo_scm_instance.get_changeset(cur_rev).prev(c.branch) c.url_prev = url('files_home', repo_name=c.repo_name, revision=prev_rev.raw_id, f_path=f_path) if c.branch: c.url_prev += '?branch=%s' % c.branch except (ChangesetDoesNotExistError, VCSError): c.url_prev = '#' # next link try: next_rev = c.db_repo_scm_instance.get_changeset(cur_rev).next(c.branch) c.url_next = url('files_home', repo_name=c.repo_name, revision=next_rev.raw_id, f_path=f_path) if c.branch: c.url_next += '?branch=%s' % c.branch except (ChangesetDoesNotExistError, VCSError): c.url_next = '#' # files or dirs try: c.file = c.changeset.get_node(f_path) if c.file.is_file(): c.load_full_history = False file_last_cs = c.file.last_changeset c.file_changeset = (c.changeset if c.changeset.revision < file_last_cs.revision else file_last_cs) #determine if we're on branch head _branches = c.db_repo_scm_instance.branches c.on_branch_head = revision in _branches.keys() + _branches.values() _hist = [] c.file_history = [] if c.load_full_history: c.file_history, _hist = self._get_node_history(c.changeset, f_path) c.authors = [] for a in set([x.author for x in _hist]): c.authors.append((h.email(a), h.person(a))) else: c.authors = c.file_history = [] except RepositoryError, e: h.flash(safe_str(e), category='error') raise HTTPNotFound()
def index(self): org_repo = c.db_repo org_scm_instance = org_repo.scm_instance try: org_scm_instance.get_changeset() except EmptyRepositoryError as e: h.flash(_('There are no changesets yet'), category='warning') raise HTTPFound( location=url('summary_home', repo_name=org_repo.repo_name)) org_rev = request.GET.get('rev_end') # rev_start is not directly useful - its parent could however be used # as default for other and thus give a simple compare view rev_start = request.GET.get('rev_start') other_rev = None if rev_start: starters = org_repo.get_changeset(rev_start).parents if starters: other_rev = starters[0].raw_id else: other_rev = org_repo.scm_instance.EMPTY_CHANGESET branch = request.GET.get('branch') c.cs_repos = [(org_repo.repo_name, org_repo.repo_name)] c.default_cs_repo = org_repo.repo_name c.cs_refs, c.default_cs_ref = self._get_repo_refs(org_scm_instance, rev=org_rev, branch=branch) default_cs_ref_type, default_cs_branch, default_cs_rev = c.default_cs_ref.split( ':') if default_cs_ref_type != 'branch': default_cs_branch = org_repo.get_changeset(default_cs_rev).branch # add org repo to other so we can open pull request against peer branches on itself c.a_repos = [(org_repo.repo_name, '%s (self)' % org_repo.repo_name)] if org_repo.parent: # add parent of this fork also and select it. # use the same branch on destination as on source, if available. c.a_repos.append((org_repo.parent.repo_name, '%s (parent)' % org_repo.parent.repo_name)) c.a_repo = org_repo.parent c.a_refs, c.default_a_ref = self._get_repo_refs( org_repo.parent.scm_instance, branch=default_cs_branch, rev=other_rev) else: c.a_repo = org_repo c.a_refs, c.default_a_ref = self._get_repo_refs(org_scm_instance, rev=other_rev) # gather forks and add to this list ... even though it is rare to # request forks to pull from their parent for fork in org_repo.forks: c.a_repos.append((fork.repo_name, fork.repo_name)) return render('/pullrequests/pullrequest.html')
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 __load_data(self): c.user = User.get(self.authuser.user_id) if c.user.username == User.DEFAULT_USER: h.flash(_("You can't edit this user since it's" " crucial for entire application"), category='warning') return redirect(url('users')) c.EXTERN_TYPE_INTERNAL = EXTERN_TYPE_INTERNAL
def oauth2callback(self): """Handle oauth2 callback.""" state = request.GET.get('state') code = request.GET.get('code') plugin = KallitheaAuthPlugin() plugin.store_user_info(code=code) h.flash(_('Successfully authenticated'), 'success') redirect(state)
def comment(self, repo_name, revision): status = request.POST.get('changeset_status') text = request.POST.get('text', '').strip() or _('No comments.') c.co = comm = ChangesetCommentsModel().create( text=text, repo=c.db_repo.repo_id, user=c.authuser.user_id, revision=revision, f_path=request.POST.get('f_path'), line_no=request.POST.get('line'), status_change=(ChangesetStatus.get_status_lbl(status) if status else None)) # get status if set ! if status: # if latest status was from pull request and it's closed # disallow changing status ! # dont_allow_on_closed_pull_request = True ! try: ChangesetStatusModel().set_status( c.db_repo.repo_id, status, c.authuser.user_id, comm, revision=revision, dont_allow_on_closed_pull_request=True) except StatusChangeOnClosedPullRequestError: log.error(traceback.format_exc()) msg = _('Changing status on a changeset associated with ' 'a closed pull request is not allowed') h.flash(msg, category='warning') return redirect( h.url('changeset_home', repo_name=repo_name, revision=revision)) action_logger(self.authuser, 'user_commented_revision:%s' % revision, c.db_repo, self.ip_addr, self.sa) Session().commit() if not request.environ.get('HTTP_X_PARTIAL_XHR'): return redirect( h.url('changeset_home', repo_name=repo_name, revision=revision)) #only ajax below data = { 'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))), } if comm: data.update(comm.get_dict()) data.update({ 'rendered_text': render('changeset/changeset_comment_block.html') }) return data
def settings_global(self): """GET /admin/settings/global: All items in the collection""" # url('admin_settings_global') c.active = 'global' if request.POST: application_form = ApplicationSettingsForm()() try: form_result = application_form.to_python(dict(request.POST)) except formencode.Invalid as errors: return htmlfill.render( render('admin/settings/settings.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False) try: sett1 = Setting.create_or_update('title', form_result['title']) Session().add(sett1) sett2 = Setting.create_or_update('realm', form_result['realm']) Session().add(sett2) sett3 = Setting.create_or_update('ga_code', form_result['ga_code']) Session().add(sett3) sett4 = Setting.create_or_update('captcha_public_key', form_result['captcha_public_key']) Session().add(sett4) sett5 = Setting.create_or_update('captcha_private_key', form_result['captcha_private_key']) Session().add(sett5) Session().commit() set_app_settings(config) h.flash(_('Updated application settings'), category='success') except Exception: log.error(traceback.format_exc()) h.flash(_('Error occurred while updating ' 'application settings'), category='error') raise HTTPFound(location=url('admin_settings_global')) defaults = Setting.get_app_settings() defaults.update(self._get_hg_ui_settings()) return htmlfill.render( render('admin/settings/settings.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def index(self): org_repo = c.db_repo org_scm_instance = org_repo.scm_instance try: org_scm_instance.get_changeset() except EmptyRepositoryError, e: h.flash(h.literal(_('There are no changesets yet')), category='warning') redirect(url('summary_home', repo_name=org_repo.repo_name))
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 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_email(self, id): """DELETE /user_emails_delete/id: Delete an existing item""" # url('user_emails_delete', id=ID, method='delete') 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') return redirect(url('edit_user_emails', id=id))
def delete_repo_field(self, repo_name, field_id): field = RepositoryField.get_or_404(field_id) try: Session().delete(field) Session().commit() except Exception, e: log.error(traceback.format_exc()) msg = _('An error occurred during removal of field') h.flash(msg, category='error')