Changeset - cc8d7d450d15
[Not reviewed]
beta
0 3 0
Marcin Kuzminski - 13 years ago 2012-07-26 22:01:41
marcin@python-works.com
No more raw html inside users controller.
We use cool mako Template features
3 files changed with 41 insertions and 22 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/users.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.controllers.admin.users
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Users crud controller for pylons
 

	
 
    :created_on: Apr 4, 2010
 
    :author: marcink
 
    :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
import traceback
 
import formencode
 
from pylons import response
 

	
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url, config
 
from pylons.controllers.util import redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib.exceptions import DefaultUserException, \
 
    UserOwnsReposException
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
 
    AuthUser
 
from rhodecode.lib.base import BaseController, render
 

	
 
import rhodecode
 
from rhodecode.model.db import User, Permission, UserEmailMap
 
from rhodecode.model.forms import UserForm
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.meta import Session
 
from rhodecode.lib.utils import action_logger
 
from rhodecode.lib.compat import json
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersController(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('user', 'users')
 

	
 
    @LoginRequired()
 
    @HasPermissionAllDecorator('hg.admin')
 
    def __before__(self):
 
        c.admin_user = session.get('admin_user')
 
        c.admin_username = session.get('admin_username')
 
        super(UsersController, self).__before__()
 
        c.available_permissions = config['available_permissions']
 

	
 
    def index(self, format='html'):
 
        """GET /users: All items in the collection"""
 
        # url('users')
 

	
 
        c.users_list = User.query().order_by(User.username).all()
 

	
 
        users_data = []
 
        total_records = len(c.users_list)
 
        grav_tmpl = """<div class="gravatar"><img alt="gravatar" src="%s"/> </div>"""
 
        usr_tmpl = """<a href="%s">%s</a>""" % (h.url('edit_user', id='__ID__'), '%s')
 
        usr_tmpl = usr_tmpl.replace('__ID__', '%s')
 
        edit_tmpl = '''
 
            <form action="/_admin/users/%s" method="post">
 
            <div style="display:none">
 
            <input name="_method" type="hidden" value="%s">
 
            </div>
 
            <input class="delete_icon action_button" id="remove_user_%s" 
 
            name="remove_" onclick="return confirm('%s');" 
 
            type="submit" value="delete">
 
            </form>
 
        '''
 
        _tmpl_lookup = rhodecode.CONFIG['pylons.app_globals'].mako_lookup
 
        template = _tmpl_lookup.get_template('data_table/_dt_elements.html')
 

	
 
        grav_tmpl = lambda user_email, size: (
 
                template.get_def("user_gravatar")
 
                .render(user_email, size, _=_, h=h))
 

	
 
        user_lnk = lambda user_id, username: (
 
                template.get_def("user_name")
 
                .render(user_id, username, _=_, h=h))
 

	
 
        user_actions = lambda user_id, username: (
 
                template.get_def("user_actions")
 
                .render(user_id, username, _=_, h=h))
 

	
 
        for user in c.users_list:
 
            users_data.append({
 
                "gravatar": grav_tmpl % h.gravatar_url(user.email, 24),
 
                "gravatar": grav_tmpl(user. email, 24),
 
                "raw_username": user.username,
 
                "username": usr_tmpl % (user.user_id, user.username),
 
                "username": user_lnk(user.user_id, user.username),
 
                "firstname": user.name,
 
                "lastname": user.lastname,
 
                "last_login": h.fmt_date(user.last_login),
 
                "active": h.bool2icon(user.active),
 
                "admin": h.bool2icon(user.admin),
 
                "ldap": h.bool2icon(bool(user.ldap_dn)),
 
                "action": edit_tmpl % (user.user_id, _('delete'),
 
                    user.user_id,
 
                    _('Confirm to delete this user: %s') % user.username
 
                ),
 
                "action": user_actions(user.user_id, user.username),
 
            })
 

	
 
        c.data = json.dumps({
 
            "totalRecords": total_records,
 
            "startIndex": 0,
 
            "sort": None,
 
            "dir": "asc",
 
            "records": users_data
 
        })
 

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

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

	
 
        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,
 
                          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 Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during creation of user %s') \
 
                    % request.POST.get('username'), category='error')
 
        return redirect(url('users'))
 

	
 
    def new(self, format='html'):
 
        """GET /users/new: Form to create a new item"""
 
        # url('new_user')
 
        return render('admin/users/user_add.html')
 

	
 
    def update(self, id):
 
        """PUT /users/id: Update an existing item"""
 
        # Forms posted to this method should contain a hidden field:
rhodecode/templates/admin/users/users.html
Show inline comments
 
@@ -95,54 +95,51 @@
 
        containerClass: 'pagination-wh',
 
        currentPageClass: 'pager_curpage',
 
        pageLinkClass: 'pager_link',
 
        nextPageLinkLabel: '&gt;',
 
        previousPageLinkLabel: '&lt;',
 
        firstPageLinkLabel: '&lt;&lt;',
 
        lastPageLinkLabel: '&gt;&gt;',
 
        containers:['user-paginator']
 
    }),
 

	
 
    MSG_SORTASC:"${_('Click to sort ascending')}",
 
    MSG_SORTDESC:"${_('Click to sort descending')}",
 
    MSG_EMPTY:"${_('No records found.')}",
 
    MSG_ERROR:"${_('Data error.')}",
 
    MSG_LOADING:"${_('Loading...')}",
 
  }
 
  );
 
  myDataTable.subscribe('postRenderEvent',function(oArgs) {
 

	
 
  });
 
  
 
  var filterTimeout = null;
 

	
 
  updateFilter  = function () {
 
      // Reset timeout
 
      filterTimeout = null;
 

	
 
      // Reset sort
 
      var state = myDataTable.getState();
 
          state.sortedBy = {key:'username', dir:YAHOO.widget.DataTable.CLASS_ASC};
 

	
 
      // Get filtered data
 
      myDataSource.sendRequest(YUD.get('q_filter').value,{
 
          success : myDataTable.onDataReturnInitializeTable,
 
          failure : myDataTable.onDataReturnInitializeTable,
 
          scope   : myDataTable,
 
          argument: state
 
      });
 

	
 
  };  
 
  YUE.on('q_filter','click',function(){
 
      YUD.get('q_filter').value = '';
 
   });
 

	
 
  YUE.on('q_filter','keyup',function (e) {
 
      clearTimeout(filterTimeout);
 
      filterTimeout = setTimeout(updateFilter,600);
 
  });  
 
  
 
  
 
  
 
