Changeset - 9fe23fdab9e9
[Not reviewed]
default
0 3 1
Marcin Kuzminski - 16 years ago 2010-04-17 19:59:06
marcin@python-blog.com
Implemented AJAH paging
4 files changed with 42 insertions and 26 deletions:
0 comments (0 inline, 0 general)
pylons_app/controllers/admin.py
Show inline comments
 
import logging
 

	
 
from pylons import request, response, session, tmpl_context as c, url, app_globals as g
 
from pylons.controllers.util import abort, redirect
 

	
 
from pylons_app.lib.base import BaseController, render
 
import os
 
from mercurial import ui, hg
 
from mercurial.error import RepoError
 
from ConfigParser import ConfigParser
 
from pylons_app.lib import auth
 
from pylons_app.model.forms import LoginForm
 
import formencode
 
import formencode.htmlfill as htmlfill
 
from pylons_app.model import meta
 
from pylons_app.model.db import Users, UserLogs
 
from webhelpers.paginate import Page
 
log = logging.getLogger(__name__)
 

	
 
class AdminController(BaseController):
 

	
 
    def __before__(self):
 
        c.staticurl = g.statics
 
        c.admin_user = session.get('admin_user', False)
 
        c.admin_username = session.get('admin_username')
 
        
 
    def index(self):
 
        # Return a rendered template
 
        if request.POST:
 
            #import Login Form validator class
 
            login_form = LoginForm()
 

	
 
            try:
 
                c.form_result = login_form.to_python(dict(request.params))
 
                if auth.admin_auth(c.form_result['username'], c.form_result['password']):
 
                    session['admin_user'] = True
 
                    session['admin_username'] = c.form_result['username']
 
                    session.save()
 
                    return redirect(url('admin_home'))
 
                else:
 
                    raise formencode.Invalid('Login Error', None, None,
 
                                             error_dict={'username':'invalid login',
 
                                                         'password':'invalid password'})
 
                                      
 
            except formencode.Invalid, error:
 
                c.form_result = error.value
 
                c.form_errors = error.error_dict or {}
 
                html = render('/admin.html')
 

	
 
                return htmlfill.render(
 
                    html,
 
                    defaults=c.form_result,
 
                    encoding="UTF-8"
 
                )
 
        if c.admin_user:
 
            sa = meta.Session
 
                             
 
            users_log = sa.query(UserLogs)\
 
                .order_by(UserLogs.action_date.desc())
 
            p = int(request.params.get('page', 1))
 
            c.users_log = Page(users_log, page=p, items_per_page=10)
 
            c.log_data = render('admin_log.html')
 
            if request.params.get('partial'):
 
                return c.log_data
 
        return render('/admin.html')
 

	
 
    def hgrc(self, dirname):
 
        filename = os.path.join(dirname, '.hg', 'hgrc')
 
        return filename
 

	
 
    def add_repo(self, new_repo):
 
        
 

	
 
        #extra check it can be add since it's the command
 
        if new_repo == '_admin':
 
            c.msg = 'DENIED'
 
            c.new_repo = ''
 
            return render('add.html')
 

	
 
        new_repo = new_repo.replace(" ", "_")
 
        new_repo = new_repo.replace("-", "_")
 

	
 
        try:
 
            self._create_repo(new_repo)
 
            c.new_repo = new_repo
 
            c.msg = 'added repo'
 
        except Exception as e:
 
            c.new_repo = 'Exception when adding: %s' % new_repo
 
            c.msg = str(e)
 

	
 
        return render('add.html')
 

	
 
    def _check_repo(self, repo_name):
 
        p = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
 
        config_path = os.path.join(p, 'hgwebdir.config')
 

	
 
        cp = ConfigParser()
 

	
 
        cp.read(config_path)
 
        repos_path = cp.get('paths', '/').replace("**", '')
 

	
 
        if not repos_path:
 
            raise Exception('Could not read config !')
 

	
 
        self.repo_path = os.path.join(repos_path, repo_name)
 

	
 
        try:
 
            r = hg.repository(ui.ui(), self.repo_path)
 
            hg.verify(r)
 
            #here we hnow that repo exists it was verified
 
            log.info('%s repo is already created', repo_name)
 
            raise Exception('Repo exists')
 
        except RepoError:
 
            log.info('%s repo is free for creation', repo_name)
 
            #it means that there is no valid repo there...
 
            return True
 

	
 

	
 
    def _create_repo(self, repo_name):
 
        if repo_name in [None, '', 'add']:
 
            raise Exception('undefined repo_name of repo')
 

	
 
        if self._check_repo(repo_name):
 
            log.info('creating repo %s in %s', repo_name, self.repo_path)
 
            cmd = """mkdir %s && hg init %s""" \
 
                    % (self.repo_path, self.repo_path)
 
            os.popen(cmd)
pylons_app/templates/admin.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="base/base.html"/>
 
 <%def name="get_form_error(element)">
 
    %if type(c.form_errors) == dict:
 
        %if c.form_errors.get(element,False):
 
            <span class="error-message">
 
                ${c.form_errors.get(element,'')}
 
            </span>
 
        %endif
 
    %endif           
 
 </%def>
 
<%def name="title()">
 
    ${_('Repository managment')}
 
</%def>
 
