Changeset - d208416c84c6
[Not reviewed]
Bradley M. Kuhn - 11 years ago 2014-07-03 01:05:10
bkuhn@sfconservancy.org
Rename rhodecode_user to authuser - it is an AuthUser instance
45 files changed with 176 insertions and 176 deletions:
0 comments (0 inline, 0 general)
kallithea/controllers/admin/gists.py
Show inline comments
 
@@ -60,46 +60,46 @@ class GistsController(BaseController):
 
            (str(60), _('1 hour')),
 
            (str(60 * 24), _('1 day')),
 
            (str(60 * 24 * 30), _('1 month')),
 
        ]
 
        if extra_values:
 
            c.lifetime_values.append(extra_values)
 
        c.lifetime_options = [(c.lifetime_values, _("Lifetime"))]
 

	
 
    @LoginRequired()
 
    def index(self):
 
        """GET /admin/gists: All items in the collection"""
 
        # url('gists')
 
        not_default_user = c.rhodecode_user.username != User.DEFAULT_USER
 
        not_default_user = c.authuser.username != User.DEFAULT_USER
 
        c.show_private = request.GET.get('private') and not_default_user
 
        c.show_public = request.GET.get('public') and not_default_user
 

	
 
        gists = Gist().query()\
 
            .filter(or_(Gist.gist_expires == -1, Gist.gist_expires >= time.time()))\
 
            .order_by(Gist.created_on.desc())
 

	
 
        # MY private
 
        if c.show_private and not c.show_public:
 
            gists = gists.filter(Gist.gist_type == Gist.GIST_PRIVATE)\
 
                             .filter(Gist.gist_owner == c.rhodecode_user.user_id)
 
                             .filter(Gist.gist_owner == c.authuser.user_id)
 
        # MY public
 
        elif c.show_public and not c.show_private:
 
            gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)\
 
                             .filter(Gist.gist_owner == c.rhodecode_user.user_id)
 
                             .filter(Gist.gist_owner == c.authuser.user_id)
 

	
 
        # MY public+private
 
        elif c.show_private and c.show_public:
 
            gists = gists.filter(or_(Gist.gist_type == Gist.GIST_PUBLIC,
 
                                     Gist.gist_type == Gist.GIST_PRIVATE))\
 
                             .filter(Gist.gist_owner == c.rhodecode_user.user_id)
 
                             .filter(Gist.gist_owner == c.authuser.user_id)
 

	
 
        # default show ALL public gists
 
        if not c.show_public and not c.show_private:
 
            gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)
 

	
 
        c.gists = gists
 
        p = safe_int(request.GET.get('page', 1), 1)
 
        c.gists_pager = Page(c.gists, page=p, items_per_page=10)
 
        return render('admin/gists/index.html')
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
@@ -113,25 +113,25 @@ class GistsController(BaseController):
 
            #TODO: multiple files support, from the form
 
            filename = form_result['filename'] or Gist.DEFAULT_FILENAME
 
            nodes = {
 
                filename: {
 
                    'content': form_result['content'],
 
                    'lexer': form_result['mimetype']  # None is autodetect
 
                }
 
            }
 
            _public = form_result['public']
 
            gist_type = Gist.GIST_PUBLIC if _public else Gist.GIST_PRIVATE
 
            gist = GistModel().create(
 
                description=form_result['description'],
 
                owner=c.rhodecode_user.user_id,
 
                owner=c.authuser.user_id,
 
                gist_mapping=nodes,
 
                gist_type=gist_type,
 
                lifetime=form_result['lifetime']
 
            )
 
            Session().commit()
 
            new_gist_id = gist.gist_access_id
 
        except formencode.Invalid, errors:
 
            defaults = errors.value
 

	
 
            return formencode.htmlfill.render(
 
                render('admin/gists/new.html'),
 
                defaults=defaults,
 
@@ -167,25 +167,25 @@ class GistsController(BaseController):
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def delete(self, gist_id):
 
        """DELETE /admin/gists/gist_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('gist', gist_id=ID),
 
        #           method='delete')
 
        # url('gist', gist_id=ID)
 
        gist = GistModel().get_gist(gist_id)
 
        owner = gist.gist_owner == c.rhodecode_user.user_id
 
        owner = gist.gist_owner == c.authuser.user_id
 
        if h.HasPermissionAny('hg.admin')() or owner:
 
            GistModel().delete(gist)
 
            Session().commit()
 
            h.flash(_('Deleted gist %s') % gist.gist_access_id, category='success')
 
        else:
 
            raise HTTPForbidden()
 

	
 
        return redirect(url('gists'))
 

	
 
    @LoginRequired()
 
    def show(self, gist_id, revision='tip', format='html', f_path=None):
 
        """GET /admin/gists/gist_id: Show a specific item"""
kallithea/controllers/admin/my_account.py
Show inline comments
 
@@ -54,82 +54,82 @@ class MyAccountController(BaseController
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('setting', 'settings', controller='admin/settings',
 
    #         path_prefix='/admin', name_prefix='admin_')
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def __before__(self):
 
        super(MyAccountController, self).__before__()
 

	
 
    def __load_data(self):
 
        c.user = User.get(self.rhodecode_user.user_id)
 
        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'))
 

	
 
    def _load_my_repos_data(self, watched=False):
 
        if watched:
 
            admin = False
 
            repos_list = [x.follows_repository for x in
 
                          Session().query(UserFollowing).filter(
 
                              UserFollowing.user_id ==
 
                              self.rhodecode_user.user_id).all()]
 
                              self.authuser.user_id).all()]
 
        else:
 
            admin = True
 
            repos_list = Session().query(Repository)\
 
                         .filter(Repository.user_id ==
 
                                 self.rhodecode_user.user_id)\
 
                                 self.authuser.user_id)\
 
                         .order_by(func.lower(Repository.repo_name)).all()
 

	
 
        repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
 
                                                   admin=admin)
 
        #json used to render the grid
 
        return json.dumps(repos_data)
 

	
 
    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.rhodecode_user.user_id,
 
        c.perm_user = AuthUser(user_id=self.authuser.user_id,
 
                               ip_addr=self.ip_addr)
 
        c.extern_type = c.user.extern_type
 
        c.extern_name = c.user.extern_name
 

	
 
        defaults = c.user.get_dict()
 
        update = False
 
        if request.POST:
 
            _form = UserForm(edit=True,
 
                             old_data={'user_id': self.rhodecode_user.user_id,
 
                                       'email': self.rhodecode_user.email})()
 
                             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']
 
                #TODO: plugin should define if username can be updated
 
                if c.extern_type != "rhodecode":
 
                    # forbid updating username for external accounts
 
                    skip_attrs.append('username')
 

	
 
                UserModel().update(self.rhodecode_user.user_id, form_result,
 
                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, errors:
 
                return htmlfill.render(
 
                    render('admin/my_account/my_account.html'),
 
                    defaults=errors.value,
 
                    errors=errors.error_dict or {},
 
                    prefix_error=False,
 
@@ -142,28 +142,28 @@ class MyAccountController(BaseController
 
            return redirect('my_account')
 
        return htmlfill.render(
 
            render('admin/my_account/my_account.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )
 

	
 
    def my_account_password(self):
 
        c.active = 'password'
 
        self.__load_data()
 
        if request.POST:
 
            _form = PasswordChangeForm(self.rhodecode_user.username)()
 
            _form = PasswordChangeForm(self.authuser.username)()
 
            try:
 
                form_result = _form.to_python(request.POST)
 
                UserModel().update(self.rhodecode_user.user_id, form_result)
 
                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")
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during update of user password'),
 
@@ -180,111 +180,111 @@ class MyAccountController(BaseController
 

	
 
    def my_account_watched(self):
 
        c.active = 'watched'
 
        self.__load_data()
 

	
 
        #json used to render the grid
 
        c.data = self._load_my_repos_data(watched=True)
 
        return render('admin/my_account/my_account.html')
 

	
 
    def my_account_perms(self):
 
        c.active = 'perms'
 
        self.__load_data()
 
        c.perm_user = AuthUser(user_id=self.rhodecode_user.user_id,
 
        c.perm_user = AuthUser(user_id=self.authuser.user_id,
 
                               ip_addr=self.ip_addr)
 

	
 
        return render('admin/my_account/my_account.html')
 

	
 
    def my_account_emails(self):
 
        c.active = 'emails'
 
        self.__load_data()
 

	
 
        c.user_email_map = UserEmailMap.query()\
 
            .filter(UserEmailMap.user == c.user).all()
 
        return render('admin/my_account/my_account.html')
 

	
 
    def my_account_emails_add(self):
 
        email = request.POST.get('new_email')
 

	
 
        try:
 
            UserModel().add_extra_email(self.rhodecode_user.user_id, email)
 
            UserModel().add_extra_email(self.authuser.user_id, email)
 
            Session().commit()
 
            h.flash(_("Added email %s to user") % email, category='success')
 
        except formencode.Invalid, error:
 
            msg = error.error_dict['email']
 
            h.flash(msg, category='error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during email saving'),
 
                    category='error')
 
        return redirect(url('my_account_emails'))
 

	
 
    def my_account_emails_delete(self):
 
        email_id = request.POST.get('del_email_id')
 
        user_model = UserModel()
 
        user_model.delete_extra_email(self.rhodecode_user.user_id, email_id)
 
        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 my_account_pullrequests(self):
 
        c.active = 'pullrequests'
 
        self.__load_data()
 
        c.show_closed = request.GET.get('pr_show_closed')
 

	
 
        def _filter(pr):
 
            s = sorted(pr, key=lambda o: o.created_on, reverse=True)
 
            if not c.show_closed:
 
                s = filter(lambda p: p.status != PullRequest.STATUS_CLOSED, s)
 
            return s
 

	
 
        c.my_pull_requests = _filter(PullRequest.query()\
 
                                .filter(PullRequest.user_id ==
 
                                        self.rhodecode_user.user_id)\
 
                                        self.authuser.user_id)\
 
                                .all())
 
        my_prs = [x.pull_request for x in PullRequestReviewers.query()
 
                    .filter(PullRequestReviewers.user_id ==
 
                        self.rhodecode_user.user_id).all()]
 
                        self.authuser.user_id).all()]
 
        c.participate_in_pull_requests = _filter(my_prs)
 
        return render('admin/my_account/my_account.html')
 

	
 
    def my_account_api_keys(self):
 
        c.active = 'api_keys'
 
        self.__load_data()
 
        show_expired = True
 
        c.lifetime_values = [
 
            (str(-1), _('forever')),
 
            (str(5), _('5 minutes')),
 
            (str(60), _('1 hour')),
 
            (str(60 * 24), _('1 day')),
 
            (str(60 * 24 * 30), _('1 month')),
 
        ]
 
        c.lifetime_options = [(c.lifetime_values, _("Lifetime"))]
 
        c.user_api_keys = ApiKeyModel().get_api_keys(self.rhodecode_user.user_id,
 
        c.user_api_keys = ApiKeyModel().get_api_keys(self.authuser.user_id,
 
                                                     show_expired=show_expired)
 
        return render('admin/my_account/my_account.html')
 

	
 
    def my_account_api_keys_add(self):
 
        lifetime = safe_int(request.POST.get('lifetime'), -1)
 
        description = request.POST.get('description')
 
        new_api_key = ApiKeyModel().create(self.rhodecode_user.user_id,
 
        new_api_key = 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_api_keys_delete(self):
 
        api_key = request.POST.get('del_api_key')
 
        user_id = self.rhodecode_user.user_id
 
        user_id = self.authuser.user_id
 
        if request.POST.get('del_api_key_builtin'):
 
            user = User.get(user_id)
 
            if user:
 
                user.api_key = generate_api_key(user.username)
 
                Session().add(user)
 
                Session().commit()
 
                h.flash(_("Api key successfully reset"), category='success')
 
        elif api_key:
 
            ApiKeyModel().delete(api_key, self.rhodecode_user.user_id)
 
            ApiKeyModel().delete(api_key, self.authuser.user_id)
 
            Session().commit()
 
            h.flash(_("Api key successfully deleted"), category='success')
 

	
 
        return redirect(url('my_account_api_keys'))
kallithea/controllers/admin/notifications.py
Show inline comments
 
@@ -50,115 +50,115 @@ class NotificationsController(BaseContro
 
    # file has a resource setup:
 
    #     map.resource('notification', 'notifications', controller='_admin/notifications',
 
    #         path_prefix='/_admin', name_prefix='_admin_')
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def __before__(self):
 
        super(NotificationsController, self).__before__()
 

	
 
    def index(self, format='html'):
 
        """GET /_admin/notifications: All items in the collection"""
 
        # url('notifications')
 
        c.user = self.rhodecode_user
 
        notif = NotificationModel().get_for_user(self.rhodecode_user.user_id,
 
        c.user = self.authuser
 
        notif = NotificationModel().get_for_user(self.authuser.user_id,
 
                                            filter_=request.GET.getall('type'))
 

	
 
        p = safe_int(request.GET.get('page', 1), 1)
 
        c.notifications = Page(notif, page=p, items_per_page=10)
 
        c.pull_request_type = Notification.TYPE_PULL_REQUEST
 
        c.comment_type = [Notification.TYPE_CHANGESET_COMMENT,
 
                          Notification.TYPE_PULL_REQUEST_COMMENT]
 

	
 
        _current_filter = request.GET.getall('type')
 
        c.current_filter = 'all'
 
        if _current_filter == [c.pull_request_type]:
 
            c.current_filter = 'pull_request'
 
        elif _current_filter == c.comment_type:
 
            c.current_filter = 'comment'
 

	
 
        return render('admin/notifications/notifications.html')
 

	
 
    def mark_all_read(self):
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            nm = NotificationModel()
 
            # mark all read
 
            nm.mark_all_read_for_user(self.rhodecode_user.user_id,
 
            nm.mark_all_read_for_user(self.authuser.user_id,
 
                                      filter_=request.GET.getall('type'))
 
            Session().commit()
 
            c.user = self.rhodecode_user
 
            notif = nm.get_for_user(self.rhodecode_user.user_id,
 
            c.user = self.authuser
 
            notif = nm.get_for_user(self.authuser.user_id,
 
                                    filter_=request.GET.getall('type'))
 
            c.notifications = Page(notif, page=1, items_per_page=10)
 
            return render('admin/notifications/notifications_data.html')
 

	
 
    def create(self):
 
        """POST /_admin/notifications: Create a new item"""
 
        # url('notifications')
 

	
 
    def new(self, format='html'):
 
        """GET /_admin/notifications/new: Form to create a new item"""
 
        # url('new_notification')
 

	
 
    def update(self, notification_id):
 
        """PUT /_admin/notifications/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('notification', notification_id=ID),
 
        #           method='put')
 
        # url('notification', notification_id=ID)
 
        try:
 
            no = Notification.get(notification_id)
 
            owner = all(un.user.user_id == c.rhodecode_user.user_id
 
            owner = all(un.user.user_id == c.authuser.user_id
 
                        for un in no.notifications_to_users)
 
            if h.HasPermissionAny('hg.admin')() or owner:
 
                # deletes only notification2user
 
                NotificationModel().mark_read(c.rhodecode_user.user_id, no)
 
                NotificationModel().mark_read(c.authuser.user_id, no)
 
                Session().commit()
 
                return 'ok'
 
        except Exception:
 
            Session().rollback()
 
            log.error(traceback.format_exc())
 
        raise HTTPBadRequest()
 

	
 
    def delete(self, notification_id):
 
        """DELETE /_admin/notifications/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('notification', notification_id=ID),
 
        #           method='delete')
 
        # url('notification', notification_id=ID)
 
        try:
 
            no = Notification.get(notification_id)
 
            owner = any(un.user.user_id == c.rhodecode_user.user_id
 
            owner = any(un.user.user_id == c.authuser.user_id
 
                        for un in no.notifications_to_users)
 
            if h.HasPermissionAny('hg.admin')() or owner:
 
                # deletes only notification2user
 
                NotificationModel().delete(c.rhodecode_user.user_id, no)
 
                NotificationModel().delete(c.authuser.user_id, no)
 
                Session().commit()
 
                return 'ok'
 
        except Exception:
 
            Session().rollback()
 
            log.error(traceback.format_exc())
 
        raise HTTPBadRequest()
 

	
 
    def show(self, notification_id, format='html'):
 
        """GET /_admin/notifications/id: Show a specific item"""
 
        # url('notification', notification_id=ID)
 
        c.user = self.rhodecode_user
 
        c.user = self.authuser
 
        no = Notification.get(notification_id)
 

	
 
        owner = any(un.user.user_id == c.rhodecode_user.user_id
 
        owner = any(un.user.user_id == c.authuser.user_id
 
                    for un in no.notifications_to_users)
 
        repo_admin = h.HasRepoPermissionAny('repository.admin')
 
        if no and (h.HasPermissionAny('hg.admin')() or repo_admin or owner):
 
            unotification = NotificationModel()\
 
                            .get_user_notification(c.user.user_id, no)
 

	
 
            # if this association to user is not valid, we don't want to show
 
            # this message
 
            if unotification:
 
                if not unotification.read:
 
                    unotification.mark_as_read()
 
                    Session().commit()
kallithea/controllers/admin/repo_groups.py
Show inline comments
 
@@ -97,27 +97,27 @@ class RepoGroupsController(BaseControlle
 
        for p in repo_group.repo_group_to_perm:
 
            data.update({'u_perm_%s' % p.user.username:
 
                             p.permission.permission_name})
 

	
 
        # fill repository group groups
 
        for p in repo_group.users_group_to_perm:
 
            data.update({'g_perm_%s' % p.users_group.users_group_name:
 
                             p.permission.permission_name})
 

	
 
        return data
 

	
 
    def _revoke_perms_on_yourself(self, form_result):
 
        _up = filter(lambda u: c.rhodecode_user.username == u[0],
 
        _up = filter(lambda u: c.authuser.username == u[0],
 
                     form_result['perms_updates'])
 
        _new = filter(lambda u: c.rhodecode_user.username == u[0],
 
        _new = filter(lambda u: c.authuser.username == u[0],
 
                      form_result['perms_new'])
 
        if _new and _new[0][1] != 'group.admin' or _up and _up[0][1] != 'group.admin':
 
            return True
 
        return False
 

	
 
    def index(self, format='html'):
 
        """GET /repo_groups: All items in the collection"""
 
        # url('repos_groups')
 
        _list = RepoGroup.query()\
 
                    .order_by(func.lower(RepoGroup.group_name))\
 
                    .all()
 
        group_iter = RepoGroupList(_list, perm_set=['group.admin'])
 
@@ -168,25 +168,25 @@ class RepoGroupsController(BaseControlle
 
        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.rhodecode_user.user_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,
 
@@ -403,61 +403,61 @@ class RepoGroupsController(BaseControlle
 

	
 
    @HasRepoGroupPermissionAnyDecorator('group.admin')
 
    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.rhodecode_user.is_admin:
 
        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.rhodecode_user, 'admin_changed_repo_permissions',
 
        #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))
 

	
 
    @HasRepoGroupPermissionAnyDecorator('group.admin')
 
    def delete_perms(self, group_name):
 
        """
 
        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:
 
            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')
 
            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',
kallithea/controllers/admin/repos.py
Show inline comments
 
@@ -134,25 +134,25 @@ class ReposController(BaseRepoController
 

	
 
        self.__load_defaults()
 
        form_result = {}
 
        task_id = None
 
        try:
 
            # CanWriteToGroup validators checks permissions of this POST
 
            form_result = RepoForm(repo_groups=c.repo_groups_choices,
 
                                   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, self.rhodecode_user.user_id)
 
            task = RepoModel().create(form_result, self.authuser.user_id)
 
            from celery.result import BaseAsyncResult
 
            if isinstance(task, BaseAsyncResult):
 
                task_id = task.task_id
 
        except formencode.Invalid, errors:
 
            return htmlfill.render(
 
                render('admin/repos/repo_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 

	
 
        except Exception:
 
@@ -278,25 +278,25 @@ class ReposController(BaseRepoController
 
        }
 
        _form = RepoForm(edit=True, old_data=old_data,
 
                         repo_groups=c.repo_groups_choices,
 
                         landing_revs=c.landing_revs_choices)()
 

	
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            repo = repo_model.update(repo_name, **form_result)
 
            ScmModel().mark_for_invalidation(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',
 
            action_logger(self.authuser, 'admin_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('admin/repos/repo_edit.html'),
 
                defaults=defaults,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 

	
 
@@ -325,25 +325,25 @@ class ReposController(BaseRepoController
 
        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(self.rhodecode_user, 'admin_deleted_repo',
 
            action_logger(self.authuser, 'admin_deleted_repo',
 
                  repo_name, self.ip_addr, self.sa)
 
            ScmModel().mark_for_invalidation(repo_name)
 
            h.flash(_('Deleted repository %s') % repo_name, category='success')
 
            Session().commit()
 
        except AttachedForksError:
 
            h.flash(_('Cannot delete %s it still contains attached 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')
 
@@ -385,47 +385,47 @@ class ReposController(BaseRepoController
 

	
 
        return htmlfill.render(
 
            render('admin/repos/repo_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 

	
 
    def edit_permissions_update(self, repo_name):
 
        form = RepoPermsForm()().to_python(request.POST)
 
        RepoModel()._update_permissions(repo_name, form['perms_new'],
 
                                        form['perms_updates'])
 
        #TODO: implement this
 
        #action_logger(self.rhodecode_user, 'admin_changed_repo_permissions',
 
        #action_logger(self.authuser, '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_perms', repo_name=repo_name))
 

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

	
 
            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
 
                )
 
            #TODO: implement this
 
            #action_logger(self.rhodecode_user, 'admin_revoked_repo_permissions',
 
            #action_logger(self.authuser, '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()
 

	
 
    @HasRepoPermissionAllDecorator('repository.admin')
 
    def edit_fields(self, repo_name):
 
        """GET /repo_name/settings: Form to edit an existing item"""
 
        # url('edit_repo', repo_name=ID)
 
@@ -531,50 +531,50 @@ class ReposController(BaseRepoController
 

	
 

	
 
    @HasRepoPermissionAllDecorator('repository.admin')
 
    def edit_advanced_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)
 
                                           self.authuser.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 RepositoryError, e:
 
            log.error(traceback.format_exc())
 
            h.flash(str(e), category='error')
 
        except Exception, e:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during this operation'),
 
                    category='error')
 

	
 
        return redirect(url('edit_repo_advanced', repo_name=repo_name))
 

	
 
    @HasRepoPermissionAllDecorator('repository.admin')
 
    def edit_advanced_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)
 
                Repository.lock(repo, c.authuser.user_id)
 
                h.flash(_('Locked repository'), category='success')
 
            elif request.POST.get('set_unlock'):
 
                Repository.unlock(repo)
 
                h.flash(_('Unlocked repository'), category='success')
 
        except Exception, e:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during unlocking'),
 
                    category='error')
 
        return redirect(url('edit_repo_advanced', repo_name=repo_name))
 

	
 
    @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
 
    def toggle_locking(self, repo_name):
 
@@ -583,25 +583,25 @@ class ReposController(BaseRepoController
 

	
 
        :param repo_name:
 
        """
 

	
 
        try:
 
            repo = Repository.get_by_repo_name(repo_name)
 

	
 
            if repo.enable_locking:
 
                if repo.locked[0]:
 
                    Repository.unlock(repo)
 
                    action = _('Unlocked')
 
                else:
 
                    Repository.lock(repo, c.rhodecode_user.user_id)
 
                    Repository.lock(repo, c.authuser.user_id)
 
                    action = _('Locked')
 

	
 
                h.flash(_('Repository has been %s') % action,
 
                        category='success')
 
        except Exception, e:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during unlocking'),
 
                    category='error')
 
        return redirect(url('summary_home', repo_name=repo_name))
 

	
 
    @HasRepoPermissionAllDecorator('repository.admin')
 
    def edit_caches(self, repo_name):
 
@@ -622,25 +622,25 @@ class ReposController(BaseRepoController
 

	
 
            return redirect(url('edit_repo_caches', repo_name=c.repo_name))
 
        return render('admin/repos/repo_edit.html')
 

	
 
    @HasRepoPermissionAllDecorator('repository.admin')
 
    def edit_remote(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)
 
        c.active = 'remote'
 
        if request.POST:
 
            try:
 
                ScmModel().pull_changes(repo_name, self.rhodecode_user.username)
 
                ScmModel().pull_changes(repo_name, self.authuser.username)
 
                h.flash(_('Pulled from remote location'), category='success')
 
            except Exception, e:
 
                log.error(traceback.format_exc())
 
                h.flash(_('An error occurred during pull from remote location'),
 
                        category='error')
 
            return redirect(url('edit_repo_remote', repo_name=c.repo_name))
 
        return render('admin/repos/repo_edit.html')
 

	
 
    @HasRepoPermissionAllDecorator('repository.admin')
 
    def edit_statistics(self, repo_name):
 
        """GET /repo_name/settings: Form to edit an existing item"""
 
        # url('edit_repo', repo_name=ID)
kallithea/controllers/admin/user_groups.py
Show inline comments
 
@@ -129,29 +129,29 @@ class UserGroupsController(BaseControlle
 
        return render('admin/user_groups/user_groups.html')
 

	
 
    @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
 
    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))
 
            UserGroupModel().create(name=form_result['users_group_name'],
 
                                    description=form_result['user_group_description'],
 
                                    owner=self.rhodecode_user.user_id,
 
                                    owner=self.authuser.user_id,
 
                                    active=form_result['users_group_active'])
 

	
 
            gr = form_result['users_group_name']
 
            action_logger(self.rhodecode_user,
 
            action_logger(self.authuser,
 
                          'admin_created_users_group:%s' % gr,
 
                          None, self.ip_addr, self.sa)
 
            h.flash(_('Created user group %s') % gr, 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")
 
        except Exception:
 
@@ -182,25 +182,25 @@ class UserGroupsController(BaseControlle
 
        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.user_group.get_dict(),
 
                                         available_members=available_members)()
 

	
 
        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(self.rhodecode_user,
 
            action_logger(self.authuser,
 
                          '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,
 
@@ -300,47 +300,47 @@ class UserGroupsController(BaseControlle
 
        """
 
        user_group = UserGroup.get_or_404(id)
 
        form = UserGroupPermsForm()().to_python(request.POST)
 

	
 
        # set the permissions !
 
        try:
 
            UserGroupModel()._update_permissions(user_group, form['perms_new'],
 
                                                 form['perms_updates'])
 
        except RepoGroupAssignmentError:
 
            h.flash(_('Target group cannot be the same'), category='error')
 
            return redirect(url('edit_user_group_perms', id=id))
 
        #TODO: implement this
 
        #action_logger(self.rhodecode_user, 'admin_changed_repo_permissions',
 
        #action_logger(self.authuser, 'admin_changed_repo_permissions',
 
        #              repo_name, self.ip_addr, self.sa)
 
        Session().commit()
 
        h.flash(_('User Group permissions updated'), category='success')
 
        return redirect(url('edit_user_group_perms', id=id))
 

	
 
    @HasUserGroupPermissionAnyDecorator('usergroup.admin')
 
    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.rhodecode_user.is_admin:
 
                if obj_type == 'user' and c.rhodecode_user.user_id == obj_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())
kallithea/controllers/admin/users.py
Show inline comments
 
@@ -119,25 +119,25 @@ class UsersController(BaseController):
 
        return render('admin/users/users.html')
 

	
 
    def create(self):
 
        """POST /users: Create a new item"""
 
        # url('users')
 
        c.default_extern_type = auth_modules.auth_rhodecode.RhodeCodeAuthPlugin.name
 
        user_model = UserModel()
 
        user_form = UserForm()()
 
        try:
 
            form_result = user_form.to_python(dict(request.POST))
 
            user_model.create(form_result)
 
            usr = form_result['username']
 
            action_logger(self.rhodecode_user, 'admin_created_user:%s' % usr,
 
            action_logger(self.authuser, 'admin_created_user:%s' % usr,
 
                          None, self.ip_addr, self.sa)
 
            h.flash(_('Created user %s') % usr,
 
                    category='success')
 
            Session().commit()
 
        except formencode.Invalid, errors:
 
            return htmlfill.render(
 
                render('admin/users/user_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 
        except UserCreationError, e:
 
@@ -172,25 +172,25 @@ class UsersController(BaseController):
 
                                              'email': c.user.email})()
 
        form_result = {}
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            skip_attrs = ['extern_type', 'extern_name']
 
            #TODO: plugin should define if username can be updated
 
            if c.extern_type != "rhodecode":
 
                # forbid updating username for external accounts
 
                skip_attrs.append('username')
 

	
 
            user_model.update(id, form_result, skip_attrs=skip_attrs)
 
            usr = form_result['username']
 
            action_logger(self.rhodecode_user, 'admin_updated_user:%s' % usr,
 
            action_logger(self.authuser, 'admin_updated_user:%s' % usr,
 
                          None, self.ip_addr, self.sa)
 
            h.flash(_('User updated successfully'), category='success')
 
            Session().commit()
 
        except formencode.Invalid, errors:
 
            defaults = errors.value
 
            e = errors.error_dict or {}
 
            defaults.update({
 
                'create_repo_perm': user_model.has_perm(id,
 
                                                        'hg.create.repository'),
 
                'fork_repo_perm': user_model.has_perm(id, 'hg.fork.repository'),
 
                '_method': 'put'
 
            })
kallithea/controllers/api/__init__.py
Show inline comments
 
@@ -180,26 +180,26 @@ class JSONRPCController(WSGIController):
 
        # self.kargs and dispatch control to WGIController
 
        argspec = inspect.getargspec(self._func)
 
        arglist = argspec[0][1:]
 
        defaults = map(type, argspec[3] or [])
 
        default_empty = types.NotImplementedType
 

	
 
        # kw arguments required by this method
 
        func_kwargs = dict(izip_longest(reversed(arglist), reversed(defaults),
 
                                        fillvalue=default_empty))
 

	
 
        # this is little trick to inject logged in user for
 
        # perms decorators to work they expect the controller class to have
 
        # rhodecode_user attribute set
 
        self.rhodecode_user = auth_u
 
        # authuser attribute set
 
        self.authuser = auth_u
 

	
 
        # This attribute will need to be first param of a method that uses
 
        # api_key, which is translated to instance of user at that name
 
        USER_SESSION_ATTR = 'apiuser'
 

	
 
        if USER_SESSION_ATTR not in arglist:
 
            return jsonrpc_error(
 
                retid=self._req_id,
 
                message='This method [%s] does not support '
 
                         'authentication (missing %s param)' % (
 
                                    self._func.__name__, USER_SESSION_ATTR)
 
            )
kallithea/controllers/api/api.py
Show inline comments
 
@@ -187,25 +187,25 @@ class ApiController(JSONRPCController):
 
          id : <id_given_in_input>
 
          result : null
 
          error :  {
 
            "Unable to pull changes from `<reponame>`"
 
          }
 

	
 
        """
 

	
 
        repo = get_repo_or_error(repoid)
 

	
 
        try:
 
            ScmModel().pull_changes(repo.repo_name,
 
                                    self.rhodecode_user.username)
 
                                    self.authuser.username)
 
            return dict(
 
                msg='Pulled from `%s`' % repo.repo_name,
 
                repository=repo.repo_name
 
            )
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError(
 
                'Unable to pull changes from `%s`' % repo.repo_name
 
            )
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def rescan_repos(self, apiuser, remove_obsolete=Optional(False)):
kallithea/controllers/changeset.py
Show inline comments
 
@@ -347,55 +347,55 @@ class ChangesetController(BaseRepoContro
 
    @jsonify
 
    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.db_repo.repo_id,
 
            user=c.rhodecode_user.user_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 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.db_repo.repo_id,
 
                    status,
 
                    c.rhodecode_user.user_id,
 
                    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.rhodecode_user,
 
        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'))),
 
        }
 
@@ -416,25 +416,25 @@ class ChangesetController(BaseRepoContro
 
        text = request.POST.get('text')
 
        if text:
 
            return h.rst_w_mentions(text)
 
        return ''
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    @jsonify
 
    def delete_comment(self, repo_name, comment_id):
 
        co = ChangesetComment.get(comment_id)
 
        owner = co.author.user_id == c.rhodecode_user.user_id
 
        owner = co.author.user_id == c.authuser.user_id
 
        repo_admin = h.HasRepoPermissionAny('repository.admin')
 
        if h.HasPermissionAny('hg.admin')() or repo_admin or owner:
 
            ChangesetCommentsModel().delete(comment=co)
 
            Session().commit()
 
            return True
 
        else:
 
            raise HTTPForbidden()
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    @jsonify
kallithea/controllers/files.py
Show inline comments
 
@@ -313,37 +313,37 @@ class FilesController(BaseRepoController
 
            return redirect(h.url('files_home',
 
                                  repo_name=repo_name, revision='tip',
 
                                  f_path=f_path))
 

	
 
        r_post = request.POST
 

	
 
        c.cs = self.__get_cs_or_redirect(revision, repo_name)
 
        c.file = self.__get_filenode_or_redirect(repo_name, c.cs, f_path)
 

	
 
        c.default_message = _('Deleted file %s via RhodeCode') % (f_path)
 
        c.f_path = f_path
 
        node_path = f_path
 
        author = self.rhodecode_user.full_contact
 
        author = self.authuser.full_contact
 

	
 
        if r_post:
 
            message = r_post.get('message') or c.default_message
 

	
 
            try:
 
                nodes = {
 
                    node_path: {
 
                        'content': ''
 
                    }
 
                }
 
                self.scm_model.delete_nodes(
 
                    user=c.rhodecode_user.user_id, repo=c.db_repo,
 
                    user=c.authuser.user_id, repo=c.db_repo,
 
                    message=message,
 
                    nodes=nodes,
 
                    parent_cs=c.cs,
 
                    author=author,
 
                )
 

	
 
                h.flash(_('Successfully deleted file %s') % f_path,
 
                        category='success')
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during commit'), category='error')
 
            return redirect(url('changeset_home',
 
@@ -386,34 +386,34 @@ class FilesController(BaseRepoController
 
        c.f_path = f_path
 

	
 
        if r_post:
 

	
 
            old_content = c.file.content
 
            sl = old_content.splitlines(1)
 
            first_line = sl[0] if sl else ''
 
            # modes:  0 - Unix, 1 - Mac, 2 - DOS
 
            mode = detect_mode(first_line, 0)
 
            content = convert_line_endings(r_post.get('content', ''), mode)
 

	
 
            message = r_post.get('message') or c.default_message
 
            author = self.rhodecode_user.full_contact
 
            author = self.authuser.full_contact
 

	
 
            if content == old_content:
 
                h.flash(_('No changes'), category='warning')
 
                return redirect(url('changeset_home', repo_name=c.repo_name,
 
                                    revision='tip'))
 
            try:
 
                self.scm_model.commit_change(repo=c.db_repo_scm_instance,
 
                                             repo_name=repo_name, cs=c.cs,
 
                                             user=self.rhodecode_user.user_id,
 
                                             user=self.authuser.user_id,
 
                                             author=author, message=message,
 
                                             content=content, f_path=f_path)
 
                h.flash(_('Successfully committed to %s') % f_path,
 
                        category='success')
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during commit'), category='error')
 
            return redirect(url('changeset_home',
 
                                repo_name=c.repo_name, revision='tip'))
 

	
 
        return render('files/files_edit.html')
 

	
 
@@ -457,34 +457,34 @@ class FilesController(BaseRepoController
 

	
 
            if not content:
 
                h.flash(_('No content'), category='warning')
 
                return redirect(url('changeset_home', repo_name=c.repo_name,
 
                                    revision='tip'))
 
            if not filename:
 
                h.flash(_('No filename'), category='warning')
 
                return redirect(url('changeset_home', repo_name=c.repo_name,
 
                                    revision='tip'))
 
            #strip all crap out of file, just leave the basename
 
            filename = os.path.basename(filename)
 
            node_path = os.path.join(location, filename)
 
            author = self.rhodecode_user.full_contact
 
            author = self.authuser.full_contact
 

	
 
            try:
 
                nodes = {
 
                    node_path: {
 
                        'content': content
 
                    }
 
                }
 
                self.scm_model.create_nodes(
 
                    user=c.rhodecode_user.user_id, repo=c.db_repo,
 
                    user=c.authuser.user_id, repo=c.db_repo,
 
                    message=message,
 
                    nodes=nodes,
 
                    parent_cs=c.cs,
 
                    author=author,
 
                )
 

	
 
                h.flash(_('Successfully committed to %s') % node_path,
 
                        category='success')
 
            except NonRelativePathError, e:
 
                h.flash(_('Location must be relative path and must not '
 
                          'contain .. in path'), category='warning')
 
                return redirect(url('changeset_home', repo_name=c.repo_name,
 
@@ -577,25 +577,25 @@ class FilesController(BaseRepoController
 
            while True:
 
                data = stream.read(16 * 1024)
 
                if not data:
 
                    stream.close()
 
                    if fd:  # fd means we used temporary file
 
                        os.close(fd)
 
                    if not archive_cache_enabled:
 
                        log.debug('Destroing temp archive %s' % archive)
 
                        os.remove(archive)
 
                    break
 
                yield data
 
        # store download action
 
        action_logger(user=c.rhodecode_user,
 
        action_logger(user=c.authuser,
 
                      action='user_downloaded_archive:%s' % (archive_name),
 
                      repo=repo_name, ipaddr=self.ip_addr, commit=True)
 
        response.content_disposition = str('attachment; filename=%s' % (archive_name))
 
        response.content_type = str(content_type)
 
        return get_chunked_archive(archive)
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def diff(self, repo_name, f_path):
 
        ignore_whitespace = request.GET.get('ignorews') == '1'
 
        line_context = request.GET.get('context', 3)
kallithea/controllers/forks.py
Show inline comments
 
@@ -163,25 +163,25 @@ class ForksController(BaseRepoController
 
                             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 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.
 
            task = RepoModel().create_fork(form_result, self.rhodecode_user.user_id)
 
            task = RepoModel().create_fork(form_result, self.authuser.user_id)
 
            from celery.result import BaseAsyncResult
 
            if isinstance(task, BaseAsyncResult):
 
                task_id = task.task_id
 
        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")
 
        except Exception:
kallithea/controllers/journal.py
Show inline comments
 
@@ -187,45 +187,45 @@ class JournalController(BaseController):
 
                          author_email=user.email,
 
                          author_name=user.full_contact,
 
                          description=desc)
 

	
 
        response.content_type = feed.mime_type
 
        return feed.writeString('utf-8')
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def index(self):
 
        # Return a rendered template
 
        p = safe_int(request.GET.get('page', 1), 1)
 
        c.user = User.get(self.rhodecode_user.user_id)
 
        c.user = User.get(self.authuser.user_id)
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.rhodecode_user.user_id)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
 
        journal = self._get_journal_data(c.following)
 

	
 
        def url_generator(**kw):
 
            return url.current(filter=c.search_term, **kw)
 

	
 
        c.journal_pager = Page(journal, page=p, items_per_page=20, url=url_generator)
 
        c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager)
 

	
 
        c.journal_data = render('journal/journal_data.html')
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.journal_data
 

	
 
        repos_list = Session().query(Repository)\
 
                     .filter(Repository.user_id ==
 
                             self.rhodecode_user.user_id)\
 
                             self.authuser.user_id)\
 
                     .order_by(func.lower(Repository.repo_name)).all()
 

	
 
        repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
 
                                                   admin=True)
 
        #json used to render the grid
 
        c.data = json.dumps(repos_data)
 

	
 
        watched_repos_data = []
 

	
 
        ## watched repos
 
        _render = RepoModel._render_datatable
 

	
 
@@ -279,103 +279,103 @@ class JournalController(BaseController):
 
            "dir": "asc",
 
            "records": watched_repos_data
 
        })
 
        return render('journal/journal.html')
 

	
 
    @LoginRequired(api_access=True)
 
    @NotAnonymous()
 
    def journal_atom(self):
 
        """
 
        Produce an atom-1.0 feed via feedgenerator module
 
        """
 
        following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.rhodecode_user.user_id)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 
        return self._atom_feed(following, public=False)
 

	
 
    @LoginRequired(api_access=True)
 
    @NotAnonymous()
 
    def journal_rss(self):
 
        """
 
        Produce an rss feed via feedgenerator module
 
        """
 
        following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.rhodecode_user.user_id)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 
        return self._rss_feed(following, public=False)
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def toggle_following(self):
 
        cur_token = request.POST.get('auth_token')
 
        token = h.get_token()
 
        if cur_token == token:
 

	
 
            user_id = request.POST.get('follows_user_id')
 
            if user_id:
 
                try:
 
                    self.scm_model.toggle_following_user(user_id,
 
                                                self.rhodecode_user.user_id)
 
                                                self.authuser.user_id)
 
                    Session.commit()
 
                    return 'ok'
 
                except Exception:
 
                    raise HTTPBadRequest()
 

	
 
            repo_id = request.POST.get('follows_repo_id')
 
            if repo_id:
 
                try:
 
                    self.scm_model.toggle_following_repo(repo_id,
 
                                                self.rhodecode_user.user_id)
 
                                                self.authuser.user_id)
 
                    Session.commit()
 
                    return 'ok'
 
                except Exception:
 
                    raise HTTPBadRequest()
 

	
 
        log.debug('token mismatch %s vs %s' % (cur_token, token))
 
        raise HTTPBadRequest()
 

	
 
    @LoginRequired()
 
    def public_journal(self):
 
        # Return a rendered template
 
        p = safe_int(request.GET.get('page', 1), 1)
 

	
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.rhodecode_user.user_id)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
 
        journal = self._get_journal_data(c.following)
 

	
 
        c.journal_pager = Page(journal, page=p, items_per_page=20)
 

	
 
        c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager)
 

	
 
        c.journal_data = render('journal/journal_data.html')
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.journal_data
 
        return render('journal/public_journal.html')
 

	
 
    @LoginRequired(api_access=True)
 
    def public_journal_atom(self):
 
        """
 
        Produce an atom-1.0 feed via feedgenerator module
 
        """
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.rhodecode_user.user_id)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
 
        return self._atom_feed(c.following)
 

	
 
    @LoginRequired(api_access=True)
 
    def public_journal_rss(self):
 
        """
 
        Produce an rss2 feed via feedgenerator module
 
        """
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.rhodecode_user.user_id)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
 
        return self._rss_feed(c.following)
kallithea/controllers/login.py
Show inline comments
 
@@ -50,25 +50,25 @@ log = logging.getLogger(__name__)
 

	
 

	
 
class LoginController(BaseController):
 

	
 
    def __before__(self):
 
        super(LoginController, self).__before__()
 

	
 
    def _store_user_in_session(self, username, remember=False):
 
        user = User.get_by_username(username, case_insensitive=True)
 
        auth_user = AuthUser(user.user_id)
 
        auth_user.set_authenticated()
 
        cs = auth_user.get_cookie_store()
 
        session['rhodecode_user'] = cs
 
        session['authuser'] = cs
 
        user.update_lastlogin()
 
        Session().commit()
 

	
 
        # If they want to be remembered, update the cookie
 
        if remember:
 
            _year = (datetime.datetime.now() +
 
                     datetime.timedelta(seconds=60 * 60 * 24 * 365))
 
            session._set_cookie_expires(_year)
 

	
 
        session.save()
 

	
 
        log.info('user %s is now authenticated and stored in '
 
@@ -96,29 +96,29 @@ class LoginController(BaseController):
 
            came_from = url('home')
 
        elif server_parsed.netloc != parsed.netloc:
 
            log.error('Suspicious NETLOC detected %s for url %s server url '
 
                      'is: %s' % (parsed.netloc, parsed, server_parsed))
 
            came_from = url('home')
 
        return came_from
 

	
 
    def index(self):
 
        _default_came_from = url('home')
 
        came_from = self._validate_came_from(request.GET.get('came_from'))
 
        c.came_from = came_from or _default_came_from
 

	
 
        not_default = self.rhodecode_user.username != User.DEFAULT_USER
 
        ip_allowed = self.rhodecode_user.ip_allowed
 
        not_default = self.authuser.username != User.DEFAULT_USER
 
        ip_allowed = self.authuser.ip_allowed
 

	
 
        # redirect if already logged in
 
        if self.rhodecode_user.is_authenticated and not_default and ip_allowed:
 
        if self.authuser.is_authenticated and not_default and ip_allowed:
 
            raise HTTPFound(location=c.came_from)
 

	
 
        if request.POST:
 
            # import Login Form validator class
 
            login_form = LoginForm()
 
            try:
 
                session.invalidate()
 
                c.form_result = login_form.to_python(dict(request.POST))
 
                # form checks for username/password, now we're authenticated
 
                headers = self._store_user_in_session(
 
                                        username=c.form_result['username'],
 
                                        remember=c.form_result['remember'])
kallithea/controllers/pullrequests.py
Show inline comments
 
@@ -152,28 +152,28 @@ class PullrequestsController(BaseRepoCon
 
                    k, v = repo.branches.items()[0]
 
                    selected = 'branch:%s:%s' % (k, v)
 

	
 
        groups = [(specials, _("Special")),
 
                  (peers, _("Peer branches")),
 
                  (bookmarks, _("Bookmarks")),
 
                  (branches, _("Branches")),
 
                  (tags, _("Tags")),
 
                  ]
 
        return [g for g in groups if g[0]], selected
 

	
 
    def _get_is_allowed_change_status(self, pull_request):
 
        owner = self.rhodecode_user.user_id == pull_request.user_id
 
        reviewer = self.rhodecode_user.user_id in [x.user_id for x in
 
        owner = self.authuser.user_id == pull_request.user_id
 
        reviewer = self.authuser.user_id in [x.user_id for x in
 
                                                   pull_request.reviewers]
 
        return self.rhodecode_user.admin or owner or reviewer
 
        return self.authuser.admin or owner or reviewer
 

	
 
    def _load_compare_data(self, pull_request, enable_comments=True):
 
        """
 
        Load context data needed for generating compare diff
 

	
 
        :param pull_request:
 
        """
 
        org_repo = pull_request.org_repo
 
        (org_ref_type,
 
         org_ref_name,
 
         org_ref_rev) = pull_request.org_ref.split(':')
 

	
 
@@ -336,69 +336,69 @@ class PullrequestsController(BaseRepoCon
 
        org_ref = _form['org_ref'] # will end with merge_rev but have symbolic name
 
        other_repo = _form['other_repo']
 
        other_ref = 'rev:ancestor:%s' % _form['ancestor_rev'] # could be calculated from other_ref ...
 
        revisions = [x for x in reversed(_form['revisions'])]
 
        reviewers = _form['review_members']
 

	
 
        title = _form['pullrequest_title']
 
        if not title:
 
            title = '%s#%s to %s' % (org_repo, org_ref.split(':', 2)[1], other_repo)
 
        description = _form['pullrequest_desc']
 
        try:
 
            pull_request = PullRequestModel().create(
 
                self.rhodecode_user.user_id, org_repo, org_ref, other_repo,
 
                self.authuser.user_id, org_repo, org_ref, other_repo,
 
                other_ref, revisions, reviewers, title, description
 
            )
 
            Session().commit()
 
            h.flash(_('Successfully opened new pull request'),
 
                    category='success')
 
        except Exception:
 
            h.flash(_('Error occurred during sending pull request'),
 
                    category='error')
 
            log.error(traceback.format_exc())
 
            return redirect(url('pullrequest_home', repo_name=repo_name))
 

	
 
        return redirect(url('pullrequest_show', repo_name=other_repo,
 
                            pull_request_id=pull_request.pull_request_id))
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    @jsonify
 
    def update(self, repo_name, pull_request_id):
 
        pull_request = PullRequest.get_or_404(pull_request_id)
 
        if pull_request.is_closed():
 
            raise HTTPForbidden()
 
        #only owner or admin can update it
 
        owner = pull_request.author.user_id == c.rhodecode_user.user_id
 
        owner = pull_request.author.user_id == c.authuser.user_id
 
        repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
 
        if h.HasPermissionAny('hg.admin') or repo_admin or owner:
 
            reviewers_ids = map(int, filter(lambda v: v not in [None, ''],
 
                request.POST.get('reviewers_ids', '').split(',')))
 

	
 
            PullRequestModel().update_reviewers(pull_request_id, reviewers_ids)
 
            Session().commit()
 
            return True
 
        raise HTTPForbidden()
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    @jsonify
 
    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.author.user_id == c.rhodecode_user.user_id:
 
        if pull_request.author.user_id == c.authuser.user_id:
 
            PullRequestModel().delete(pull_request)
 
            Session().commit()
 
            h.flash(_('Successfully deleted pull request'),
 
                    category='success')
 
            return redirect(url('my_account_pullrequests'))
 
        raise HTTPForbidden()
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def show(self, repo_name, pull_request_id):
 
        repo_model = RepoModel()
 
@@ -476,53 +476,53 @@ class PullrequestsController(BaseRepoCon
 
        close_pr = request.POST.get('save_close')
 

	
 
        allowed_to_change_status = self._get_is_allowed_change_status(pull_request)
 
        if status and change_status and allowed_to_change_status:
 
            _def = (_('Status change -> %s')
 
                            % ChangesetStatus.get_status_lbl(status))
 
            if close_pr:
 
                _def = _('Closing with') + ' ' + _def
 
            text = text or _def
 
        comm = ChangesetCommentsModel().create(
 
            text=text,
 
            repo=c.db_repo.repo_id,
 
            user=c.rhodecode_user.user_id,
 
            user=c.authuser.user_id,
 
            pull_request=pull_request_id,
 
            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
 
                           and allowed_to_change_status else None),
 
            closing_pr=close_pr
 
        )
 

	
 
        action_logger(self.rhodecode_user,
 
        action_logger(self.authuser,
 
                      'user_commented_pull_request:%s' % pull_request_id,
 
                      c.db_repo, self.ip_addr, self.sa)
 

	
 
        if allowed_to_change_status:
 
            # get status if set !
 
            if status and change_status:
 
                ChangesetStatusModel().set_status(
 
                    c.db_repo.repo_id,
 
                    status,
 
                    c.rhodecode_user.user_id,
 
                    c.authuser.user_id,
 
                    comm,
 
                    pull_request=pull_request_id
 
                )
 

	
 
            if close_pr:
 
                if status in ['rejected', 'approved']:
 
                    PullRequestModel().close_pull_request(pull_request_id)
 
                    action_logger(self.rhodecode_user,
 
                    action_logger(self.authuser,
 
                              'user_closed_pull_request:%s' % pull_request_id,
 
                              c.db_repo, self.ip_addr, self.sa)
 
                else:
 
                    h.flash(_('Closing pull request on other statuses than '
 
                              'rejected or approved forbidden'),
 
                            category='warning')
 

	
 
        Session().commit()
 

	
 
        if not request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return redirect(h.url('pullrequest_show', repo_name=repo_name,
 
                                  pull_request_id=pull_request_id))
 
@@ -540,20 +540,20 @@ class PullrequestsController(BaseRepoCon
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    @jsonify
 
    def delete_comment(self, repo_name, comment_id):
 
        co = ChangesetComment.get(comment_id)
 
        if co.pull_request.is_closed():
 
            #don't allow deleting comments on closed pull request
 
            raise HTTPForbidden()
 

	
 
        owner = co.author.user_id == c.rhodecode_user.user_id
 
        owner = co.author.user_id == c.authuser.user_id
 
        repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
 
        if h.HasPermissionAny('hg.admin') or repo_admin or owner:
 
            ChangesetCommentsModel().delete(comment=co)
 
            Session().commit()
 
            return True
 
        else:
 
            raise HTTPForbidden()
kallithea/controllers/summary.py
Show inline comments
 
@@ -127,26 +127,26 @@ class SummaryController(BaseRepoControll
 
        valid = CacheInvalidation.test_and_set_valid(repo_name, kind)
 
        if not valid:
 
            region_invalidate(_get_readme_from_cache, None, repo_name, kind)
 
        return _get_readme_from_cache(repo_name, kind)
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def index(self, repo_name):
 
        _load_changelog_summary()
 

	
 
        username = ''
 
        if self.rhodecode_user.username != User.DEFAULT_USER:
 
            username = safe_str(self.rhodecode_user.username)
 
        if self.authuser.username != User.DEFAULT_USER:
 
            username = safe_str(self.authuser.username)
 

	
 
        _def_clone_uri = _def_clone_uri_by_id = c.clone_uri_tmpl
 
        if '{repo}' in _def_clone_uri:
 
            _def_clone_uri_by_id = _def_clone_uri.replace('{repo}', '_{repoid}')
 
        elif '{repoid}' in _def_clone_uri:
 
            _def_clone_uri_by_id = _def_clone_uri.replace('_{repoid}', '{repo}')
 

	
 
        c.clone_repo_url = c.db_repo.clone_url(user=username,
 
                                                uri_tmpl=_def_clone_uri)
 
        c.clone_repo_url_id = c.db_repo.clone_url(user=username,
 
                                                uri_tmpl=_def_clone_uri_by_id)
 

	
kallithea/lib/auth.py
Show inline comments
 
@@ -727,25 +727,25 @@ class LoginRequired(object):
 
    :param api_access: if enabled this checks only for valid auth token
 
        and grants access based on valid token
 
    """
 

	
 
    def __init__(self, api_access=False):
 
        self.api_access = api_access
 

	
 
    def __call__(self, func):
 
        return decorator(self.__wrapper, func)
 

	
 
    def __wrapper(self, func, *fargs, **fkwargs):
 
        cls = fargs[0]
 
        user = cls.rhodecode_user
 
        user = cls.authuser
 
        loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
 

	
 
        # check if our IP is allowed
 
        ip_access_valid = True
 
        if not user.ip_allowed:
 
            from kallithea.lib import helpers as h
 
            h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr))),
 
                    category='warning')
 
            ip_access_valid = False
 

	
 
        # check if we used an APIKEY and it's a valid one
 
        # defined whitelist of controllers which API access will be enabled
 
@@ -785,25 +785,25 @@ class LoginRequired(object):
 

	
 

	
 
class NotAnonymous(object):
 
    """
 
    Must be logged in to execute this function else
 
    redirect to login page"""
 

	
 
    def __call__(self, func):
 
        return decorator(self.__wrapper, func)
 

	
 
    def __wrapper(self, func, *fargs, **fkwargs):
 
        cls = fargs[0]
 
        self.user = cls.rhodecode_user
 
        self.user = cls.authuser
 

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

	
 
        anonymous = self.user.username == User.DEFAULT_USER
 

	
 
        if anonymous:
 
            p = url.current()
 

	
 
            import kallithea.lib.helpers as h
 
            h.flash(_('You need to be a registered user to '
 
                      'perform this action'),
 
                    category='warning')
 
@@ -815,25 +815,25 @@ class NotAnonymous(object):
 
class PermsDecorator(object):
 
    """Base class for controller decorators"""
 

	
 
    def __init__(self, *required_perms):
 
        self.required_perms = set(required_perms)
 
        self.user_perms = None
 

	
 
    def __call__(self, func):
 
        return decorator(self.__wrapper, func)
 

	
 
    def __wrapper(self, func, *fargs, **fkwargs):
 
        cls = fargs[0]
 
        self.user = cls.rhodecode_user
 
        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
 

	
kallithea/lib/base.py
Show inline comments
 
@@ -305,66 +305,66 @@ class BaseController(WSGIController):
 

	
 
        ## INI stored
 
        c.visual.allow_repo_location_change = str2bool(config.get('allow_repo_location_change', True))
 
        c.visual.allow_custom_hooks_settings = str2bool(config.get('allow_custom_hooks_settings', True))
 

	
 
        c.rhodecode_instanceid = config.get('instance_id')
 
        c.issues_url = config.get('bugtracker', url('issues_url'))
 
        # END CONFIG VARS
 

	
 
        c.repo_name = get_repo_slug(request)  # can be empty
 
        c.backends = BACKENDS.keys()
 
        c.unread_notifications = NotificationModel()\
 
                        .get_unread_cnt_for_user(c.rhodecode_user.user_id)
 
                        .get_unread_cnt_for_user(c.authuser.user_id)
 

	
 
        self.cut_off_limit = safe_int(config.get('cut_off_limit'))
 
        self.sa = meta.Session
 
        self.scm_model = ScmModel(self.sa)
 

	
 
    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']
 
        try:
 
            self.ip_addr = _get_ip_addr(environ)
 
            # make sure that we update permissions each time we call controller
 
            api_key = request.GET.get('api_key')
 

	
 
            if api_key:
 
                # when using API_KEY we are sure user exists.
 
                auth_user = AuthUser(api_key=api_key, ip_addr=self.ip_addr)
 
                authenticated = False
 
            else:
 
                cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
 
                cookie_store = CookieStoreWrapper(session.get('authuser'))
 
                try:
 
                    auth_user = AuthUser(user_id=cookie_store.get('user_id', None),
 
                                         ip_addr=self.ip_addr)
 
                except UserCreationError, e:
 
                    from kallithea.lib import helpers as h
 
                    h.flash(e, 'error')
 
                    # 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
 
                    auth_user = AuthUser(ip_addr=self.ip_addr)
 

	
 
                authenticated = cookie_store.get('is_authenticated')
 

	
 
            if not auth_user.is_authenticated and auth_user.user_id is not None:
 
                # user is not authenticated and not empty
 
                auth_user.set_authenticated(authenticated)
 
            request.user = auth_user
 
            #set globals for auth user
 
            self.rhodecode_user = c.rhodecode_user = auth_user
 
            self.authuser = c.authuser = auth_user
 
            log.info('IP: %s User: %s accessed %s' % (
 
               self.ip_addr, auth_user, safe_unicode(_get_access_path(environ)))
 
            )
 
            return WSGIController.__call__(self, environ, start_response)
 
        finally:
 
            meta.Session.remove()
 

	
 

	
 
class BaseRepoController(BaseController):
 
    """
 
    Base class for controllers responsible for loading all needed data for
 
    repository loaded items are
 
@@ -404,13 +404,13 @@ class BaseRepoController(BaseController)
 
                          'cannot be created as an scm instance', c.repo_name)
 

	
 
                redirect(url('home'))
 

	
 
            # update last change according to VCS data
 
            dbr.update_changeset_cache(dbr.get_changeset())
 

	
 
            # some globals counter for menu
 
            c.repository_followers = self.scm_model.get_followers(dbr)
 
            c.repository_forks = self.scm_model.get_forks(dbr)
 
            c.repository_pull_requests = self.scm_model.get_pull_requests(dbr)
 
            c.repository_following = self.scm_model.is_following_repo(
 
                                    c.repo_name, self.rhodecode_user.user_id)
 
                                    c.repo_name, self.authuser.user_id)
kallithea/lib/utils.py
Show inline comments
 
@@ -47,25 +47,25 @@ from kallithea.lib.vcs.backends.base imp
 
from kallithea.lib.vcs.utils.lazy import LazyProperty
 
from kallithea.lib.vcs.utils.hgcompat import ui, config
 
from kallithea.lib.vcs.utils.helpers import get_scm
 
from kallithea.lib.vcs.exceptions import VCSError
 

	
 
from kallithea.lib.caching_query import FromCache
 

	
 
from kallithea.model import meta
 
from kallithea.model.db import Repository, User, RhodeCodeUi, \
 
    UserLog, RepoGroup, RhodeCodeSetting, CacheInvalidation, UserGroup
 
from kallithea.model.meta import Session
 
from kallithea.model.repo_group import RepoGroupModel
 
from kallithea.lib.utils2 import safe_str, safe_unicode, get_current_rhodecode_user
 
from kallithea.lib.utils2 import safe_str, safe_unicode, get_current_authuser
 
from kallithea.lib.vcs.utils.fakemod import create_module
 
from kallithea.model.user_group import UserGroupModel
 

	
 
log = logging.getLogger(__name__)
 

	
 
REMOVED_REPO_PAT = re.compile(r'rm__\d{8}_\d{6}_\d{6}__.*')
 

	
 

	
 
def recursive_replace(str_, replace=' '):
 
    """
 
    Recursive replace of given sign to just one instance
 

	
 
@@ -169,25 +169,25 @@ def action_logger(user, action, repo, ip
 
    :param repo: string name of repository or object containing repo_id,
 
        that action was made on
 
    :param ipaddr: optional ip address from what the action was made
 
    :param sa: optional sqlalchemy session
 

	
 
    """
 

	
 
    if not sa:
 
        sa = meta.Session()
 
    # if we don't get explicit IP address try to get one from registered user
 
    # in tmpl context var
 
    if not ipaddr:
 
        ipaddr = getattr(get_current_rhodecode_user(), 'ip_addr', '')
 
        ipaddr = getattr(get_current_authuser(), 'ip_addr', '')
 

	
 
    try:
 
        if getattr(user, 'user_id', None):
 
            user_obj = User.get(user.user_id)
 
        elif isinstance(user, basestring):
 
            user_obj = User.get_by_username(user)
 
        else:
 
            raise Exception('You have to provide a user object or a username')
 

	
 
        if getattr(repo, 'repo_id', None):
 
            repo_obj = Repository.get(repo.repo_id)
 
            repo_name = repo_obj.repo_name
kallithea/lib/utils2.py
Show inline comments
 
@@ -662,32 +662,32 @@ def suuid(url=None, truncate_to=22, alph
 
    else:
 
        unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
 

	
 
    alphabet_length = len(_ALPHABET)
 
    output = []
 
    while unique_id > 0:
 
        digit = unique_id % alphabet_length
 
        output.append(_ALPHABET[digit])
 
        unique_id = int(unique_id / alphabet_length)
 
    return "".join(output)[:truncate_to]
 

	
 

	
 
def get_current_rhodecode_user():
 
def get_current_authuser():
 
    """
 
    Gets rhodecode user from threadlocal tmpl_context variable if it's
 
    defined, else returns None.
 
    """
 
    from pylons import tmpl_context
 
    if hasattr(tmpl_context, 'rhodecode_user'):
 
        return tmpl_context.rhodecode_user
 
    if hasattr(tmpl_context, 'authuser'):
 
        return tmpl_context.authuser
 

	
 
    return None
 

	
 

	
 
class OptionalAttr(object):
 
    """
 
    Special Optional Option that defines other attribute. Example::
 

	
 
        def test(apiuser, userid=Optional(OAttr('apiuser')):
 
            user = Optional.extract(userid)
 
            # calls
 

	
kallithea/model/repo.py
Show inline comments
 
@@ -26,25 +26,25 @@ Repository model for rhodecode
 

	
 
from __future__ import with_statement
 
import os
 
import shutil
 
import logging
 
import traceback
 
from datetime import datetime
 
from kallithea.lib.utils import make_ui
 

	
 
from kallithea.lib.vcs.backends import get_backend
 
from kallithea.lib.compat import json
 
from kallithea.lib.utils2 import LazyProperty, safe_str, safe_unicode, \
 
    remove_prefix, obfuscate_url_pw, get_current_rhodecode_user
 
    remove_prefix, obfuscate_url_pw, get_current_authuser
 
from kallithea.lib.caching_query import FromCache
 
from kallithea.lib.hooks import log_create_repository, log_delete_repository
 

	
 
from kallithea.model import BaseModel
 
from kallithea.model.db import Repository, UserRepoToPerm, UserGroupRepoToPerm, \
 
    UserRepoGroupToPerm, UserGroupRepoGroupToPerm, User, Permission, \
 
    Statistics, UserGroup, RhodeCodeUi, RepoGroup, \
 
    RhodeCodeSetting, RepositoryField
 

	
 
from kallithea.lib import helpers as h
 
from kallithea.lib.auth import HasRepoPermissionAny, HasUserGroupPermissionAny
 
from kallithea.lib.exceptions import AttachedForksError
 
@@ -528,25 +528,25 @@ class RepoModel(BaseModel):
 

	
 
    def delete(self, repo, forks=None, fs_remove=True, cur_user=None):
 
        """
 
        Delete given repository, forks parameter defines what do do with
 
        attached forks. Throws AttachedForksError if deleted repo has attached
 
        forks
 

	
 
        :param repo:
 
        :param forks: str 'delete' or 'detach'
 
        :param fs_remove: remove(archive) repo from filesystem
 
        """
 
        if not cur_user:
 
            cur_user = getattr(get_current_rhodecode_user(), 'username', None)
 
            cur_user = getattr(get_current_authuser(), 'username', None)
 
        repo = self._get_repo(repo)
 
        if repo:
 
            if forks == 'detach':
 
                for r in repo.forks:
 
                    r.fork = None
 
                    self.sa.add(r)
 
            elif forks == 'delete':
 
                for r in repo.forks:
 
                    self.delete(r, forks='delete')
 
            elif [f for f in repo.forks]:
 
                raise AttachedForksError()
 

	
kallithea/model/user.py
Show inline comments
 
@@ -23,25 +23,25 @@ users model for RhodeCode
 
:license: GPLv3, see LICENSE for more details.
 
"""
 

	
 

	
 
import logging
 
import traceback
 
from pylons import url
 
from pylons.i18n.translation import _
 

	
 
from sqlalchemy.exc import DatabaseError
 

	
 

	
 
from kallithea.lib.utils2 import safe_unicode, generate_api_key, get_current_rhodecode_user
 
from kallithea.lib.utils2 import safe_unicode, generate_api_key, get_current_authuser
 
from kallithea.lib.caching_query import FromCache
 
from kallithea.model import BaseModel
 
from kallithea.model.db import User, UserToPerm, Notification, \
 
    UserEmailMap, UserIpMap
 
from kallithea.lib.exceptions import DefaultUserException, \
 
    UserOwnsReposException
 
from kallithea.model.meta import Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
@@ -69,25 +69,25 @@ class UserModel(BaseModel):
 
            user = user.options(FromCache("sql_cache_short",
 
                                          "get_user_%s" % username))
 
        return user.scalar()
 

	
 
    def get_by_email(self, email, cache=False, case_insensitive=False):
 
        return User.get_by_email(email, case_insensitive, cache)
 

	
 
    def get_by_api_key(self, api_key, cache=False):
 
        return User.get_by_api_key(api_key, cache)
 

	
 
    def create(self, form_data, cur_user=None):
 
        if not cur_user:
 
            cur_user = getattr(get_current_rhodecode_user(), 'username', None)
 
            cur_user = getattr(get_current_authuser(), 'username', None)
 

	
 
        from kallithea.lib.hooks import log_create_user, check_allowed_create_user
 
        _fd = form_data
 
        user_data = {
 
            'username': _fd['username'], 'password': _fd['password'],
 
            'email': _fd['email'], 'firstname': _fd['firstname'], 'lastname': _fd['lastname'],
 
            'active': _fd['active'], 'admin': False
 
        }
 
        # raises UserCreationError if it's not allowed
 
        check_allowed_create_user(user_data, cur_user)
 
        from kallithea.lib.auth import get_crypt_password
 
        try:
 
@@ -118,25 +118,25 @@ class UserModel(BaseModel):
 
        :param password:
 
        :param email:
 
        :param active:
 
        :param firstname:
 
        :param lastname:
 
        :param active:
 
        :param admin:
 
        :param extern_name:
 
        :param extern_type:
 
        :param cur_user:
 
        """
 
        if not cur_user:
 
            cur_user = getattr(get_current_rhodecode_user(), 'username', None)
 
            cur_user = getattr(get_current_authuser(), 'username', None)
 

	
 
        from kallithea.lib.auth import get_crypt_password, check_password
 
        from kallithea.lib.hooks import log_create_user, check_allowed_create_user
 
        user_data = {
 
            'username': username, 'password': password,
 
            'email': email, 'firstname': firstname, 'lastname': lastname,
 
            'active': active, 'admin': admin
 
        }
 
        # raises UserCreationError if it's not allowed
 
        check_allowed_create_user(user_data, cur_user)
 

	
 
        log.debug('Checking for %s account in RhodeCode database' % username)
 
@@ -250,25 +250,25 @@ class UserModel(BaseModel):
 
                if k == 'password' and v:
 
                    v = get_crypt_password(v)
 

	
 
                setattr(user, k, v)
 
            self.sa.add(user)
 
            return user
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def delete(self, user, cur_user=None):
 
        if not cur_user:
 
            cur_user = getattr(get_current_rhodecode_user(), 'username', None)
 
            cur_user = getattr(get_current_authuser(), 'username', None)
 
        user = self._get_user(user)
 

	
 
        try:
 
            if user.username == User.DEFAULT_USER:
 
                raise DefaultUserException(
 
                    _(u"You can't remove this user since it's"
 
                      " crucial for entire application")
 
                )
 
            if user.repositories:
 
                repos = [x.repo_name for x in user.repositories]
 
                raise UserOwnsReposException(
 
                    _(u'user "%s" still owns %s repositories and cannot be '
kallithea/templates/admin/gists/edit.html
Show inline comments
 
@@ -42,25 +42,25 @@
 
            </div>
 
            <script>
 
            if (typeof jQuery != 'undefined') {
 
                $(".alert").alert();
 
            }
 
            </script>
 
        </div>
 

	
 
        <div id="files_data">
 
          ${h.form(h.url('edit_gist', gist_id=c.gist.gist_access_id), method='post', id='eform')}
 
            <div>
 
                <div class="gravatar">
 
                   <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(c.rhodecode_user.full_contact),32)}"/>
 
                   <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(c.authuser.full_contact),32)}"/>
 
                </div>
 
                <input type="hidden" value="${c.file_changeset.raw_id}" name="parent_hash">
 
                <textarea style="resize:vertical; width:400px;border: 1px solid #ccc;border-radius: 3px;"
 
                          id="description" name="description"
 
                          placeholder="${_('Gist description ...')}">${c.gist.gist_description}</textarea>
 
                <div style="padding:0px 0px 0px 42px">
 
                    <label for='lifetime'>${_('Gist lifetime')}</label>
 
                    ${h.select('lifetime', '0', c.lifetime_options)}
 
                    <span class="" style="color: #AAA">
 
                     %if c.gist.gist_expires == -1:
 
                      ${_('Expires')}: ${_('never')}
 
                     %else:
kallithea/templates/admin/gists/index.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    %if c.show_private:
 
        ${_('Private Gists for user %s') % c.rhodecode_user.username}
 
        ${_('Private Gists for user %s') % c.authuser.username}
 
    %elif c.show_public:
 
        ${_('Public Gists for user %s') % c.rhodecode_user.username}
 
        ${_('Public Gists for user %s') % c.authuser.username}
 
    %else:
 
        ${_('Public Gists')}
 
    %endif
 
    %if c.rhodecode_name:
 
        &middot; ${c.rhodecode_name}
 
    %endif
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    %if c.show_private:
 
        ${_('Private Gists for user %s') % c.rhodecode_user.username}
 
        ${_('Private Gists for user %s') % c.authuser.username}
 
    %elif c.show_public:
 
        ${_('Public Gists for user %s') % c.rhodecode_user.username}
 
        ${_('Public Gists for user %s') % c.authuser.username}
 
    %else:
 
        ${_('Public Gists')}
 
    %endif
 
    - ${c.gists_pager.item_count}
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('gists')}
 
</%def>
 

	
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
        %if c.rhodecode_user.username != 'default':
 
        %if c.authuser.username != 'default':
 
        <ul class="links">
 
          <li>
 
             <a href="${h.url('new_gist')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_(u'Create New Gist')}</a>
 
          </li>
 
        </ul>
 
        %endif
 
    </div>
 
    %if c.gists_pager.item_count>0:
 
        % for gist in c.gists_pager:
 
          <div class="gist-item" style="padding:10px 20px 10px 15px">
 

	
 
            <div class="gravatar">
kallithea/templates/admin/gists/new.html
Show inline comments
 
@@ -29,25 +29,25 @@
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 

	
 
    <div class="table">
 
        <div id="files_data">
 
          ${h.form(h.url('gists'), method='post',id='eform')}
 
            <div>
 
                <div class="gravatar">
 
                   <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(c.rhodecode_user.full_contact),32)}"/>
 
                   <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(c.authuser.full_contact),32)}"/>
 
                </div>
 
                <textarea style="resize:vertical; width:400px;border: 1px solid #ccc;border-radius: 3px;" id="description" name="description" placeholder="${_('Gist description ...')}"></textarea>
 
                <div style="padding:0px 0px 0px 42px">
 
                <label for='lifetime'>${_('Gist lifetime')}</label>
 
                ${h.select('lifetime', '', c.lifetime_options)}
 
                </div>
 
            </div>
 
            <div id="body" class="codeblock">
 
                <div style="padding: 10px 10px 10px 26px;color:#666666">
 
                    ${h.text('filename', size=30, placeholder=_('name this file...'))}
 
                    ${h.select('mimetype','plain',[('plain',_('plain'))])}
 
                </div>
kallithea/templates/admin/gists/show.html
Show inline comments
 
@@ -13,25 +13,25 @@
 
    / ${_('URL')}: ${c.gist.gist_url()}
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('gists')}
 
</%def>
 

	
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
        %if c.rhodecode_user.username != 'default':
 
        %if c.authuser.username != 'default':
 
        <ul class="links">
 
          <li>
 
              <a href="${h.url('new_gist')}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_(u'Create New Gist')}</a>
 
          </li>
 
        </ul>
 
        %endif
 
    </div>
 
    <div class="table">
 
        <div id="files_data">
 
            <div id="body" class="codeblock">
 
                <div class="code-header">
 
                    <div class="stats">
 
@@ -44,34 +44,34 @@
 
                        </div>
 
                        <div class="left item">
 
                            ${c.gist.gist_description}
 
                        </div>
 
                        <div class="left item last" style="color: #AAA">
 
                         %if c.gist.gist_expires == -1:
 
                          ${_('Expires')}: ${_('never')}
 
                         %else:
 
                          ${_('Expires')}: ${h.age(h.time_to_datetime(c.gist.gist_expires))}
 
                         %endif
 
                       </div>
 

	
 
                       %if h.HasPermissionAny('hg.admin')() or c.gist.gist_owner == c.rhodecode_user.user_id:
 
                       %if h.HasPermissionAny('hg.admin')() or c.gist.gist_owner == c.authuser.user_id:
 
                        <div style="float:right">
 
                            ${h.form(url('gist', gist_id=c.gist.gist_id),method='delete')}
 
                                ${h.submit('remove_gist', _('Delete'),class_="btn btn-mini btn-danger",onclick="return confirm('"+_('Confirm to delete this Gist')+"');")}
 
                            ${h.end_form()}
 
                        </div>
 
                       %endif
 
                        <div class="buttons">
 
                          ## only owner should see that
 
                          %if h.HasPermissionAny('hg.admin')() or c.gist.gist_owner == c.rhodecode_user.user_id:
 
                          %if h.HasPermissionAny('hg.admin')() or c.gist.gist_owner == c.authuser.user_id:
 
                            ${h.link_to(_('Edit'),h.url('edit_gist', gist_id=c.gist.gist_access_id),class_="btn btn-mini")}
 
                          %endif
 
                          ${h.link_to(_('Show as Raw'),h.url('formatted_gist', gist_id=c.gist.gist_access_id, format='raw'),class_="btn btn-mini")}
 
                        </div>
 
                    </div>
 

	
 
                    <div class="author">
 
                        <div class="gravatar">
 
                            <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(c.file_changeset.author),16)}"/>
 
                        </div>
 
                        <div title="${c.file_changeset.author}" class="user">${h.person(c.file_changeset.author)} - ${_('created')} ${h.age(c.file_changeset.date)}</div>
 
                    </div>