</script>
 

	
 
</%def>
rhodecode/templates/data_table/_dt_elements.html
Show inline comments
 
## DATA TABLE RE USABLE ELEMENTS
 
## usage:
 
## <%namespace name="dt" file="/data_table/_dt_elements.html"/>
 

	
 
<%def name="repo_actions(repo_name)">
 
  ${h.form(h.url('repo', repo_name=repo_name),method='delete')}
 
    ${h.submit('remove_%s' % repo_name,_('delete'),class_="delete_icon action_button",onclick="return confirm('"+_('Confirm to delete this repository: %s') % repo_name+"');")}
 
  ${h.end_form()}
 
</%def>
 

	
 
<%def name="quick_menu(repo_name)">
 
  <ul class="menu_items hidden">
 
    <li style="border-top:1px solid #003367;margin-left:18px;padding-left:-99px"></li>
 
    <li>
 
       <a title="${_('Summary')}" href="${h.url('summary_home',repo_name=repo_name)}">
 
       <span class="icon">
 
           <img src="${h.url('/images/icons/clipboard_16.png')}" alt="${_('Summary')}" />
 
       </span>
 
       <span>${_('Summary')}</span>
 
       </a>
 
    </li>
 
    <li>
 
       <a title="${_('Changelog')}" href="${h.url('changelog_home',repo_name=repo_name)}">
 
       <span class="icon">
 
           <img src="${h.url('/images/icons/time.png')}" alt="${_('Changelog')}" />
 
       </span>
 
       <span>${_('Changelog')}</span>
 
       </a>
 
    </li>
 
    <li>
 
       <a title="${_('Files')}" href="${h.url('files_home',repo_name=repo_name)}">
 
       <span class="icon">
 
           <img src="${h.url('/images/icons/file.png')}" alt="${_('Files')}" />
 
       </span>
 
       <span>${_('Files')}</span>
 
       </a>
 
    </li>
 
    <li>
 
       <a title="${_('Fork')}" href="${h.url('repo_fork_home',repo_name=repo_name)}">
 
       <span class="icon">
 
           <img src="${h.url('/images/icons/arrow_divide.png')}" alt="${_('Fork')}" />
 
       </span>
 
       <span>${_('Fork')}</span>
 
       </a>
 
    </li>
 
  </ul>
 
</%def>
 

	
 
<%def name="repo_name(name,rtype,private,fork_of,short_name=False, admin=False)">
 
    <%
 
    def get_name(name,short_name=short_name):
 
      if short_name:
 
        return name.split('/')[-1]
 
      else:
 
        return name
 
    %>
 
  <div style="white-space: nowrap">
 
   ##TYPE OF REPO
 
   %if h.is_hg(rtype):
 
     <img class="icon" title="${_('Mercurial repository')}" alt="${_('Mercurial repository')}" src="${h.url('/images/icons/hgicon.png')}"/>
 
   %elif h.is_git(rtype):
 
     <img class="icon" title="${_('Git repository')}" alt="${_('Git repository')}" src="${h.url('/images/icons/giticon.png')}"/>
 
   %endif
 

	
 
   ##PRIVATE/PUBLIC
 
   %if private:
 
      <img class="icon" title="${_('private repository')}" alt="${_('private repository')}" src="${h.url('/images/icons/lock.png')}"/>
 
   %else:
 
      <img class="icon" title="${_('public repository')}" alt="${_('public repository')}" src="${h.url('/images/icons/lock_open.png')}"/>
 
   %endif
 

	
 
   ##NAME
 
   %if admin:
 
    ${h.link_to(get_name(name),h.url('edit_repo',repo_name=name),class_="repo_name")}
 
   %else:
 
    ${h.link_to(get_name(name),h.url('summary_home',repo_name=name),class_="repo_name")}
 
   %endif
 
   %if fork_of:
 
        <a href="${h.url('summary_home',repo_name=fork_of)}">
 
        <img class="icon" alt="${_('fork')}" title="${_('Fork of')} ${fork_of}" src="${h.url('/images/icons/arrow_divide.png')}"/></a>
 
   %endif
 
  </div>
 
</%def>
 

	
 

	
 

	
 
<%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="user_gravatar(email, size=24)">
 
    <div class="gravatar"><img alt="gravatar" src="${h.gravatar_url(email, size)}"/> </div>
 
</%def>
 

	
 
<%def name="user_actions(user_id, username)">
 
  ${h.form(h.url('delete_user', id=user_id),method='delete')}
 
      ${h.submit('remove_',_('delete'),id="remove_user_%s" % user_id,
 
      class_="delete_icon action_button",onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
 
  ${h.end_form()}
 
</%def>
 

	
 
<%def name="user_name(user_id, username)">
 
    ${h.link_to(username,h.url('edit_user', id=user_id))}
 
</%def>
 

	
0 comments (0 inline, 0 general)