<%def name="breadcrumbs()">
 
	${h.link_to(u'Home',h.url('/'))}
 
	 / 
 
	${h.link_to(u'Admin',h.url('admin_home'))}
 
</%def>
 
<%def name="page_nav()">
 
<li>${h.link_to(u'Home',h.url('/'))}</li>
 
<li class="current">${_('Admin')}</li>
 
</%def>
 
<%def name="main()">
 
    %if c.admin_user:
 
    <ul class="submenu">
 
        <li>
 
            ${h.link_to(u'Repos',h.url('repos'))}
 
        </li>
 
        <li>
 
            ${h.link_to(u'Users',h.url('users'))}
 
        </li>
 
    </ul>
 
    <br/>
 
    <div>
 
        <h2>Welcome ${c.admin_username}</h2>
 
        <div>${_('Last 10 user actions')}</div>
 
        %if c.users_log:
 
	        <table>
 
	        <tr>
 
	        	<td>${_('Username')}</td>
 
	        	<td>${_('Repository')}</td>
 
	        	<td>${_('Action')}</td>
 
	        	<td>${_('Date')}</td>
 
	        </tr>
 
	        %for cnt,l in enumerate(c.users_log):
 
				<tr class="parity${cnt%2}">
 
					<td>${l.user.username}</td>
 
					<td>${l.repository}</td>
 
					<td>${l.action}</td>
 
					<td>${l.action_date}</td>
 
				</tr>
 
			%endfor
 
			<tr>
 
				<td>${c.users_log.pager('$link_previous ~2~ $link_next')}</td>
 
			</tr>
 
			</table>        
 
		%else:
 
			${_('No actions yet')}
 
		%endif
 

	
 
		    <div id="user_log">
 
				${c.log_data}
 
			</div>
 
    </div>
 
    %else:
 
        <div>
 
        <br />
 
        <h2>${_('Login')}</h2>
 
        ${h.form(h.url.current())}
 
        <table>
 
            <tr>
 
                <td>${_('Username')}</td>
 
                <td>${h.text('username')}</td>
 
                <td>${get_form_error('username')} </td>
 
            </tr>
 
            <tr>
 
                <td>${_('Password')}</td>
 
                <td>${h.password('password')}</td>
 
                <td>${get_form_error('password')}</td> 
 
            </tr>
 
            <tr>
 
                <td></td>
 
                <td>${h.submit('login','login')}</td>
 
            </tr>            
 
        </table>
 
        ${h.end_form()}
 
        </div>
 
    %endif
 
    
 
</%def>
 
\ No newline at end of file
pylons_app/templates/admin_log.html
Show inline comments
 
new file 100644
 
%if c.users_log:
 
<table>
 
	<tr>
 
		<td>${_('Username')}</td>
 
		<td>${_('Repository')}</td>
 
		<td>${_('Action')}</td>
 
		<td>${_('Date')}</td>
 
	</tr>
 

	
 
	%for cnt,l in enumerate(c.users_log):
 
	<tr class="parity${cnt%2}">
 
		<td>${l.user.username}</td>
 
		<td>${l.repository}</td>
 
		<td>${l.action}</td>
 
		<td>${l.action_date}</td>
 
	</tr>
 
	%endfor
 

	
 
	<tr>
 
		<td>${c.users_log.pager('$link_previous ~2~ $link_next',
 
		onclick="""YAHOO.util.Connect.asyncRequest('GET','$partial_url',{
 
		success:function(o){YAHOO.util.Dom.get('user_log').innerHTML=o.responseText;}
 
		},null); return false;""")}</td>
 
	</tr>
 
</table>
 

	
 
%else: 
 
	${_('No actions yet')} 
 
%endif
pylons_app/templates/base/base.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
##filters definition
 
<%namespace name="f" module="pylons_app.lib.filters" inheritable="True"/>
 

	
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
 
    <link rel="icon" href="${c.staticurl}hgicon.png" type="image/png" />
 
    <meta name="robots" content="index, nofollow"/>
 
    <link rel="stylesheet" href="${c.staticurl}style-monoblue.css" type="text/css" />
 
       <title>${next.title()}</title>
 
    ${self.js()}
 
</head>
 

	
 
<body>
 
<div id="container">
 
    <div class="page-header">
 
        <h1>
 
            ${next.breadcrumbs()}
 
        </h1>
 
        <ul class="page-nav">
 
            ${next.page_nav()}
 
        </ul>
 
    </div>
 
    ${next.main()}
 
    <div class="page-footer">
 
        Mercurial App &copy; 2010
 
    </div>   
 

	
 
    <div id="powered-by">
 
        <p>
 
        <a href="http://mercurial.selenic.com/" title="Mercurial">
 
            <img src="${c.staticurl}hglogo.png" width="75" height="90" alt="mercurial"/></a>
 
        </p>
 
    </div>
 

	
 
    <div id="corner-top-left"></div>
 
    <div id="corner-top-right"></div>
 
    <div id="corner-bottom-left"></div>
 
    <div id="corner-bottom-right"></div>
 

	
 
</div>
 
</body>
 
</html>
 
\ No newline at end of file
 
</html>
 

	
 

	
 
<%def name="js()">
 
<script type="text/javascript" src="/js/yui/utilities/utilities.js"></script>
 
</%def>
 
\ No newline at end of file
0 comments (0 inline, 0 general)