kallithea/templates/admin/my_account/my_account.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('My account')} ${c.rhodecode_user.username}
 
    ${_('My account')} ${c.authuser.username}
 
    %if c.rhodecode_name:
 
        &middot; ${c.rhodecode_name}
 
    %endif
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${_('My Account')}
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('admin')}
 
</%def>
kallithea/templates/admin/notifications/notifications.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('My Notifications')} ${c.rhodecode_user.username}
 
    ${_('My Notifications')} ${c.authuser.username}
 
    %if c.rhodecode_name:
 
        &middot; ${c.rhodecode_name}
 
    %endif
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${_('My Notifications')}
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('admin')}
 
</%def>
kallithea/templates/admin/notifications/show_notification.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('Show notification')} ${c.rhodecode_user.username}
 
    ${_('Show notification')} ${c.authuser.username}
 
    %if c.rhodecode_name:
 
        &middot; ${c.rhodecode_name}
 
    %endif
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Notifications'),h.url('notifications'))}
 
    &raquo;
 
    ${_('Show notification')}
 
</%def>
 

	
 
<%def name="page_nav()">
kallithea/templates/admin/repo_groups/repo_group_edit_perms.html
Show inline comments
 
@@ -6,25 +6,25 @@ ${h.form(url('edit_repo_group_perms', gr
 
                <tr>
 
                    <td>${_('none')}</td>
 
                    <td>${_('read')}</td>
 
                    <td>${_('write')}</td>
 
                    <td>${_('admin')}</td>
 
                    <td>${_('user/user group')}</td>
 
                    <td></td>
 
                </tr>
 
                ## USERS
 
                %for r2p in c.repo_group.repo_group_to_perm:
 
                    ##forbid revoking permission from yourself, except if you're an super admin
 
                    <tr id="id${id(r2p.user.username)}">
 
                        %if c.rhodecode_user.user_id != r2p.user.user_id or c.rhodecode_user.is_admin:
 
                        %if c.authuser.user_id != r2p.user.user_id or c.authuser.is_admin:
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'group.none')}</td>
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'group.read')}</td>
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'group.write')}</td>
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'group.admin')}</td>
 
                        <td style="white-space: nowrap;">
 
                            <img class="perm-gravatar" src="${h.gravatar_url(r2p.user.email,14)}"/>
 
                            %if h.HasPermissionAny('hg.admin')() and r2p.user.username != 'default':
 
                             <a href="${h.url('edit_user',id=r2p.user.user_id)}">${r2p.user.username}</a>
 
                            %else:
 
                             ${r2p.user.username if r2p.user.username != 'default' else _('default')}
 
                            %endif
 
                        </td>
