Changeset - a886f5eba757
[Not reviewed]
default
0 6 0
marcink - 16 years ago 2010-04-07 17:28:10

implemented admin page login
6 files changed with 85 insertions and 50 deletions:
0 comments (0 inline, 0 general)
pylons_app/controllers/admin.py
Show inline comments
 
@@ -6,23 +6,54 @@ from pylons.controllers.util import abor
 
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
 
log = logging.getLogger(__name__)
 

	
 
class AdminController(BaseController):
 

	
 

	
 
    def __before__(self):
 
        c.staticurl = g.statics
 
        c.admin_user = True
 
        c.admin_user = session.get('admin_user')
 
        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.authfunc(None, c.form_result['username'], c.form_result['password']) and\
 
                    c.form_result['username'] == 'admin':
 
                    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"
 
                )
 
        return render('/admin.html')
 

	
 
    def repos_manage(self):
 
        return render('/repos_manage.html')
 
    
 
    def users_manage(self):
pylons_app/lib/auth.py
Show inline comments
 
@@ -20,38 +20,36 @@ def authfunc(environ, username, password
 
    try:
 
        cur.execute("SELECT * FROM users WHERE username=?", (username,))
 
        data = cur.fetchone()
 
    except sqlite3.OperationalError as e:
 
        data = None
 
        log.error(e)
 

	
 
    if data:
 
        if data[3]:
 
            if data[1] == username and data[2] == password_crypt:
 
                log.info('user %s authenticated correctly', username)
 
                
 
                http_accept = environ.get('HTTP_ACCEPT')
 
        
 
                if http_accept.startswith('application/mercurial') or \
 
                    environ['PATH_INFO'].find('raw-file') != -1:
 
                    cmd = environ['PATH_INFO']
 
                    for qry in environ['QUERY_STRING'].split('&'):
 
                        if qry.startswith('cmd'):
 
                            cmd += "|" + qry
 
                            
 
                            try:
 
                                cur.execute('''INSERT INTO 
 
                                                    user_logs 
 
                                               VALUES(?,?,?,?)''',
 
                                                (None, data[0], cmd, datetime.now()))
 
                                conn.commit()
 
                            except Exception as e:
 
                                conn.rollback()
 
                                log.error(e)
 
                            
 
                if environ:
 
                    http_accept = environ.get('HTTP_ACCEPT')
 
            
 
                    if http_accept.startswith('application/mercurial') or \
 
                        environ['PATH_INFO'].find('raw-file') != -1:
 
                        cmd = environ['PATH_INFO']
 
                        for qry in environ['QUERY_STRING'].split('&'):
 
                            if qry.startswith('cmd'):
 
                                cmd += "|" + qry
 
                                
 
                                try:
 
                                    cur.execute('''INSERT INTO 
 
                                                        user_logs 
 
                                                   VALUES(?,?,?,?)''',
 
                                                    (None, data[0], cmd, datetime.now()))
 
                                    conn.commit()
 
                                except Exception as e:
 
                                    conn.rollback()
 
                                    log.error(e)
 
                                  
 
                return True
 
        else:
 
            log.error('user %s is disabled', username)
 
            
 
    return False
 

	
pylons_app/lib/helpers.py
Show inline comments
 
@@ -9,13 +9,13 @@ from webhelpers.html.tools import (auto_
 
                                   , mail_to, strip_links, strip_tags, tag_re)
 
from webhelpers.html.tags import (auto_discovery_link, checkbox, css_classes,
 
                                  end_form, file, form, hidden, image,
 
                                  javascript_link, link_to, link_to_if,
 
                                  link_to_unless, ol, required_legend,
 
                                  select, stylesheet_link,
 
                                  submit, text, textarea, title, ul, xml_declaration)
 
                                  submit, text, password, textarea, title, ul, xml_declaration)
 
from webhelpers.text import (chop_at, collapse, convert_accented_entities,
 
                             convert_misc_characters, convert_misc_entities,
 
                             lchop, plural, rchop, remove_formatting, replace_whitespace,
 
                             urlify)
 

	
 
from webhelpers.pylonslib import Flash as _Flash
pylons_app/model/forms.py
Show inline comments
 
@@ -28,36 +28,31 @@ from webhelpers.pylonslib.secure_form im
 
class ValidAuthToken(formencode.validators.FancyValidator):
 
    messages = {'invalid_token':_('Token mismatch')}
 

	
 
    def validate_python(self, value, state):
 

	
 
        if value != authentication_token():
 
            raise formencode.Invalid(self.message('invalid_token', state, search_number = value), value, state)
 
            raise formencode.Invalid(self.message('invalid_token', state, search_number=value), value, state)
 

	
 

	
 
class WireTransferForm(object):
 
    '''
 
    A factory wrapper class. It might return the instance of class for a validation, but also it can
 
    return the list for select fields values.
 
    @param ret_type: type to return defaut: 'class'
 
    '''
 
    #class attributes here
 
    #it might be fetched from db,from models and so on
 
    recipients_list = [
 
                       (1, 'a'),
 
                       (2, 'b')
 
                       ]
 
class LoginForm(formencode.Schema):
 
    allow_extra_fields = True
 
    filter_extra_fields = True
 
    username = UnicodeString(
 
                             strip=True,
 
                             min=3,
 
                             not_empty=True,
 
                             messages={
 
                                       'empty':_('Please enter a login'),
 
                                       'tooShort':_('Enter a value %(min)i characters long or more')}
 
                            )
 

	
 
    def _form(self):
 
        class _WireTransferForm(formencode.Schema):
 
            allow_extra_fields = True
 
            _authentication_token = ValidAuthToken()
 
            account_number = Regex(r'[0-9]{26}', not_empty = True, messages = {
 
                                                'invalid': _("Account number is invalid, it must be 26 digits")})
 
            title = UnicodeString(not_empty = True, min = 3, strip = True)
 
            recipient = formencode.All(OneOf([i[0] for i in WireTransferForm.recipients_list],
 
                                             testValueList = True, hideList = True), Int())
 
            recipient_address = UnicodeString(not_empty = True, strip = True)
 
            amount = Number(not_empty = True, min = 1)
 
    password = UnicodeString(
 
                            strip=True,
 
                            min=3,
 
                            not_empty=True,
 
                            messages={
 
                                      'empty':_('Please enter a password'),
 
                                      'tooShort':_('Enter a value %(min)i characters long or more')}
 
                                )
 

	
 
        return _WireTransferForm()
 

	
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('/'))}
 
	 / 
 
@@ -33,16 +42,18 @@
 
        <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.text('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>
pylons_app/templates/monoblue_custom/index.tmpl
Show inline comments
 
@@ -6,13 +6,13 @@
 
<body>
 
<div id="container">
 
    <div class="page-header">
 
        <h1>${c.repos_prefix} Mercurial Repositories</h1>
 
        <ul class="page-nav">
 
            <li class="current">Home</li>
 
            <li>${h.link_to(u'Admin',h.url('admin_home'))}</li>
 
            <li><a href="/_admin/">Admin</a></li>
 
        </ul>
 
    </div>
 
    
 
    <table cellspacing="0">
 
        <tr>
 
            <td><a href="?sort={sort_name}">Name</a></td>
0 comments (0 inline, 0 general)