Changeset - 25e516447a33
[Not reviewed]
default
0 4 0
marcink - 16 years ago 2010-04-08 12:00:06

implemented autentication
4 files changed with 30 insertions and 14 deletions:
0 comments (0 inline, 0 general)
pylons_app/controllers/admin.py
Show inline comments
 
@@ -3,32 +3,32 @@ 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.lib.auth import authenticate
 
log = logging.getLogger(__name__)
 

	
 
class AdminController(BaseController):
 

	
 

	
 
    def __before__(self):
 
        c.staticurl = g.statics
 
        c.admin_user = session.get('admin_user')
 
        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
pylons_app/controllers/repos.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 import auth
 
from pylons_app.lib.base import BaseController, render
 
from pylons_app.model import meta
 
from pylons_app.model.db import Users, UserLogs
 
from pylons_app.lib.auth import authenticate
 

	
 
log = logging.getLogger(__name__)
 

	
 
class ReposController(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('repo', 'repos')
 
    
 
    @authenticate
 
    def __before__(self):
 
        c.staticurl = g.statics
 
        c.admin_user = session.get('admin_user')
 
        c.admin_username = session.get('admin_username')
 
        self.sa = meta.Session
 
                
 
    def index(self, format='html'):
 
        """GET /repos: All items in the collection"""
 
        # url('repos')
 
        return render('/repos.html')
 
    
 
    def create(self):
pylons_app/controllers/users.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
 
from formencode import htmlfill
 
from pylons_app.model import meta
 
from pylons_app.model.db import Users, UserLogs
 
from pylons_app.lib.auth import authenticate
 
import crypt
 

	
 
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')
 
    
 
    @authenticate
 
    def __before__(self):
 
        c.staticurl = g.statics
 
        c.admin_user = session.get('admin_user')
 
        c.admin_username = session.get('admin_username')
 
        self.sa = meta.Session
 
        
 
    def index(self, format='html'):
 
        """GET /users: All items in the collection"""
 
        # url('users')
 
        
 
        c.users_list = self.sa.query(Users).all()     
 
        return render('/users.html')
pylons_app/lib/auth.py
Show inline comments
 
import sqlite3
 
import os
 
import logging
 
from os.path import dirname as dn
 
from datetime import datetime
 
import crypt
 

	
 
from pylons import session, url
 
from pylons.controllers.util import abort, redirect
 
from decorator import decorator
 
log = logging.getLogger(__name__)
 
ROOT = dn(dn(dn(os.path.realpath(__file__))))
 

	
 
def get_sqlite_conn_cur():
 
    conn = sqlite3.connect(os.path.join(ROOT, 'auth.sqlite'))
 
    cur = conn.cursor()
 
    return conn, cur
 

	
 

	
 
def admin_auth(username, password):
 
    conn, cur = get_sqlite_conn_cur()
 
    password_crypt = crypt.crypt(password, '6a')
 
@@ -51,73 +53,80 @@ def authfunc(environ, username, password
 
                log.info('user %s authenticated correctly', username)
 
                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 
 
                                    cur.execute("""INSERT INTO 
 
                                                        user_logs 
 
                                                   VALUES(?,?,?,?)''',
 
                                                   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
 

	
 

	
 
@decorator
 
def authenticate(fn, *args, **kwargs):
 
    if not session.get('admin_user', False):
 
        redirect(url('admin_home'), 301)
 
    return fn(*args, **kwargs)
 

	
 
def create_user_table():
 
    '''
 
    """
 
    Create a auth database
 
    '''
 
    """
 
    conn, cur = get_sqlite_conn_cur()
 
    try:
 
        log.info('creating table %s', 'users')
 
        cur.execute('''DROP TABLE IF EXISTS users ''')
 
        cur.execute('''CREATE TABLE users
 
        cur.execute("""DROP TABLE IF EXISTS users """)
 
        cur.execute("""CREATE TABLE users
 
                        (user_id INTEGER PRIMARY KEY AUTOINCREMENT, 
 
                         username TEXT, 
 
                         password TEXT,
 
                         active INTEGER,
 
                         admin INTEGER)''')
 
                         admin INTEGER)""")
 
        log.info('creating table %s', 'user_logs')
 
        cur.execute('''DROP TABLE IF EXISTS user_logs ''')
 
        cur.execute('''CREATE TABLE user_logs
 
        cur.execute("""DROP TABLE IF EXISTS user_logs """)
 
        cur.execute("""CREATE TABLE user_logs
 
                        (id INTEGER PRIMARY KEY AUTOINCREMENT,
 
                            user_id INTEGER,
 
                            last_action TEXT, 
 
                            last_action_date DATETIME)''')
 
                            last_action_date DATETIME)""")
 
        conn.commit()
 
    except:
 
        conn.rollback()
 
        raise
 
    
 
    cur.close()
 
    
 
def create_user(username, password, admin=False):
 
    conn, cur = get_sqlite_conn_cur()    
 
    password_crypt = crypt.crypt(password, '6a')
 
    log.info('creating user %s', username)
 
    try:
 
        cur.execute('''INSERT INTO users values (?,?,?,?,?) ''',
 
        cur.execute("""INSERT INTO users values (?,?,?,?,?) """,
 
                    (None, username, password_crypt, 1, admin))     
 
        conn.commit()
 
    except:
 
        conn.rollback()
 
        raise
 
    
 
if __name__ == "__main__":
 
    create_user_table()
 
    create_user('marcink', 'qweqwe', True)
 
    create_user('lukaszd', 'qweqwe')
 
    create_user('adriand', 'qweqwe')
 
    create_user('radek', 'qweqwe')
0 comments (0 inline, 0 general)