kallithea/templates/admin/repos/repo_add.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('Add repository')}
 
    %if c.rhodecode_name:
 
        &middot; ${c.rhodecode_name}
 
    %endif
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    %if c.rhodecode_user.is_admin:
 
    %if c.authuser.is_admin:
 
    ${h.link_to(_('Admin'),h.url('admin_home'))}
 
    &raquo;
 
    ${h.link_to(_('Repositories'),h.url('repos'))}
 
    %else:
 
    ${_('Admin')}
 
    &raquo;
 
    ${_('Repositories')}
 
    %endif
 
    &raquo;
 
    ${_('Add Repository')}
 
</%def>
 

	
kallithea/templates/admin/repos/repo_add_base.html
Show inline comments
 
@@ -4,25 +4,25 @@ ${h.form(url('repos'))}
 
<div class="form">
 
    <!-- fields -->
 
    <div class="fields">
 
        <div class="field">
 
            <div class="label">
 
                <label for="repo_name">${_('Name')}:</label>
 
            </div>
 
            <div class="input">
 
                ${h.text('repo_name',class_="small")}
 
                <div style="margin: 6px 0px 0px 0px">
 
                    <a id="remote_clone_toggle" href="#"><i class="icon-download-alt"></i> ${_('Import existing repository ?')}</a>
 
                </div>
 
                %if not c.rhodecode_user.is_admin:
 
                %if not c.authuser.is_admin:
 
                    ${h.hidden('user_created',True)}
 
                %endif
 
            </div>
 
         </div>
 
        <div id="remote_clone" class="field" style="display: none">
 
            <div class="label">
 
                <label for="clone_uri">${_('Clone from')}:</label>
 
            </div>
 
            <div class="input">
 
                ${h.text('clone_uri',class_="small")}
 
                <span class="help-block">${_('Optional http[s] url from which repository should be cloned.')}</span>
 
            </div>
