changeset 45:a886f5eba757

implemented admin page login
author marcink
date Wed, 07 Apr 2010 17:28:10 +0200
parents d924b931b488
children 9db7782727b3
files pylons_app/controllers/admin.py pylons_app/lib/auth.py pylons_app/lib/helpers.py pylons_app/model/forms.py pylons_app/templates/admin.html pylons_app/templates/monoblue_custom/index.tmpl
diffstat 6 files changed, 85 insertions(+), 50 deletions(-) [+]
line wrap: on
line diff
--- a/pylons_app/controllers/admin.py	Wed Apr 07 16:42:11 2010 +0200
+++ b/pylons_app/controllers/admin.py	Wed Apr 07 17:28:10 2010 +0200
@@ -9,6 +9,9 @@
 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):
@@ -16,10 +19,38 @@
 
     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):
--- a/pylons_app/lib/auth.py	Wed Apr 07 16:42:11 2010 +0200
+++ b/pylons_app/lib/auth.py	Wed Apr 07 17:28:10 2010 +0200
@@ -23,32 +23,30 @@
     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)
--- a/pylons_app/lib/helpers.py	Wed Apr 07 16:42:11 2010 +0200
+++ b/pylons_app/lib/helpers.py	Wed Apr 07 17:28:10 2010 +0200
@@ -12,7 +12,7 @@
                                   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,
--- a/pylons_app/model/forms.py	Wed Apr 07 16:42:11 2010 +0200
+++ b/pylons_app/model/forms.py	Wed Apr 07 17:28:10 2010 +0200
@@ -31,33 +31,28 @@
     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()
 
--- a/pylons_app/templates/admin.html	Wed Apr 07 16:42:11 2010 +0200
+++ b/pylons_app/templates/admin.html	Wed Apr 07 17:28:10 2010 +0200
@@ -1,5 +1,14 @@
 ## -*- 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>
@@ -36,10 +45,12 @@
             <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>
--- a/pylons_app/templates/monoblue_custom/index.tmpl	Wed Apr 07 16:42:11 2010 +0200
+++ b/pylons_app/templates/monoblue_custom/index.tmpl	Wed Apr 07 17:28:10 2010 +0200
@@ -9,7 +9,7 @@
         <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>