예제 #1
0
    def delete(self, repo_name):
        """DELETE /repos/repo_name: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('repo_settings_delete', repo_name=ID),
        #           method='delete')
        # url('repo_settings_delete', repo_name=ID)

        repo_model = RepoModel()
        repo = repo_model.get_by_repo_name(repo_name)
        if not repo:
            h.not_mapped_error(repo_name)
            return redirect(url('home'))
        try:
            action_logger(self.rhodecode_user, 'user_deleted_repo',
                              repo_name, self.ip_addr, self.sa)
            repo_model.delete(repo)
            invalidate_cache('get_repo_cached_%s' % repo_name)
            h.flash(_('deleted repository %s') % repo_name, category='success')
            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during deletion of %s') % repo_name,
                    category='error')

        return redirect(url('admin_settings_my_account', anchor='my'))
예제 #2
0
    def index(self, revision):

        c.anchor_url = anchor_url
        c.ignorews_url = _ignorews_url
        c.context_url = _context_url
        limit_off = request.GET.get('fulldiff')
        #get ranges of revisions if preset
        rev_range = revision.split('...')[:2]
        enable_comments = True
        try:
            if len(rev_range) == 2:
                enable_comments = False
                rev_start = rev_range[0]
                rev_end = rev_range[1]
                rev_ranges = c.rhodecode_repo.get_changesets(start=rev_start,
                                                            end=rev_end)
            else:
                rev_ranges = [c.rhodecode_repo.get_changeset(revision)]

            c.cs_ranges = list(rev_ranges)
            if not c.cs_ranges:
                raise RepositoryError('Changeset range returned empty result')

        except (RepositoryError, ChangesetDoesNotExistError, Exception), e:
            log.error(traceback.format_exc())
            h.flash(str(e), category='warning')
            return redirect(url('home'))
예제 #3
0
    def register(self):
        c.auto_active = 'hg.register.auto_activate' in User.get_default_user()\
            .AuthUser.permissions['global']

        if request.POST:
            register_form = RegisterForm()()
            try:
                form_result = register_form.to_python(dict(request.POST))
                form_result['active'] = c.auto_active
                UserModel().create_registration(form_result)
                h.flash(_('You have successfully registered into RhodeCode'),
                            category='success')
                Session().commit()
                return redirect(url('login_home'))

            except formencode.Invalid, errors:
                return htmlfill.render(
                    render('/register.html'),
                    defaults=errors.value,
                    errors=errors.error_dict or {},
                    prefix_error=False,
                    encoding="UTF-8")
            except UserCreationError, 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')
예제 #4
0
    def set_repo_perm_member(self, repo_name):
        form = RepoPermsForm()().to_python(request.POST)

        perms_new = form['perms_new']
        perms_updates = form['perms_updates']
        cur_repo = repo_name

        # update permissions
        for member, perm, member_type in perms_updates:
            if member_type == 'user':
                # this updates existing one
                RepoModel().grant_user_permission(
                    repo=cur_repo, user=member, perm=perm
                )
            else:
                RepoModel().grant_users_group_permission(
                    repo=cur_repo, group_name=member, perm=perm
                )
        # set new permissions
        for member, perm, member_type in perms_new:
            if member_type == 'user':
                RepoModel().grant_user_permission(
                    repo=cur_repo, user=member, perm=perm
                )
            else:
                RepoModel().grant_users_group_permission(
                    repo=cur_repo, group_name=member, perm=perm
                )
        #TODO: implement this
        #action_logger(self.rhodecode_user, 'admin_changed_repo_permissions',
        #              repo_name, self.ip_addr, self.sa)
        Session().commit()
        h.flash(_('Repository permissions updated'), category='success')
        return redirect(url('edit_repo', repo_name=repo_name))
예제 #5
0
    def my_account_update(self):
        """PUT /_admin/my_account_update: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('admin_settings_my_account_update'),
        #           method='put')
        # url('admin_settings_my_account_update', id=ID)
        user_model = UserModel()
        uid = self.rhodecode_user.user_id
        _form = UserForm(edit=True,
                         old_data={'user_id': uid,
                                   'email': self.rhodecode_user.email})()
        form_result = {}
        try:
            form_result = _form.to_python(dict(request.POST))
            user_model.update_my_account(uid, form_result)
            h.flash(_('Your account was updated successfully'),
                    category='success')
            Session.commit()
        except formencode.Invalid, errors:
            c.user = User.get(self.rhodecode_user.user_id)
            all_repos = self.sa.query(Repository)\
                .filter(Repository.user_id == c.user.user_id)\
                .order_by(func.lower(Repository.repo_name))\
                .all()
            c.user_repos = ScmModel().get_repos(all_repos)

            return htmlfill.render(
                render('admin/users/user_edit_my_account.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #6
0
    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_choices,
                             landing_revs=c.landing_revs_choices)()
        form_result = {}
        try:
            form_result = _form.to_python(dict(request.POST))

            # an approximation that is better than nothing
            if not RhodeCodeUi.get_by_key(RhodeCodeUi.HOOK_UPDATE).ui_active:
                form_result['update_after_clone'] = False

            # create fork is done sometimes async on celery, db transaction
            # management is handled there.
            RepoModel().create_fork(form_result, self.rhodecode_user.user_id)
            fork_url = h.link_to(form_result['repo_name_full'],
                    h.url('summary_home', repo_name=form_result['repo_name_full']))

            h.flash(h.literal(_('Forked repository %s as %s') \
                      % (repo_name, fork_url)),
                    category='success')
        except formencode.Invalid, errors:
            c.new_repo = errors.value['repo_name']

            return htmlfill.render(
                render('forks/fork.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #7
0
    def index(self):
        limit = 100
        default = 20
        if request.GET.get('size'):
            c.size = max(min(safe_int(request.GET.get('size')), limit), 1)
            session['changelog_size'] = c.size
            session.save()
        else:
            c.size = int(session.get('changelog_size', default))
        # min size must be 1
        c.size = max(c.size, 1)
        p = safe_int(request.GET.get('page', 1), 1)
        branch_name = request.GET.get('branch', None)
        try:
            if branch_name:
                collection = [z for z in
                              c.rhodecode_repo.get_changesets(start=0,
                                                    branch_name=branch_name)]
                c.total_cs = len(collection)
            else:
                collection = c.rhodecode_repo
                c.total_cs = len(c.rhodecode_repo)

            c.pagination = RepoPage(collection, page=p, item_count=c.total_cs,
                                    items_per_page=c.size, branch=branch_name)
            collection = list(c.pagination)
            page_revisions = [x.raw_id for x in collection]
            c.comments = c.rhodecode_db_repo.get_comments(page_revisions)
            c.statuses = c.rhodecode_db_repo.statuses(page_revisions)
        except (EmptyRepositoryError), e:
            h.flash(str(e), category='warning')
            return redirect(url('summary_home', repo_name=c.repo_name))
예제 #8
0
    def update(self, id):
        """PUT /repos_groups/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('repos_group', id=ID),
        #           method='put')
        # url('repos_group', id=ID)

        self.__load_defaults()
        c.repos_group = RepoGroup.get(id)

        repos_group_form = ReposGroupForm(
            edit=True,
            old_data=c.repos_group.get_dict(),
            available_groups=c.repo_groups_choices
        )()
        try:
            form_result = repos_group_form.to_python(dict(request.POST))
            ReposGroupModel().update(id, form_result)
            Session().commit()
            h.flash(_('updated repos group %s') \
                    % form_result['group_name'], category='success')
            #TODO: in future action_logger(, '', '', '', self.sa)
        except formencode.Invalid, errors:

            return htmlfill.render(
                render('admin/repos_groups/repos_groups_edit.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #9
0
    def ldap_settings(self):
        """POST ldap create and store ldap settings"""

        _form = LdapSettingsForm([x[0] for x in self.tls_reqcert_choices],
                                 [x[0] for x in self.search_scope_choices],
                                 [x[0] for x in self.tls_kind_choices])()

        try:
            form_result = _form.to_python(dict(request.POST))
            try:

                for k, v in form_result.items():
                    if k.startswith('ldap_'):
                        setting = RhodeCodeSettings.get_by_name(k)
                        setting.app_settings_value = v
                        self.sa.add(setting)

                self.sa.commit()
                h.flash(_('Ldap settings updated successfully'),
                    category='success')
            except (DatabaseError,):
                raise
        except LdapImportError:
            h.flash(_('Unable to activate ldap. The "python-ldap" library '
                      'is missing.'), category='warning')

        except formencode.Invalid, errors:
            e = errors.error_dict or {}

            return htmlfill.render(
                render('admin/ldap/ldap.html'),
                defaults=errors.value,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
예제 #10
0
파일: repos.py 프로젝트: elfixit/rhodecode
 def update(self, repo_name):
     """
     PUT /repos/repo_name: Update an existing item"""
     # Forms posted to this method should contain a hidden field:
     #    <input type="hidden" name="_method" value="PUT" />
     # Or using helpers:
     #    h.form(url('repo', repo_name=ID),
     #           method='put')
     # url('repo', repo_name=ID)
     self.__load_defaults()
     repo_model = RepoModel()
     changed_name = repo_name
     _form = RepoForm(edit=True, old_data={'repo_name': repo_name},
                      repo_groups=c.repo_groups_choices)()
     try:
         form_result = _form.to_python(dict(request.POST))
         repo = repo_model.update(repo_name, form_result)
         invalidate_cache('get_repo_cached_%s' % repo_name)
         h.flash(_('Repository %s updated successfully' % repo_name),
                 category='success')
         changed_name = repo.repo_name
         action_logger(self.rhodecode_user, 'admin_updated_repo',
                           changed_name, '', self.sa)
         Session.commit()
     except formencode.Invalid, errors:
         defaults = self.__load_data(repo_name)
         defaults.update(errors.value)
         return htmlfill.render(
             render('admin/repos/repo_edit.html'),
             defaults=defaults,
             errors=errors.error_dict or {},
             prefix_error=False,
             encoding="UTF-8")
예제 #11
0
    def edit(self, id, format='html'):
        """GET /users/id/edit: Form to edit an existing item"""
        # url('edit_user', id=ID)
        c.user = User.get_or_404(id)

        if c.user.username == 'default':
            h.flash(_("You can't edit this user"), category='warning')
            return redirect(url('users'))

        c.perm_user = AuthUser(user_id=id, ip_addr=self.ip_addr)
        c.user.permissions = {}
        c.granted_permissions = UserModel().fill_perms(c.user)\
            .permissions['global']
        c.user_email_map = UserEmailMap.query()\
                        .filter(UserEmailMap.user == c.user).all()
        c.user_ip_map = UserIpMap.query()\
                        .filter(UserIpMap.user == c.user).all()
        user_model = UserModel()
        c.ldap_dn = c.user.ldap_dn
        defaults = c.user.get_dict()
        defaults.update({
            'create_repo_perm': user_model.has_perm(id, 'hg.create.repository'),
            'fork_repo_perm': user_model.has_perm(id, 'hg.fork.repository'),
        })

        return htmlfill.render(
            render('admin/users/user_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
예제 #12
0
    def update(self, id):
        """PUT /permissions/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('permission', id=ID),
        #           method='put')
        # url('permission', id=ID)

        permission_model = PermissionModel()

        _form = DefaultPermissionsForm([x[0] for x in self.perms_choices],
                                       [x[0] for x in self.register_choices],
                                       [x[0] for x in self.create_choices])()

        try:
            form_result = _form.to_python(dict(request.POST))
            form_result.update({'perm_user_name': id})
            permission_model.update(form_result)
            h.flash(_('Default permissions updated successfully'),
                    category='success')

        except formencode.Invalid, errors:
            c.perms_choices = self.perms_choices
            c.register_choices = self.register_choices
            c.create_choices = self.create_choices
            defaults = errors.value

            return htmlfill.render(
                render('admin/permissions/permissions.html'),
                defaults=defaults,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #13
0
파일: auth.py 프로젝트: lmamsen/rhodecode
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        self.user = cls.rhodecode_user
        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.warning('Permission denied for %s %s', cls, self.user)


            anonymous = self.user.username == 'default'

            if anonymous:
                p = url.current()

                import rhodecode.lib.helpers as h
                h.flash(_('You need to be a 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)
예제 #14
0
    def update(self, id):
        """PUT /defaults/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('default', id=ID),
        #           method='put')
        # url('default', id=ID)

        _form = DefaultsForm()()

        try:
            form_result = _form.to_python(dict(request.POST))
            for k, v in form_result.iteritems():
                setting = RhodeCodeSetting.get_by_name_or_create(k)
                setting.app_settings_value = v
                Session().add(setting)
            Session().commit()
            h.flash(_('Default settings updated successfully'),
                    category='success')

        except formencode.Invalid, 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")
예제 #15
0
    def delete_repo_perm_member(self, repo_name):
        """
        DELETE an existing repository permission user

        :param 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'))

            if obj_type == 'user':
                RepoModel().revoke_user_permission(repo=repo_name, user=obj_id)
            elif obj_type == 'user_group':
                RepoModel().revoke_users_group_permission(
                    repo=repo_name, group_name=obj_id
                )
            #TODO: implement this
            #action_logger(self.rhodecode_user, 'admin_revoked_repo_permissions',
            #              repo_name, self.ip_addr, self.sa)
            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during revoking of permission'),
                    category='error')
            raise HTTPInternalServerError()
예제 #16
0
    def my_account(self):
        """
        GET /_admin/my_account Displays info about my account
        """
        # url('admin_settings_my_account')

        c.user = User.get(self.rhodecode_user.user_id)
        all_repos = self.sa.query(Repository)\
                     .filter(Repository.user_id == c.user.user_id)\
                     .order_by(func.lower(Repository.repo_name)).all()

        c.user_repos = ScmModel().get_repos(all_repos)

        if c.user.username == 'default':
            h.flash(_("You can't edit this user since it's"
              " crucial for entire application"), category='warning')
            return redirect(url('users'))

        defaults = c.user.get_dict()
        return htmlfill.render(
            render('admin/users/user_edit_my_account.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
예제 #17
0
    def index(self, revision):

        def wrap_to_table(str):

            return '''<table class="code-difftable">
                        <tr class="line">
                        <td class="lineno new"></td>
                        <td class="code"><pre>%s</pre></td>
                        </tr>
                      </table>''' % str

        #get ranges of revisions if preset
        rev_range = revision.split('...')[:2]

        try:
            if len(rev_range) == 2:
                rev_start = rev_range[0]
                rev_end = rev_range[1]
                rev_ranges = c.rhodecode_repo.get_changesets(start=rev_start,
                                                            end=rev_end)
            else:
                rev_ranges = [c.rhodecode_repo.get_changeset(revision)]

            c.cs_ranges = list(rev_ranges)

        except (RepositoryError, ChangesetDoesNotExistError, Exception), e:
            log.error(traceback.format_exc())
            h.flash(str(e), category='warning')
            return redirect(url('home'))
예제 #18
0
    def delete_user_group_perm_member(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.rhodecode_user.is_admin:
                if obj_type == 'user' and c.rhodecode_user.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_users_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()
예제 #19
0
파일: users.py 프로젝트: elfixit/rhodecode
    def update_perm(self, id):
        """PUT /users_perm/id: Update an existing item"""
        # url('user_perm', id=ID, method='put')

        grant_perm = request.POST.get('create_repo_perm', False)
        user_model = UserModel()

        if grant_perm:
            perm = Permission.get_by_key('hg.create.none')
            user_model.revoke_perm(id, perm)

            perm = Permission.get_by_key('hg.create.repository')
            user_model.grant_perm(id, perm)
            h.flash(_("Granted 'repository create' permission to user"),
                    category='success')
            Session.commit()
        else:
            perm = Permission.get_by_key('hg.create.repository')
            user_model.revoke_perm(id, perm)

            perm = Permission.get_by_key('hg.create.none')
            user_model.grant_perm(id, perm)
            h.flash(_("Revoked 'repository create' permission to user"),
                    category='success')
            Session.commit()
        return redirect(url('edit_user', id=id))
예제 #20
0
    def __get_rev_or_redirect(self, ref, repo, redirect_after=True,
                             partial=False):
        """
        Safe way to get changeset if error occur it redirects to changeset with
        proper message. If partial is set then don't do redirect raise Exception
        instead

        :param rev: revision to fetch
        :param repo: repo instance
        """

        rev = ref[1] # default and used for git
        if repo.scm_instance.alias == 'hg':
            # lookup up the exact node id
            _revset_predicates = {
                    'branch': 'branch',
                    'book': 'bookmark',
                    'tag': 'tag',
                    'rev': 'id',
                }
            rev_spec = "max(%s(%%s))" % _revset_predicates[ref[0]]
            revs = repo.scm_instance._repo.revs(rev_spec, safe_str(ref[1]))
            if revs:
                rev = revs[-1]
            # else: TODO: just report 'not found'

        try:
            return repo.scm_instance.get_changeset(rev).raw_id
        except EmptyRepositoryError, e:
            if not redirect_after:
                return None
            h.flash(h.literal(_('There are no changesets yet')),
                    category='warning')
            redirect(url('summary_home', repo_name=repo.repo_name))
예제 #21
0
    def index(self, repo_name, revision=None, f_path=None):
        p = safe_int(request.params.get('page', 1), 1)
        size = safe_int(request.params.get('size', 20), 20)
        collection = c.rhodecode_repo
        c.file_history = f_path

        def url_generator(**kw):
            if f_path:
                return url('shortlog_file_home', repo_name=repo_name,
                           revision=revision, f_path=f_path, size=size, **kw)
            return url('shortlog_home', repo_name=repo_name, size=size, **kw)

        if f_path:
            log.debug('generating shortlog for path %s' % f_path)
            # get the history for the file !
            tip_cs = c.rhodecode_repo.get_changeset()
            try:
                collection = tip_cs.get_file_history(f_path)
            except (NodeDoesNotExistError, ChangesetError):
                #this node is not present at tip !
                try:
                    cs = self.__get_cs_or_redirect(revision, repo_name)
                    collection = cs.get_file_history(f_path)
                except RepositoryError, e:
                    h.flash(str(e), category='warning')
                    redirect(h.url('shortlog_home', repo_name=repo_name))
            collection = list(reversed(collection))
예제 #22
0
    def create(self):
        """POST /repos_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
        repos_group_form = ReposGroupForm(available_groups=
                                map(lambda k: unicode(k[0]), c.repo_groups))()
        try:
            form_result = repos_group_form.to_python(dict(request.POST))
            ReposGroupModel().create(
                    group_name=form_result['group_name'],
                    group_description=form_result['group_description'],
                    parent=form_result['group_parent_id'],
                    owner=self.rhodecode_user.user_id
            )
            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/repos_groups/repos_groups_add.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #23
0
    def register(self):
        user_model = UserModel()
        c.auto_active = False
        for perm in user_model.get_by_username('default',
                                               cache=False).user_perms:
            if perm.permission.permission_name == 'hg.register.auto_activate':
                c.auto_active = True
                break

        if request.POST:

            register_form = RegisterForm()()
            try:
                form_result = register_form.to_python(dict(request.POST))
                form_result['active'] = c.auto_active
                user_model.create_registration(form_result)
                h.flash(_('You have successfully registered into rhodecode'),
                            category='success')
                return redirect(url('login_home'))

            except formencode.Invalid, errors:
                return htmlfill.render(
                    render('/register.html'),
                    defaults=errors.value,
                    errors=errors.error_dict or {},
                    prefix_error=False,
                    encoding="UTF-8")
예제 #24
0
파일: forks.py 프로젝트: break123/rhodecode
    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_choices,
                             landing_revs=c.landing_revs_choices)()
        form_result = {}
        try:
            form_result = _form.to_python(dict(request.POST))

            # create fork is done sometimes async on celery, db transaction
            # management is handled there.
            RepoModel().create_fork(form_result, self.rhodecode_user.user_id)
            h.flash(_('forked %s repository as %s') \
                      % (repo_name, form_result['repo_name']),
                    category='success')
        except formencode.Invalid, errors:
            c.new_repo = errors.value['repo_name']

            return htmlfill.render(
                render('forks/fork.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #25
0
    def my_account(self):
        """
        GET /_admin/my_account Displays info about my account
        """
        # url('admin_settings_my_account')

        c.user = User.get(self.rhodecode_user.user_id)
        c.perm_user = AuthUser(user_id=self.rhodecode_user.user_id,
                               ip_addr=self.ip_addr)
        c.ldap_dn = c.user.ldap_dn

        if c.user.username == 'default':
            h.flash(_("You can't edit this user since it's"
              " crucial for entire application"), category='warning')
            return redirect(url('users'))

        #json used to render the grid
        c.data = self._load_my_repos_data()

        defaults = c.user.get_dict()

        c.form = htmlfill.render(
            render('admin/users/user_edit_my_account_form.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
        return render('admin/users/user_edit_my_account.html')
예제 #26
0
    def comment(self, repo_name, revision):
        status = request.POST.get('changeset_status')
        change_status = request.POST.get('change_changeset_status')
        text = request.POST.get('text')
        if status and change_status:
            text = text or (_('Status change -> %s')
                            % ChangesetStatus.get_status_lbl(status))

        c.co = comm = ChangesetCommentsModel().create(
            text=text,
            repo=c.rhodecode_db_repo.repo_id,
            user=c.rhodecode_user.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 and change_status else None)
        )

        # get status if set !
        if status and change_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.rhodecode_db_repo.repo_id,
                    status,
                    c.rhodecode_user.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.rhodecode_user,
                      'user_commented_revision:%s' % revision,
                      c.rhodecode_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
예제 #27
0
파일: users.py 프로젝트: elfixit/rhodecode
    def update(self, id):
        """PUT /users/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('update_user', id=ID),
        #           method='put')
        # url('user', id=ID)
        user_model = UserModel()
        c.user = user_model.get(id)

        _form = UserForm(edit=True, old_data={'user_id': id,
                                              'email': c.user.email})()
        form_result = {}
        try:
            form_result = _form.to_python(dict(request.POST))
            user_model.update(id, form_result)
            h.flash(_('User updated successfully'), category='success')
            Session.commit()
        except formencode.Invalid, errors:
            e = errors.error_dict or {}
            perm = Permission.get_by_key('hg.create.repository')
            e.update({'create_repo_perm': user_model.has_perm(id, perm)})
            return htmlfill.render(
                render('admin/users/user_edit.html'),
                defaults=errors.value,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
예제 #28
0
    def create(self):
        """POST /repos_groups: Create a new item"""
        # url('repos_groups')
        self.__load_defaults()
        repos_group_form = ReposGroupForm(available_groups =
                                          c.repo_groups_choices)()
        try:
            form_result = repos_group_form.to_python(dict(request.POST))
            ReposGroupModel().create(
                    group_name=form_result['group_name'],
                    group_description=form_result['group_description'],
                    parent=form_result['group_parent_id']
            )
            Session().commit()
            h.flash(_('created repos group %s') \
                    % form_result['group_name'], category='success')
            #TODO: in futureaction_logger(, '', '', '', self.sa)
        except formencode.Invalid, errors:

            return htmlfill.render(
                render('admin/repos_groups/repos_groups_add.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #29
0
    def update(self, repo_name):
        self.__load_defaults()
        repo_model = RepoModel()
        changed_name = repo_name
        #override the choices with extracted revisions !
        choices, c.landing_revs = ScmModel().get_repo_landing_revs(repo_name)
        c.landing_revs_choices = choices

        _form = RepoSettingsForm(edit=True,
                                 old_data={'repo_name': repo_name},
                                 repo_groups=c.repo_groups_choices,
                                 landing_revs=c.landing_revs_choices)()
        try:
            form_result = _form.to_python(dict(request.POST))
            repo_model.update(repo_name, **form_result)
            invalidate_cache('get_repo_cached_%s' % repo_name)
            h.flash(_('Repository %s updated successfully') % repo_name,
                    category='success')
            changed_name = form_result['repo_name_full']
            action_logger(self.rhodecode_user, 'user_updated_repo',
                          changed_name, self.ip_addr, self.sa)
            Session().commit()
        except formencode.Invalid, errors:
            defaults = self.__load_data(repo_name)
            defaults.update(errors.value)
            return htmlfill.render(
                render('settings/repo_settings.html'),
                defaults=errors.value,
                errors=errors.error_dict or {},
                prefix_error=False,
                encoding="UTF-8")
예제 #30
0
파일: login.py 프로젝트: q210/rhodecode
    def register(self):
        user_model = UserModel()
        c.auto_active = False
        for perm in User.get_by_username("default").user_perms:
            if perm.permission.permission_name == "hg.register.auto_activate":
                c.auto_active = True
                break

        if request.POST:

            register_form = RegisterForm()()
            try:
                form_result = register_form.to_python(dict(request.POST))
                form_result["active"] = c.auto_active
                user_model.create_registration(form_result)
                h.flash(_("You have successfully registered into rhodecode"), category="success")
                return redirect(url("login_home"))

            except formencode.Invalid, errors:
                return htmlfill.render(
                    render("/register.html"),
                    defaults=errors.value,
                    errors=errors.error_dict or {},
                    prefix_error=False,
                    encoding="UTF-8",
                )
예제 #31
0
 def delete(self, id):
     """DELETE /users/id: Delete an existing item"""
     # Forms posted to this method should contain a hidden field:
     #    <input type="hidden" name="_method" value="DELETE" />
     # Or using helpers:
     #    h.form(url('delete_user', id=ID),
     #           method='delete')
     # url('user', id=ID)
     usr = User.get_or_404(id)
     try:
         UserModel().delete(usr)
         Session().commit()
         h.flash(_('Successfully deleted user'), category='success')
     except (UserOwnsReposException, DefaultUserException), e:
         h.flash(e, category='warning')
예제 #32
0
    def delete(self, id):
        """DELETE /users_groups/id: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('users_group', id=ID),
        #           method='delete')
        # url('users_group', id=ID)

        try:
            UsersGroupModel().delete(id)
            Session.commit()
            h.flash(_('successfully deleted users group'), category='success')
        except UsersGroupsAssignedException, e:
            h.flash(e, category='error')
예제 #33
0
    def update_global_perms(self, user_id):
        """PUT /users_perm/user_id: Update an existing item"""
        # url('user_perm', user_id=ID, method='put')
        user_id = safe_int(user_id)
        user = User.get_or_404(user_id)
        c.active = 'global_perms'
        try:
            # first stage that verifies the checkbox
            _form = UserIndividualPermissionsForm()
            form_result = _form.to_python(dict(request.POST))
            inherit_perms = form_result['inherit_default_permissions']
            user.inherit_default_permissions = inherit_perms
            Session().add(user)

            if not inherit_perms:
                # only update the individual ones if we un check the flag
                _form = UserPermissionsForm(
                    [x[0] for x in c.repo_create_choices],
                    [x[0] for x in c.repo_create_on_write_choices],
                    [x[0] for x in c.repo_group_create_choices],
                    [x[0] for x in c.user_group_create_choices],
                    [x[0] for x in c.fork_choices],
                    [x[0] for x in c.inherit_default_permission_choices])()

                form_result = _form.to_python(dict(request.POST))
                form_result.update({'perm_user_id': user.user_id})

                PermissionModel().update_user_permissions(form_result)

            Session().commit()
            h.flash(_('User global permissions updated successfully'),
                    category='success')

            Session().commit()
        except formencode.Invalid as errors:
            defaults = errors.value
            c.user = user
            return htmlfill.render(render('admin/users/user_edit.html'),
                                   defaults=defaults,
                                   errors=errors.error_dict or {},
                                   prefix_error=False,
                                   encoding="UTF-8",
                                   force_defaults=False)
        except Exception:
            log.exception("Exception during permissions saving")
            h.flash(_('An error occurred during permissions saving'),
                    category='error')
        return redirect(url('edit_user_global_perms', user_id=user_id))
예제 #34
0
    def ldap_settings(self):
        """POST ldap create and store ldap settings"""

        _form = LdapSettingsForm([x[0] for x in self.tls_reqcert_choices],
                                 [x[0] for x in self.search_scope_choices],
                                 [x[0] for x in self.tls_kind_choices])()
        # check the ldap lib
        ldap_active = False
        try:
            import ldap
            ldap_active = True
        except ImportError:
            pass

        try:
            form_result = _form.to_python(dict(request.POST))

            try:

                for k, v in form_result.items():
                    if k.startswith('ldap_'):
                        if k == 'ldap_active':
                            v = ldap_active
                        setting = RhodeCodeSetting.get_by_name(k)
                        setting.app_settings_value = v
                        Session().add(setting)

                Session().commit()
                h.flash(_('LDAP settings updated successfully'),
                        category='success')
                if not ldap_active:
                    #if ldap is missing send an info to user
                    h.flash(_(
                        'Unable to activate ldap. The "python-ldap" library '
                        'is missing.'),
                            category='warning')

            except (DatabaseError, ):
                raise

        except formencode.Invalid, errors:
            e = errors.error_dict or {}

            return htmlfill.render(render('admin/ldap/ldap.html'),
                                   defaults=errors.value,
                                   errors=e,
                                   prefix_error=False,
                                   encoding="UTF-8")
예제 #35
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        from rhodecode.lib import helpers as h

        # Provide the Pylons context to Pyramid's debugtoolbar if it asks
        if environ.get('debugtoolbar.wants_pylons_context', False):
            environ['debugtoolbar.pylons_context'] = c._current_obj()

        _route_name = '.'.join([environ['pylons.routes_dict']['controller'],
                                environ['pylons.routes_dict']['action']])

        self.rc_config = SettingsModel().get_all_settings(cache=True)
        self.ip_addr = get_ip_addr(environ)

        # The rhodecode auth user is looked up and passed through the
        # environ by the pylons compatibility tween in pyramid.
        # So we can just grab it from there.
        auth_user = environ['rc_auth_user']

        # set globals for auth user
        request.user = auth_user
        c.rhodecode_user = self._rhodecode_user = auth_user

        log.info('IP: %s User: %s accessed %s [%s]' % (
            self.ip_addr, auth_user, safe_unicode(get_access_path(environ)),
            _route_name)
        )

        # TODO: Maybe this should be move to pyramid to cover all views.
        # check user attributes for password change flag
        user_obj = auth_user.get_instance()
        if user_obj and user_obj.user_data.get('force_password_change'):
            h.flash('You are required to change your password', 'warning',
                    ignore_duplicate=True)

            skip_user_check_urls = [
                'error.document', 'login.logout', 'login.index',
                'admin/my_account.my_account_password',
                'admin/my_account.my_account_password_update'
            ]
            if _route_name not in skip_user_check_urls:
                return self._dispatch_redirect(
                    url('my_account_password'), environ, start_response)

        return WSGIController.__call__(self, environ, start_response)
예제 #36
0
    def update(self, user_group_id):
        """PUT /user_groups/user_group_id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('users_group', user_group_id=ID),
        #           method='put')
        # url('users_group', user_group_id=ID)

        user_group_id = safe_int(user_group_id)
        c.user_group = UserGroup.get_or_404(user_group_id)
        c.active = 'settings'
        self.__load_data(user_group_id)

        available_members = [safe_unicode(x[0]) for x in c.available_members]

        users_group_form = UserGroupForm(edit=True,
                                         old_data=c.user_group.get_dict(),
                                         available_members=available_members,
                                         allow_disabled=True)()

        try:
            form_result = users_group_form.to_python(request.POST)
            UserGroupModel().update(c.user_group, form_result)
            gr = form_result['users_group_name']
            action_logger(c.rhodecode_user,
                          'admin_updated_users_group:%s' % gr, None,
                          self.ip_addr, self.sa)
            h.flash(_('Updated user group %s') % gr, category='success')
            Session().commit()
        except formencode.Invalid as errors:
            defaults = errors.value
            e = errors.error_dict or {}

            return htmlfill.render(
                render('admin/user_groups/user_group_edit.html'),
                defaults=defaults,
                errors=e,
                prefix_error=False,
                encoding="UTF-8",
                force_defaults=False)
        except Exception:
            log.exception("Exception during update of user group")
            h.flash(_('Error occurred during update of user group %s') %
                    request.POST.get('users_group_name'),
                    category='error')

        return redirect(url('edit_users_group', user_group_id=user_group_id))
예제 #37
0
    def settings_visual_update(self):
        """POST /admin/settings/visual: All items in the collection"""
        # url('admin_settings_visual')
        c.active = 'visual'
        application_form = ApplicationVisualisationForm()()
        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:
            settings = [
                ('show_public_icon', 'rhodecode_show_public_icon', 'bool'),
                ('show_private_icon', 'rhodecode_show_private_icon', 'bool'),
                ('stylify_metatags', 'rhodecode_stylify_metatags', 'bool'),
                ('repository_fields', 'rhodecode_repository_fields', 'bool'),
                ('dashboard_items', 'rhodecode_dashboard_items', 'int'),
                ('admin_grid_items', 'rhodecode_admin_grid_items', 'int'),
                ('show_version', 'rhodecode_show_version', 'bool'),
                ('use_gravatar', 'rhodecode_use_gravatar', 'bool'),
                ('markup_renderer', 'rhodecode_markup_renderer', 'unicode'),
                ('gravatar_url', 'rhodecode_gravatar_url', 'unicode'),
                ('clone_uri_tmpl', 'rhodecode_clone_uri_tmpl', 'unicode'),
                ('support_url', 'rhodecode_support_url', 'unicode'),
                ('show_revision_number', 'rhodecode_show_revision_number',
                 'bool'),
                ('show_sha_length', 'rhodecode_show_sha_length', 'int'),
            ]
            for setting, form_key, type_ in settings:
                sett = SettingsModel().create_or_update_setting(
                    setting, form_result[form_key], type_)
                Session().add(sett)

            Session().commit()
            SettingsModel().invalidate_settings_cache()
            h.flash(_('Updated visualisation settings'), category='success')
        except Exception:
            log.exception("Exception updating visualization settings")
            h.flash(_('Error occurred during updating '
                      'visualisation settings'),
                    category='error')

        return redirect(url('admin_settings_visual'))
예제 #38
0
    def my_account_auth_tokens_delete(self):
        auth_token = request.POST.get('del_auth_token')
        user_id = c.rhodecode_user.user_id
        if request.POST.get('del_auth_token_builtin'):
            user = User.get(user_id)
            if user:
                user.api_key = generate_auth_token(user.username)
                Session().add(user)
                Session().commit()
                h.flash(_("Auth token successfully reset"), category='success')
        elif auth_token:
            AuthTokenModel().delete(auth_token, c.rhodecode_user.user_id)
            Session().commit()
            h.flash(_("Auth token successfully deleted"), category='success')

        return redirect(url('my_account_auth_tokens'))
예제 #39
0
    def delete_repos_group_user_perm(self, group_name):
        """
        DELETE an existing repositories group permission user

        :param group_name:
        """

        try:
            ReposGroupModel().revoke_user_permission(
                repos_group=group_name, user=request.POST['user_id'])
            Session.commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during deletion of group user'),
                    category='error')
            raise HTTPInternalServerError()
예제 #40
0
class ChangelogController(BaseRepoController):
    def __before__(self):
        super(ChangelogController, self).__before__()
        c.affected_files_cut_off = 60

    def __get_cs_or_redirect(self,
                             rev,
                             repo,
                             redirect_after=True,
                             partial=False):
        """
        Safe way to get changeset if error occur it redirects to changeset with
        proper message. If partial is set then don't do redirect raise Exception
        instead

        :param rev: revision to fetch
        :param repo: repo instance
        """

        try:
            return c.rhodecode_repo.get_changeset(rev)
        except EmptyRepositoryError, e:
            if not redirect_after:
                return None
            h.flash(h.literal(_('There are no changesets yet')),
                    category='warning')
            redirect(url('changelog_home', repo_name=repo.repo_name))

        except RepositoryError, e:
            log.error(traceback.format_exc())
            h.flash(safe_str(e), category='warning')
            if not partial:
                redirect(h.url('changelog_home', repo_name=repo.repo_name))
            raise HTTPBadRequest()
예제 #41
0
    def edit_emails(self, user_id):
        user_id = safe_int(user_id)
        c.user = User.get_or_404(user_id)
        if c.user.username == User.DEFAULT_USER:
            h.flash(_("You can't edit this user"), category='warning')
            return redirect(url('users'))

        c.active = 'emails'
        c.user_email_map = UserEmailMap.query() \
            .filter(UserEmailMap.user == c.user).all()

        defaults = c.user.get_dict()
        return htmlfill.render(render('admin/users/user_edit.html'),
                               defaults=defaults,
                               encoding="UTF-8",
                               force_defaults=False)
예제 #42
0
    def delete_ip(self, user_id):
        """DELETE /user_ips_delete/user_id: Delete an existing item"""
        # url('user_ips_delete', user_id=ID, method='delete')
        user_id = safe_int(user_id)
        c.user = User.get_or_404(user_id)

        ip_id = request.POST.get('del_ip_id')
        user_model = UserModel()
        user_model.delete_extra_ip(user_id, ip_id)
        Session().commit()
        h.flash(_("Removed ip address from user whitelist"),
                category='success')

        if 'default_user' in request.POST:
            return redirect(url('admin_permissions_ips'))
        return redirect(url('edit_user_ips', user_id=user_id))
예제 #43
0
파일: login.py 프로젝트: elfixit/rhodecode
    def password_reset(self):
        if request.POST:
            password_reset_form = PasswordResetForm()()
            try:
                form_result = password_reset_form.to_python(dict(request.POST))
                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")
예제 #44
0
파일: files.py 프로젝트: elfixit/rhodecode
class FilesController(BaseRepoController):
    @LoginRequired()
    def __before__(self):
        super(FilesController, self).__before__()
        c.cut_off_limit = self.cut_off_limit

    def __get_cs_or_redirect(self, rev, repo_name, redirect_after=True):
        """
        Safe way to get changeset if error occur it redirects to tip with
        proper message

        :param rev: revision to fetch
        :param repo_name: repo name to redirect after
        """

        try:
            return c.rhodecode_repo.get_changeset(rev)
        except EmptyRepositoryError, e:
            if not redirect_after:
                return None
            url_ = url('files_add_home',
                       repo_name=c.repo_name,
                       revision=0,
                       f_path='')
            add_new = '<a href="%s">[%s]</a>' % (url_, _('add new'))
            h.flash(h.literal(_('There are no files yet %s' % add_new)),
                    category='warning')
            redirect(h.url('summary_home', repo_name=repo_name))

        except RepositoryError, e:
            h.flash(str(e), category='warning')
            redirect(h.url('files_home', repo_name=repo_name, revision='tip'))
예제 #45
0
class FilesController(BaseRepoController):

    def __before__(self):
        super(FilesController, self).__before__()
        c.cut_off_limit = self.cut_off_limit

    def __get_cs_or_redirect(self, rev, repo_name, redirect_after=True):
        """
        Safe way to get changeset if error occur it redirects to tip with
        proper message

        :param rev: revision to fetch
        :param repo_name: repo name to redirect after
        """

        try:
            return c.rhodecode_repo.get_changeset(rev)
        except EmptyRepositoryError, e:
            if not redirect_after:
                return None
            url_ = url('files_add_home',
                       repo_name=c.repo_name,
                       revision=0, f_path='')
            add_new = h.link_to(_('Click here to add new file'), url_)
            h.flash(h.literal(_('There are no files yet %s') % add_new),
                    category='warning')
            redirect(h.url('summary_home', repo_name=repo_name))

        except RepositoryError, e:  # including ChangesetDoesNotExistError
            h.flash(str(e), category='error')
            raise HTTPNotFound()
예제 #46
0
    def repo_locking(self, repo_name):
        """
        Unlock repository when it is locked !

        :param repo_name:
        """

        try:
            repo = Repository.get_by_repo_name(repo_name)
            if request.POST.get('set_lock'):
                Repository.lock(repo, c.rhodecode_user.user_id)
            elif request.POST.get('set_unlock'):
                Repository.unlock(repo)
        except Exception, e:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during unlocking'), category='error')
예제 #47
0
    def update(self, id):
        """PUT /permissions/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('permission', id=ID),
        #           method='put')
        # url('permission', id=ID)
        if id == 'default':
            c.user = default_user = User.get_default_user()
            c.perm_user = AuthUser(user_id=default_user.user_id)
            c.user_ip_map = UserIpMap.query()\
                            .filter(UserIpMap.user == default_user).all()

            _form = DefaultPermissionsForm(
                [x[0] for x in c.repo_perms_choices],
                [x[0] for x in c.group_perms_choices],
                [x[0] for x in c.user_group_perms_choices],
                [x[0] for x in c.repo_create_choices],
                [x[0] for x in c.repo_group_create_choices],
                [x[0] for x in c.user_group_create_choices],
                [x[0] for x in c.fork_choices],
                [x[0] for x in c.register_choices],
                [x[0] for x in c.extern_activate_choices],
            )()

            try:
                form_result = _form.to_python(dict(request.POST))
                form_result.update({'perm_user_name': id})
                PermissionModel().update(form_result)
                Session().commit()
                h.flash(_('Default permissions updated successfully'),
                        category='success')

            except formencode.Invalid, errors:
                defaults = errors.value

                return htmlfill.render(
                    render('admin/permissions/permissions.html'),
                    defaults=defaults,
                    errors=errors.error_dict or {},
                    prefix_error=False,
                    encoding="UTF-8")
            except Exception:
                log.error(traceback.format_exc())
                h.flash(_('Error occurred during update of permissions'),
                        category='error')
예제 #48
0
    def create(self):
        """POST /repo_groups: Create a new item"""
        # url('repo_groups')

        parent_group_id = safe_int(request.POST.get('group_parent_id'))
        can_create = self._can_create_repo_group(parent_group_id)

        self.__load_defaults()
        # permissions for can create group based on parent_id are checked
        # here in the Form
        available_groups = map(lambda k: unicode(k[0]), c.repo_groups)
        repo_group_form = RepoGroupForm(available_groups=available_groups,
                                        can_create_in_root=can_create)()
        try:
            owner = c.rhodecode_user
            form_result = repo_group_form.to_python(dict(request.POST))
            RepoGroupModel().create(
                group_name=form_result['group_name_full'],
                group_description=form_result['group_description'],
                owner=owner.user_id,
                copy_permissions=form_result['group_copy_permissions'])
            Session().commit()
            _new_group_name = form_result['group_name_full']
            repo_group_url = h.link_to(
                _new_group_name,
                h.url('repo_group_home', group_name=_new_group_name))
            h.flash(h.literal(
                _('Created repository group %s') % repo_group_url),
                    category='success')
            # TODO: in futureaction_logger(, '', '', '', self.sa)
        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.exception("Exception during creation of repository group")
            h.flash(
                _('Error occurred during creation of repository group %s') %
                request.POST.get('group_name'),
                category='error')

        # TODO: maybe we should get back to the main view, not the admin one
        return redirect(url('repo_groups', parent_group=parent_group_id))
예제 #49
0
    def _meets_merge_pre_conditions(self, pull_request, user):
        if not PullRequestModel().check_user_merge(pull_request, user):
            raise HTTPForbidden()

        merge_status, msg = PullRequestModel().merge_status(pull_request)
        if not merge_status:
            log.debug("Cannot merge, not mergeable.")
            h.flash(msg, category='error')
            return False

        if (pull_request.calculated_review_status()
                is not ChangesetStatus.STATUS_APPROVED):
            log.debug("Cannot merge, approval is pending.")
            msg = _('Pull request reviewer approval is pending.')
            h.flash(msg, category='error')
            return False
        return True
예제 #50
0
    def __get_filenode_or_redirect(self, repo_name, cs, path):
        """
        Returns file_node, if error occurs or given path is directory,
        it'll redirect to top level path

        :param repo_name: repo_name
        :param cs: given changeset
        :param path: path to lookup
        """

        try:
            file_node = cs.get_node(path)
            if file_node.is_dir():
                raise RepositoryError('given path is a directory')
        except RepositoryError, e:
            h.flash(str(e), category='error')
            raise HTTPNotFound()
예제 #51
0
    def create(self, repo_name):
        repo = RepoModel()._get_repo(repo_name)
        try:
            _form = PullRequestForm(repo.repo_id)().to_python(request.POST)
        except formencode.Invalid, errors:
            log.error(traceback.format_exc())
            if errors.error_dict.get('revisions'):
                msg = 'Revisions: %s' % errors.error_dict['revisions']
            elif errors.error_dict.get('pullrequest_title'):
                msg = _('Pull request requires a title with min. 3 chars')
            else:
                msg = _('Error creating pull request: %s') % errors.msg

            h.flash(msg, 'error')
            return redirect(url(
                'pullrequest_home',
                repo_name=repo_name))  ## would rather just go back to form ...
예제 #52
0
    def update(self, id):
        """PUT /users_groups/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('users_group', id=ID),
        #           method='put')
        # url('users_group', id=ID)

        c.users_group = UserGroup.get_or_404(id)
        self._load_data(id)

        available_members = [safe_unicode(x[0]) for x in c.available_members]

        users_group_form = UserGroupForm(edit=True,
                                         old_data=c.users_group.get_dict(),
                                         available_members=available_members)()

        try:
            form_result = users_group_form.to_python(request.POST)
            UserGroupModel().update(c.users_group, form_result)
            gr = form_result['users_group_name']
            action_logger(self.rhodecode_user,
                          'admin_updated_users_group:%s' % gr, None,
                          self.ip_addr, self.sa)
            h.flash(_('Updated user group %s') % gr, category='success')
            Session().commit()
        except formencode.Invalid, errors:
            ug_model = UserGroupModel()
            defaults = errors.value
            e = errors.error_dict or {}
            defaults.update({
                'create_repo_perm':
                ug_model.has_perm(id, 'hg.create.repository'),
                'fork_repo_perm':
                ug_model.has_perm(id, 'hg.fork.repository'),
                '_method':
                'put'
            })

            return htmlfill.render(
                render('admin/users_groups/users_group_edit.html'),
                defaults=defaults,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
예제 #53
0
    def delete_perm_users_group(self, repo_name):
        """
        DELETE an existing repository permission user group

        :param repo_name:
        """

        try:
            RepoModel().revoke_users_group_permission(
                repo=repo_name, group_name=request.POST['users_group_id'])
            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during deletion of repository'
                      ' user groups'),
                    category='error')
            raise HTTPInternalServerError()
예제 #54
0
    def __load_data(self, repo_name=None):
        """
        Load defaults settings for edit, and update

        :param repo_name:
        """
        self.__load_defaults()

        c.repo_info = db_repo = Repository.get_by_repo_name(repo_name)
        repo = db_repo.scm_instance

        if c.repo_info is None:
            h.flash(_('%s repository is not mapped to db perhaps'
                      ' it was created or renamed from the filesystem'
                      ' please run the application again'
                      ' in order to rescan repositories') % repo_name,
                      category='error')

            return redirect(url('repos'))

        c.default_user_id = User.get_by_username('default').user_id
        c.in_public_journal = UserFollowing.query()\
            .filter(UserFollowing.user_id == c.default_user_id)\
            .filter(UserFollowing.follows_repository == c.repo_info).scalar()

        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)

        defaults = RepoModel()._get_defaults(repo_name)

        c.repos_list = [('', _('--REMOVE FORK--'))]
        c.repos_list += [(x.repo_id, x.repo_name) for x in
                   Repository.query().order_by(Repository.repo_name).all()]
        return defaults
예제 #55
0
    def update(self, id):
        """PUT /users_groups/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('users_group', id=ID),
        #           method='put')
        # url('users_group', id=ID)

        c.users_group = UsersGroup.get(id)
        c.group_members_obj = [x.user for x in c.users_group.members]
        c.group_members = [(x.user_id, x.username)
                           for x in c.group_members_obj]

        c.available_members = [(x.user_id, x.username)
                               for x in self.sa.query(User).all()]

        available_members = [safe_unicode(x[0]) for x in c.available_members]

        users_group_form = UsersGroupForm(
            edit=True,
            old_data=c.users_group.get_dict(),
            available_members=available_members)()

        try:
            form_result = users_group_form.to_python(request.POST)
            UsersGroupModel().update(c.users_group, form_result)
            h.flash(_('updated users group %s') \
                        % form_result['users_group_name'],
                    category='success')
            #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
            Session.commit()
        except formencode.Invalid, errors:
            e = errors.error_dict or {}

            perm = Permission.get_by_key('hg.create.repository')
            e.update(
                {'create_repo_perm': UsersGroupModel().has_perm(id, perm)})

            return htmlfill.render(
                render('admin/users_groups/users_group_edit.html'),
                defaults=errors.value,
                errors=e,
                prefix_error=False,
                encoding="UTF-8")
예제 #56
0
    def settings_issuetracker_save(self):
        settings_model = IssueTrackerSettingsModel()

        form = IssueTrackerPatternsForm()().to_python(request.POST)
        for uid in form['delete_patterns']:
            settings_model.delete_entries(uid)

        for pattern in form['patterns']:
            for setting, value, type_ in pattern:
                sett = settings_model.create_or_update_setting(
                    setting, value, type_)
                Session().add(sett)

            Session().commit()

        SettingsModel().invalidate_settings_cache()
        h.flash(_('Updated issue tracker entries'), category='success')
        return redirect(url('admin_settings_issuetracker'))
예제 #57
0
파일: files.py 프로젝트: elfixit/rhodecode
    def __get_filenode_or_redirect(self, repo_name, cs, path):
        """
        Returns file_node, if error occurs or given path is directory,
        it'll redirect to top level path

        :param repo_name: repo_name
        :param cs: given changeset
        :param path: path to lookup
        """

        try:
            file_node = cs.get_node(path)
            if file_node.is_dir():
                raise RepositoryError('given path is a directory')
        except RepositoryError, e:
            h.flash(str(e), category='warning')
            redirect(
                h.url('files_home', repo_name=repo_name, revision=cs.raw_id))
예제 #58
0
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        self.user = cls.rhodecode_user

        log.debug('Checking if user is not anonymous @%s' % cls)

        anonymous = self.user.username == 'default'

        if anonymous:
            p = url.current()

            import rhodecode.lib.helpers as h
            h.flash(_('You need to be a registered user to '
                      'perform this action'),
                    category='warning')
            return redirect(url('login_home', came_from=p))
        else:
            return func(*fargs, **fkwargs)
예제 #59
0
    def repo_as_fork(self, repo_name):
        """
        Mark given repository as a fork of another

        :param repo_name:
        """
        try:
            fork_id = request.POST.get('id_fork_of')
            repo = ScmModel().mark_as_fork(repo_name, fork_id,
                                           self.rhodecode_user.username)
            fork = repo.fork.repo_name if repo.fork else _('Nothing')
            Session().commit()
            h.flash(_('Marked repo %s as fork of %s') % (repo_name, fork),
                    category='success')
        except Exception, e:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during this operation'),
                    category='error')
예제 #60
0
    def delete_perm_user(self, repo_name):
        """
        DELETE an existing repository permission user

        :param repo_name:
        """
        try:
            RepoModel().revoke_user_permission(repo=repo_name,
                                               user=request.POST['user_id'])
            #TODO: implement this
            #action_logger(self.rhodecode_user, 'admin_revoked_repo_permissions',
            #              repo_name, self.ip_addr, self.sa)
            Session().commit()
        except Exception:
            log.error(traceback.format_exc())
            h.flash(_('An error occurred during deletion of repository user'),
                    category='error')
            raise HTTPInternalServerError()