kallithea/templates/admin/user_groups/user_group_edit_perms.html
Show inline comments
 
@@ -6,25 +6,25 @@ ${h.form(url('edit_user_group_perms', id
 
                <tr>
 
                    <td>${_('none')}</td>
 
                    <td>${_('read')}</td>
 
                    <td>${_('write')}</td>
 
                    <td>${_('admin')}</td>
 
                    <td>${_('user/user group')}</td>
 
                    <td></td>
 
                </tr>
 
                ## USERS
 
                %for r2p in c.user_group.user_user_group_to_perm:
 
                    ##forbid revoking permission from yourself, except if you're an super admin
 
                    <tr id="id${id(r2p.user.username)}">
 
                        %if c.rhodecode_user.user_id != r2p.user.user_id or c.rhodecode_user.is_admin:
 
                        %if c.authuser.user_id != r2p.user.user_id or c.authuser.is_admin:
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'usergroup.none')}</td>
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'usergroup.read')}</td>
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'usergroup.write')}</td>
 
                        <td>${h.radio('u_perm_%s' % r2p.user.username,'usergroup.admin')}</td>
 
                        <td style="white-space: nowrap;">
 
                            <img class="perm-gravatar" src="${h.gravatar_url(r2p.user.email,14)}"/>
 
                            %if h.HasPermissionAny('hg.admin')() and r2p.user.username != 'default':
 
                             <a href="${h.url('edit_user',id=r2p.user.user_id)}">${r2p.user.username}</a>
 
                            %else:
 
                             ${r2p.user.username if r2p.user.username != 'default' else _('default')}
 
                            %endif
 
                        </td>
kallithea/templates/admin/users/user_edit_profile.html
Show inline comments
 
@@ -2,25 +2,25 @@ ${h.form(url('update_user', id=c.user.us
 
<div class="form">
 
        <div class="field">
 
           <div class="gravatar_box">
 
               <div class="gravatar"><img alt="gravatar" src="${h.gravatar_url(c.user.email)}"/></div>
 
                <p>
 
                %if c.visual.use_gravatar:
 
                <strong>${_('Change avatar at')} <a href="http://gravatar.com">gravatar.com</a></strong>
 
                <br/>${_('Using')} ${c.user.email}
 
                %else:
 
                <strong>${_('Avatars are disabled')}</strong>
 
                <br/>${c.user.email or _('Missing email, please update this user email address.')}
 
                        ##show current ip just if we show ourself
 
                        %if c.rhodecode_user.username == c.user.username:
 
                        %if c.authuser.username == c.user.username:
 
                            [${_('current IP')}: ${c.perm_user.ip_addr or "?"}]
 
                        %endif
 
                %endif
 
           </div>
 
        </div>
 
        <% readonly = None %>
 
        <% disabled = "" %>
 
        <div class="fields">
 
            %if c.extern_type != 'rhodecode':
 
             <div class="field">
 
               <% readonly = "readonly" %>
 
               <% disabled = " disabled" %>
kallithea/templates/base/base.html
Show inline comments
 
@@ -169,25 +169,25 @@
 

	
 
              <li><a href="${h.url('search_repo',repo_name=c.repo_name)}"><i class="icon-search"></i> ${_('Search')}</a></li>
 

	
 
              %if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name) and c.db_repo.enable_locking:
 
                %if c.db_repo.locked[0]:
 
                  <li>${h.link_to(_('Unlock'), h.url('toggle_locking',repo_name=c.repo_name),class_='locking_del')}</li>
 
                %else:
 
                  <li>${h.link_to(_('Lock'), h.url('toggle_locking',repo_name=c.repo_name),class_='locking_add')}</li>
 
                %endif
 
              %endif
 
              ## TODO: this check feels wrong, it would be better to have a check for permissions
 
              ## also it feels like a job for the controller
 
              %if c.rhodecode_user.username != 'default':
 
              %if c.authuser.username != 'default':
 
                  <li>
 
                   <a class="${follow_class()}" onclick="javascript:toggleFollowingRepo(this,${c.db_repo.repo_id},'${str(h.get_token())}');">
 
                    <span class="show-follow"><i class="icon-heart-empty"></i> ${_('Follow')}</span>
 
                    <span class="show-following"><i class="icon-heart"></i> ${_('Unfollow')}</span>
 
                  </a>
 
                  </li>
 
                  <li><a href="${h.url('repo_fork_home',repo_name=c.repo_name)}"><i class="icon-code-fork"></i> ${_('Fork')}</a></li>
 
                  %if h.is_hg(c.db_repo_scm_instance):
 
                  <li><a href="${h.url('pullrequest_home',repo_name=c.repo_name)}"><i class="icon-code-fork"></i> ${_('Create Pull Request')}</a></li>
 
                  %endif
 
              %endif
 
             </ul>
 
@@ -213,39 +213,39 @@
 
         }
 
         return false;
 
      });
 
  </script>
 
  <!--- END CONTEXT BAR -->
 
</%def>
 

	
 
<%def name="usermenu()">
 
    ## USER MENU
 
    <li>
 
      <a class="menu_link childs" id="quick_login_link">
 
          <span class="icon">
 
             <img src="${h.gravatar_url(c.rhodecode_user.email,20)}" alt="avatar">
 
             <img src="${h.gravatar_url(c.authuser.email,20)}" alt="avatar">
 
          </span>
 
          %if c.rhodecode_user.username != 'default':
 
            <span class="menu_link_user">${c.rhodecode_user.username}</span>
 
          %if c.authuser.username != 'default':
 
            <span class="menu_link_user">${c.authuser.username}</span>
 
            %if c.unread_notifications != 0:
 
              <span class="menu_link_notifications">${c.unread_notifications}</span>
 
            %endif
 
          %else:
 
              <span>${_('Not logged in')}</span>
 
          %endif
 
      </a>
 

	
 
  <div class="user-menu">
 
      <div id="quick_login">
 
        %if c.rhodecode_user.username == 'default':
 
        %if c.authuser.username == 'default':
 
            <h4>${_('Login to your account')}</h4>
 
            ${h.form(h.url('login_home',came_from=h.url.current()))}
 
            <div class="form">
 
                <div class="fields">
 
                    <div class="field">
 
                        <div class="label">
 
                            <label for="username">${_('Username')}:</label>
 
                        </div>
 
                        <div class="input">
 
                            ${h.text('username',class_='focus')}
 
                        </div>
 

	
 
@@ -266,27 +266,27 @@
 
                         ${h.link_to(_("Don't have an account ?"),h.url('register'))}
 
                        %endif
 
                        </div>
 
                        <div class="submit">
 
                            ${h.submit('sign_in',_('Log In'),class_="btn btn-mini")}
 
                        </div>
 
                    </div>
 
                </div>
 
            </div>
 
            ${h.end_form()}
 
        %else:
 
            <div class="links_left">
 
                <div class="big_gravatar"><img alt="gravatar" src="${h.gravatar_url(c.rhodecode_user.email,48)}" /></div>
 
                <div class="full_name">${c.rhodecode_user.full_name_or_username}</div>
 
                <div class="email">${c.rhodecode_user.email}</div>
 
                <div class="big_gravatar"><img alt="gravatar" src="${h.gravatar_url(c.authuser.email,48)}" /></div>
 
                <div class="full_name">${c.authuser.full_name_or_username}</div>
 
                <div class="email">${c.authuser.email}</div>
 
            </div>
 
            <div class="links_right">
 
            <ol class="links">
 
              <li><a href="${h.url('notifications')}">${_('Notifications')}: ${c.unread_notifications}</a></li>
 
              <li>${h.link_to(_(u'My account'),h.url('my_account'))}</li>
 
              <li class="logout">${h.link_to(_(u'Log Out'),h.url('logout_home'))}</li>
 
            </ol>
 
            </div>
 
        %endif
 
      </div>
 
  </div>
 

	
 
@@ -297,70 +297,70 @@
 
        <%
 
        def is_current(selected):
 
            if selected == current:
 
                return h.literal('class="current"')
 
        %>
 
        <ul id="quick" class="horizontal-list">
 
          <!-- repo switcher -->
 
          <li ${is_current('repositories')}>
 
            <input id="repo_switcher" name="repo_switcher" type="hidden">
 
          </li>
 

	
 
          ##ROOT MENU
 
          %if c.rhodecode_user.username != 'default':
 
          %if c.authuser.username != 'default':
 
            <li ${is_current('journal')}>
 
              <a class="menu_link" title="${_('Show recent activity')}"  href="${h.url('journal')}">
 
                <i class="icon-book"></i> ${_('Journal')}
 
              </a>
 
            </li>
 
          %else:
 
            <li ${is_current('journal')}>
 
              <a class="menu_link" title="${_('Public journal')}"  href="${h.url('public_journal')}">
 
                <i class="icon-book"></i> ${_('Public journal')}
 
              </a>
 
            </li>
 
          %endif
 
            <li ${is_current('gists')}>
 
              <a class="menu_link childs" title="${_('Show public gists')}"  href="${h.url('gists')}">
 
                <i class="icon-file-2"></i> ${_('Gists')}
 
              </a>
 
                <ul class="admin_menu">
 
                  <li><a href="${h.url('new_gist', public=1)}"><i class="icon-file-alt"></i> ${_('Create new gist')}</a></li>
 
                  <li><a href="${h.url('gists')}"><i class="icon-copy"></i> ${_('All public gists')}</a></li>
 
                  %if c.rhodecode_user.username != 'default':
 
                  %if c.authuser.username != 'default':
 
                    <li><a href="${h.url('gists', public=1)}"><i class="icon-copy"></i> ${_('My public gists')}</a></li>
 
                    <li><a href="${h.url('gists', private=1)}"><i class="icon-file-text"></i> ${_('My private gists')}</a></li>
 
                  %endif
 
                </ul>
 
            </li>
 
          <li ${is_current('search')}>
 
              <a class="menu_link" title="${_('Search in repositories')}"  href="${h.url('search')}">
 
                <i class="icon-search"></i> ${_('Search')}
 
              </a>
 
          </li>
 
          % if h.HasPermissionAll('hg.admin')('access admin main page'):
 
            <li ${is_current('admin')}>
 
              <a class="menu_link childs" title="${_('Admin')}" href="${h.url('admin_home')}">
 
                <i class="icon-cog"></i> ${_('Admin')}
 
              </a>
 
              ${admin_menu()}
 
            </li>
 
          % elif c.rhodecode_user.repositories_admin or c.rhodecode_user.repository_groups_admin or c.rhodecode_user.user_groups_admin:
 
          % elif c.authuser.repositories_admin or c.authuser.repository_groups_admin or c.authuser.user_groups_admin:
 
          <li ${is_current('admin')}>
 
              <a class="menu_link childs" title="${_('Admin')}">
 
                <i class="icon-cog"></i> ${_('Admin')}
 
              </a>
 
              ${admin_menu_simple(c.rhodecode_user.repositories_admin,
 
                                  c.rhodecode_user.repository_groups_admin,
 
                                  c.rhodecode_user.user_groups_admin or h.HasPermissionAny('hg.usergroup.create.true')())}
 
              ${admin_menu_simple(c.authuser.repositories_admin,
 
                                  c.authuser.repository_groups_admin,
 
                                  c.authuser.user_groups_admin or h.HasPermissionAny('hg.usergroup.create.true')())}
 
          </li>
 
          % endif
 
          ${usermenu()}
 

	
 
    <script type="text/javascript">
 
        var visual_show_public_icon = "${c.visual.show_public_icon}" == "True";
 
        var cache = {}
 
        /*format the look of items in the list*/
 
        var format = function(state){
 
            if (!state.id){
 
              return state.text; // optgroup
 
            }
kallithea/templates/changeset/changeset_file_comment.html
Show inline comments
 
@@ -35,40 +35,40 @@
 
        </span>
 
       </div>
 

	
 
        %if co.status_change:
 
           <div  style="float:left" class="changeset-status-container">
 
             <div style="float:left;padding:10px 2px 0px 2px"></div>
 
             <div title="${_('Changeset status')}" class="changeset-status-lbl"> ${co.status_change[0].status_lbl}</div>
 
             <div class="changeset-status-ico"><img src="${h.url(str('/images/icons/flag_status_%s.png' % co.status_change[0].status))}" /></div>
 
           </div>
 
        %endif
 

	
 
      <a class="permalink" href="#comment-${co.comment_id}">&para;</a>
 
      %if h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or co.author.user_id == c.rhodecode_user.user_id:
 
      %if h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or co.author.user_id == c.authuser.user_id:
 
          <div onClick="deleteComment(${co.comment_id})" class="buttons delete-comment btn btn-mini">${_('Delete')}</div>
 
      %endif
 
      </div>
 
      <div class="text">
 
          ${h.rst_w_mentions(co.text)|n}
 
      </div>
 
    </div>
 
  </div>
 
</%def>
 

	
 

	
 
<%def name="comment_inline_form()">
 
<div id='comment-inline-form-template' style="display:none">
 
  <div class="comment-inline-form ac">
 
  %if c.rhodecode_user.username != 'default':
 
  %if c.authuser.username != 'default':
 
    <div class="overlay"><div class="overlay-text">${_('Submitting...')}</div></div>
 
      ${h.form('#', class_='inline-form')}
 
      <div id="edit-container_{1}" class="clearfix">
 
          <div class="comment-help">${_('Commenting on line {1}.')}
 
          ${(_('Comments parsed using %s syntax with %s support.') % (
 
                 ('<a href="%s">RST</a>' % h.url('rst_help')),
 
                   ('<span style="color:#003367" class="tooltip" title="%s">@mention</span>' % _('Use @username inside this text to send notification to this RhodeCode user'))
 
               )
 
            )|n
 
           }
 
          <div id="preview-btn_{1}" class="preview-btn btn btn-mini">${_('Preview')}</div>
 
          </div>
 
@@ -136,25 +136,25 @@
 
          %if not co.pull_request or (co.pull_request and co.status_change) or include_pr:
 
          ${comment_block(co)}
 
          %endif
 
        </div>
 
    %endfor
 
</div>
 
</%def>
 

	
 
## MAIN COMMENT FORM
 
<%def name="comments(post_url, cur_status, is_pr=False, change_status=True)">
 

	
 
<div class="comments">
 
    %if c.rhodecode_user.username != 'default':
 
    %if c.authuser.username != 'default':
 
    <div class="comment-form ac">
 
        ${h.form(post_url)}
 
        <div id="edit-container" class="clearfix">
 
            <div class="comment-help">
 
                ${(_('Comments parsed using %s syntax with %s support.') % (('<a href="%s">RST</a>' % h.url('rst_help')),
 
                  '<span style="color:#003367" class="tooltip" title="%s">@mention</span>' %
 
                  _('Use @username inside this text to send notification to this RhodeCode user')))|n}
 
              %if change_status:
 
                | <a id="show_changeset_link" onClick="change_status_show();">
 
                  %if is_pr:
 
                    ${_('Vote for pull request status')}
 
                  %else:
kallithea/templates/data_table/_dt_elements.html
Show inline comments
 
@@ -90,34 +90,34 @@
 

	
 
<%def name="revision(name,rev,tip,author,last_msg)">
 
  <div>
 
  %if rev >= 0:
 
      <pre><a title="${h.tooltip('%s:\n\n%s' % (author,last_msg))}" class="tooltip" href="${h.url('changeset_home',repo_name=name,revision=tip)}">${'r%s:%s' % (rev,h.short_id(tip))}</a></pre>
 
  %else:
 
      ${_('No changesets yet')}
 
  %endif
 
  </div>
 
</%def>
 

	
 
<%def name="rss(name)">
 
  %if c.rhodecode_user.username != 'default':
 
    <a title="${_('Subscribe to %s rss feed')% name}" href="${h.url('rss_feed_home',repo_name=name,api_key=c.rhodecode_user.api_key)}"><i class="icon-rss-sign" style="color: #fa9b39"></i></a>
 
  %if c.authuser.username != 'default':
 
    <a title="${_('Subscribe to %s rss feed')% name}" href="${h.url('rss_feed_home',repo_name=name,api_key=c.authuser.api_key)}"><i class="icon-rss-sign" style="color: #fa9b39"></i></a>
 
  %else:
 
    <a title="${_('Subscribe to %s rss feed')% name}" href="${h.url('rss_feed_home',repo_name=name)}"><i class="icon-rss-sign" style="color: #fa9b39"></i></a>
 
  %endif
 
</%def>
 

	
 
<%def name="atom(name)">
 
  %if c.rhodecode_user.username != 'default':
 
    <a title="${_('Subscribe to %s atom feed')% name}" href="${h.url('atom_feed_home',repo_name=name,api_key=c.rhodecode_user.api_key)}"><i class="icon-rss-sign"  style="color: #fa9b39"></i></a>
 
  %if c.authuser.username != 'default':
 
    <a title="${_('Subscribe to %s atom feed')% name}" href="${h.url('atom_feed_home',repo_name=name,api_key=c.authuser.api_key)}"><i class="icon-rss-sign"  style="color: #fa9b39"></i></a>
 
  %else:
 
    <a title="${_('Subscribe to %s atom feed')% name}" href="${h.url('atom_feed_home',repo_name=name)}"><i class="icon-rss-sign"  style="color: #fa9b39"></i></a>
 
  %endif
 
</%def>
 

	
 
<%def name="user_gravatar(email, size=24)">
 
    <div class="gravatar"><img alt="gravatar" src="${h.gravatar_url(email, size)}"/> </div>
 
</%def>
 

	
 
<%def name="repo_actions(repo_name, super_user=True)">
 
  <div>
 
    <div style="float:left; margin-right:5px;" class="grid_edit">
kallithea/templates/index_base.html
Show inline comments
 
<%page args="parent,group_name=''" />
 
    <div class="box">
 
        <!-- box / title -->
 
        <div class="title">
 
            <h5>
 
            <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/> ${parent.breadcrumbs()} <span id="repo_count">0</span> ${_('repositories')}
 
            </h5>
 
            %if c.rhodecode_user.username != 'default':
 
            %if c.authuser.username != 'default':
 
              <ul class="links">
 
                <li>
 
                <%
 
                    gr_name = c.group.group_name if c.group else None
 
                    # create repositories with write permission on group is set to true
 
                    create_on_write = h.HasPermissionAny('hg.create.write_on_repogroup.true')()
 
                    group_admin = h.HasRepoGroupPermissionAny('group.admin')(gr_name, 'can write into group index page')
 
                    group_write = h.HasRepoGroupPermissionAny('group.write')(gr_name, 'can write into group index page')
 
                %>
 
                %if h.HasPermissionAny('hg.admin','hg.create.repository')() or (group_admin or (group_write and create_on_write)):
 
                  %if c.group:
 
                        <a href="${h.url('new_repo',parent_group=c.group.group_id)}" class="btn btn-small btn-success"><i class="icon-plus"></i> ${_('Add Repository')}</a>
kallithea/templates/journal/journal.html
Show inline comments
 
@@ -12,39 +12,39 @@
 
    <input class="q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('quick filter...')}"/>
 
    <span class="tooltip" title="${h.tooltip(h.journal_filter_help())}">?</span>
 
    <input type='submit' value="${_('filter')}" class="btn btn-small" style="padding:0px 2px 0px 2px;margin:0px"/>
 
    ${_('journal')} - ${ungettext('%s entry', '%s entries', c.journal_pager.item_count) % (c.journal_pager.item_count)}
 
    </form>
 
    ${h.end_form()}
 
    </h5>
 
</%def>
 
<%def name="page_nav()">
 
    ${self.menu('journal')}
 
</%def>
 
<%def name="head_extra()">
 
<link href="${h.url('journal_atom', api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('ATOM journal feed')}" type="application/atom+xml" />
 
<link href="${h.url('journal_rss', api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('RSS journal feed')}" type="application/rss+xml" />
 
<link href="${h.url('journal_atom', api_key=c.authuser.api_key)}" rel="alternate" title="${_('ATOM journal feed')}" type="application/atom+xml" />
 
<link href="${h.url('journal_rss', api_key=c.authuser.api_key)}" rel="alternate" title="${_('RSS journal feed')}" type="application/rss+xml" />
 
</%def>
 
<%def name="main()">
 

	
 
    <div class="box box-left">
 
        <!-- box / title -->
 
        <div class="title">
 
         ${self.breadcrumbs()}
 
         <ul class="links icon-only-links">
 
           <li>
 
             <span><a id="refresh" href="${h.url('journal')}"><i class="icon-refresh"></i></a></span>
 
           </li>
 
           <li>
 
             <span><a href="${h.url('journal_atom', api_key=c.rhodecode_user.api_key)}"><i class="icon-rss-sign"></i></a></span>
 
             <span><a href="${h.url('journal_atom', api_key=c.authuser.api_key)}"><i class="icon-rss-sign"></i></a></span>
 
           </li>
 
         </ul>
 
        </div>
 
        <div id="journal">${c.journal_data}</div>
 
    </div>
 
    <div class="box box-right">
 
        <!-- box / title -->
 

	
 
        <div class="title">
 
            <h5>
 
            <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
 
            <input class="q_filter_box" id="q_filter_watched" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
kallithea/templates/pullrequests/pullrequest_show.html
Show inline comments
 
@@ -106,37 +106,37 @@ ${self.repo_context_bar('showpullrequest
 
          ## members goes here !
 
          <div>
 
            <ul id="review_members" class="group_members">
 
            %for member,status in c.pull_request_reviewers:
 
              <li id="reviewer_${member.user_id}">
 
                <div class="reviewers_member">
 
                    <div class="reviewer_status tooltip" title="${h.tooltip(h.changeset_status_lbl(status[0][1].status if status else 'not_reviewed'))}">
 
                      <img src="${h.url(str('/images/icons/flag_status_%s.png' % (status[0][1].status if status else 'not_reviewed')))}"/>
 
                    </div>
 
                  <div class="reviewer_gravatar gravatar"><img alt="gravatar" src="${h.gravatar_url(member.email,14)}"/> </div>
 
                  <div style="float:left;">${member.full_name} (${_('owner') if c.pull_request.user_id == member.user_id else _('reviewer')})</div>
 
                  <input type="hidden" value="${member.user_id}" name="review_members" />
 
                  %if not c.pull_request.is_closed() and (h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.user_id == c.rhodecode_user.user_id):
 
                  %if not c.pull_request.is_closed() and (h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.user_id == c.authuser.user_id):
 
                  <div class="reviewer_member_remove action_button" onclick="removeReviewMember(${member.user_id})">
 
                      <i class="icon-remove-sign" style="color: #FF4444;"></i>
 
                  </div>
 
                  %endif
 
                </div>
 
              </li>
 
            %endfor
 
            </ul>
 
          </div>
 
          %if not c.pull_request.is_closed():
 
          <div class='ac'>
 
            %if h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.author.user_id == c.rhodecode_user.user_id:
 
            %if h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.author.user_id == c.authuser.user_id:
 
            <div class="reviewer_ac">
 
               ${h.text('user', class_='yui-ac-input')}
 
               <span class="help-block">${_('Add or remove reviewer to this pull request.')}</span>
 
               <div id="reviewers_container"></div>
 
            </div>
 
            <div style="padding:0px 10px">
 
             <span id="update_pull_request" class="btn btn-mini">${_('Save Changes')}</span>
 
            </div>
 
            %endif
 
          </div>
 
          %endif
 
        </div>
kallithea/templates/pullrequests/pullrequest_show_all.html
Show inline comments
 
@@ -19,25 +19,25 @@
 
    ${self.menu('repositories')}
 
</%def>
 

	
 
<%def name="main()">
 
${self.repo_context_bar('showpullrequest')}
 

	
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
        <ul class="links">
 
          <li>
 
             %if c.rhodecode_user.username != 'default':
 
             %if c.authuser.username != 'default':
 
              <span>
 
                  <a id="open_new_pr" class="btn btn-small btn-success" href="${h.url('pullrequest_home',repo_name=c.repo_name)}"><i class="icon-plus"></i> ${_('Open new pull request')}</a>
 
              </span>
 
             %endif
 
              <span>
 
                %if c.from_:
 
                    <a class="btn btn-small" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed)}"><i class="icon-loop-2"></i> ${_('Show pull requests to %s') % c.repo_name}</a>
 
                %else:
 
                    <a class="btn btn-small" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed,from_=1)}"><i class="icon-loop-2"></i> ${_('Show pull requests from %s') % c.repo_name}</a>
 
                %endif
 
              </span>
 
          </li>
kallithea/templates/summary/statistics.html
Show inline comments
 
@@ -7,26 +7,26 @@
 
    %endif
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${_('Statistics')}
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('repositories')}
 
</%def>
 

	
 
<%def name="head_extra()">
 
<link href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('%s ATOM feed') % c.repo_name}" type="application/atom+xml" />
 
<link href="${h.url('rss_feed_home',repo_name=c.db_repo.repo_name,api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('%s RSS feed') % c.repo_name}" type="application/rss+xml" />
 
<link href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=c.authuser.api_key)}" rel="alternate" title="${_('%s ATOM feed') % c.repo_name}" type="application/atom+xml" />
 
<link href="${h.url('rss_feed_home',repo_name=c.db_repo.repo_name,api_key=c.authuser.api_key)}" rel="alternate" title="${_('%s RSS feed') % c.repo_name}" type="application/rss+xml" />
 
</%def>
 

	
 
<%def name="main()">
 
${self.repo_context_bar('summary')}
 
    <%
 
    summary = lambda n:{False:'summary-short'}.get(n)
 
    %>
 
    <div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
kallithea/templates/summary/summary.html
Show inline comments
 
@@ -30,26 +30,26 @@
 
    %if c.db_repo.clone_uri:
 
    <span>
 
       - <i class="icon-code-fork"></i> ${_('Clone from')} "<a href="${h.url(str(h.hide_credentials(c.db_repo.clone_uri)))}">${h.hide_credentials(c.db_repo.clone_uri)}</a>"
 
    <span>
 
    %endif
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('repositories')}
 
</%def>
 

	
 
<%def name="head_extra()">
 
<link href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('%s ATOM feed') % c.repo_name}" type="application/atom+xml" />
 
<link href="${h.url('rss_feed_home',repo_name=c.db_repo.repo_name,api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('%s RSS feed') % c.repo_name}" type="application/rss+xml" />
 
<link href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=c.authuser.api_key)}" rel="alternate" title="${_('%s ATOM feed') % c.repo_name}" type="application/atom+xml" />
 
<link href="${h.url('rss_feed_home',repo_name=c.db_repo.repo_name,api_key=c.authuser.api_key)}" rel="alternate" title="${_('%s RSS feed') % c.repo_name}" type="application/rss+xml" />
 

	
 
<script>
 
redirect_hash_branch = function(){
 
    var branch = window.location.hash.replace(/^#(.*)/, '$1');
 
    if (branch){
 
        window.location = "${h.url('changelog_home',repo_name=c.repo_name,branch='__BRANCH__')}"
 
            .replace('__BRANCH__',branch);
 
    }
 
}
 
redirect_hash_branch();
 
window.onhashchange = function() {
 
    redirect_hash_branch();
 
@@ -149,34 +149,34 @@ summary = lambda n:{False:'summary-short
 
               <a title="${_('Followers')}" href="${h.url('repo_followers_home',repo_name=c.repo_name)}">
 
                <i class="icon-heart"></i> ${_('Followers')}
 
                <span class="stats-bullet" id="current_followers_count">${c.repository_followers}</span>
 
              </a>
 
            </li>
 
            <li>
 
              <a title="${_('Forks')}" href="${h.url('repo_forks_home',repo_name=c.repo_name)}">
 
                <i class="icon-code-fork"></i> ${_('Forks')}
 
                <span class="stats-bullet">${c.repository_forks}</span>
 
              </a>
 
            </li>
 

	
 
            %if c.rhodecode_user.username != 'default':
 
            %if c.authuser.username != 'default':
 
            <li class="repo_size">
 
              <a href="#" onclick="javascript:showRepoSize('repo_size_2','${c.db_repo.repo_name}','${str(h.get_token())}')"><i class="icon-archive"></i> ${_('Repository Size')}</a>
 
              <span  class="stats-bullet" id="repo_size_2"></span>
 
            </li>
 
            %endif
 

	
 
            <li>
 
            %if c.rhodecode_user.username != 'default':
 
              <a href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=c.rhodecode_user.api_key)}"><i class="icon-rss-sign"></i> ${_('Feed')}</a>
 
            %if c.authuser.username != 'default':
 
              <a href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=c.authuser.api_key)}"><i class="icon-rss-sign"></i> ${_('Feed')}</a>
 
            %else:
 
              <a href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name)}"><i class="icon-rss-sign"></i> ${_('Feed')}</a>
 
            %endif
 
            </li>
 

	
 
            %if c.show_stats:
 
            <li>
 
              <a title="${_('Statistics')}" href="${h.url('repo_stats_home',repo_name=c.repo_name)}">
 
                <i class="icon-bar-chart"></i> ${_('Statistics')}
 
              </a>
 
            </li>
 
            %endif
kallithea/tests/__init__.py
Show inline comments
 
@@ -189,29 +189,29 @@ class TestController(BaseTestCase):
 

	
 
    def log_user(self, username=TEST_USER_ADMIN_LOGIN,
 
                 password=TEST_USER_ADMIN_PASS):
 
        self._logged_username = username
 
        response = self.app.post(url(controller='login', action='index'),
 
                                 {'username': username,
 
                                  'password': password})
 

	
 
        if 'invalid user name' in response.body:
 
            self.fail('could not login using %s %s' % (username, password))
 

	
 
        self.assertEqual(response.status, '302 Found')
 
        ses = response.session['rhodecode_user']
 
        ses = response.session['authuser']
 
        self.assertEqual(ses.get('username'), username)
 
        response = response.follow()
 
        self.assertEqual(ses.get('is_authenticated'), True)
 

	
 
        return response.session['rhodecode_user']
 
        return response.session['authuser']
 

	
 
    def _get_logged_user(self):
 
        return User.get_by_username(self._logged_username)
 

	
 
    def checkSessionFlash(self, response, msg):
 
        self.assertTrue('flash' in response.session,
 
                        msg='Response session have no flash key' % response.session)
 
        if not msg in response.session['flash'][0][1]:
 
            msg = u'msg `%s` not found in session flash: got `%s` instead' % (
 
                      msg, response.session['flash'][0][1])
 
            self.fail(safe_str(msg))
kallithea/tests/functional/test_login.py
Show inline comments
 
@@ -24,36 +24,36 @@ class TestLoginController(TestController
 
        self.assertEqual(Notification.query().all(), [])
 

	
 
    def test_index(self):
 
        response = self.app.get(url(controller='login', action='index'))
 
        self.assertEqual(response.status, '200 OK')
 
        # Test response...
 

	
 
    def test_login_admin_ok(self):
 
        response = self.app.post(url(controller='login', action='index'),
 
                                 {'username': 'test_admin',
 
                                  'password': 'test12'})
 
        self.assertEqual(response.status, '302 Found')
 
        self.assertEqual(response.session['rhodecode_user'].get('username'),
 
        self.assertEqual(response.session['authuser'].get('username'),
 
                         'test_admin')
 
        response = response.follow()
 
        response.mustcontain('/%s' % HG_REPO)
 

	
 
    def test_login_regular_ok(self):
 
        response = self.app.post(url(controller='login', action='index'),
 
                                 {'username': 'test_regular',
 
                                  'password': 'test12'})
 

	
 
        self.assertEqual(response.status, '302 Found')
 
        self.assertEqual(response.session['rhodecode_user'].get('username'),
 
        self.assertEqual(response.session['authuser'].get('username'),
 
                         'test_regular')
 
        response = response.follow()
 
        response.mustcontain('/%s' % HG_REPO)
 

	
 
    def test_login_ok_came_from(self):
 
        test_came_from = '/_admin/users'
 
        response = self.app.post(url(controller='login', action='index',
 
                                     came_from=test_came_from),
 
                                 {'username': 'test_admin',
 
                                  'password': 'test12'})
 
        self.assertEqual(response.status, '302 Found')
 
        response = response.follow()
0 comments (0 inline, 0 general)