Changeset - 9db7782727b3
[Not reviewed]
default
0 5 0
Marcin Kuzminski - 16 years ago 2010-04-07 19:39:31
marcin@python-blog.com
Static files for production fixed
Error handler for debug on, added
admin auth function authenticates only admins
changed creation of db
5 files changed with 33 insertions and 14 deletions:
0 comments (0 inline, 0 general)
development.ini
Show inline comments
 
@@ -29,25 +29,24 @@ full_stack = true
 
static_files = true
 
lang=en
 
cache_dir = %(here)s/data
 
repos_name = etelko
 

	
 
################################################################################
 
## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT*  ##
 
## Debug mode will enable the interactive debugging tool, allowing ANYONE to  ##
 
## execute malicious code after an exception is raised.                       ##
 
################################################################################
 
#set debug = false
 

	
 

	
 
################################
 
### LOGGING CONFIGURATION   ####
 
################################
 
[loggers]
 
keys = root, routes, pylons_app, sqlalchemy
 

	
 
[handlers]
 
keys = console
 

	
 
[formatters]
 
keys = generic
 

	
 
@@ -82,14 +81,14 @@ qualname = sqlalchemy.engine
 
[handler_console]
 
class = StreamHandler
 
args = (sys.stderr,)
 
level = NOTSET
 
formatter = generic
 

	
 
################
 
## FORMATTERS ##
 
################
 

	
 
[formatter_generic]
 
format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
 
datefmt = %H:%M:%S
 
datefmt = %Y-%m-%d %H:%M:%S
 

	
production.ini
Show inline comments
 
@@ -17,25 +17,25 @@ debug = true
 
#smtp_username = 
 
#smtp_password = 
 
#error_message = 'mercurial crash !'
 

	
 
[server:main]
 
use = egg:Paste#http
 
host = 127.0.0.1
 
port = 8001
 

	
 
[app:main]
 
use = egg:pylons_app
 
full_stack = true
 
static_files = false
 
static_files = true
 
lang=en
 
cache_dir = %(here)s/data
 
repos_name = etelko
 

	
 
################################################################################
 
## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT*  ##
 
## Debug mode will enable the interactive debugging tool, allowing ANYONE to  ##
 
## execute malicious code after an exception is raised.                       ##
 
################################################################################
 
#set debug = false
 

	
 
################################
 
@@ -81,14 +81,14 @@ qualname = sqlalchemy.engine
 
[handler_console]
 
class = StreamHandler
 
args = (sys.stderr,)
 
level = NOTSET
 
formatter = generic
 

	
 
################
 
## FORMATTERS ##
 
################
 

	
 
[formatter_generic]
 
format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
 
datefmt = %H:%M:%S
 
datefmt = %Y-%m-%d %H:%M:%S
 

	
pylons_app/config/middleware.py
Show inline comments
 
@@ -43,25 +43,25 @@ def make_app(global_conf, full_stack=Tru
 
    app = RoutesMiddleware(app, config['routes.map'])
 
    app = SessionMiddleware(app, config)
 
    app = AuthBasicHandler(app, config['repos_name'] + ' mercurial repository', authfunc)
 
    
 
    if asbool(full_stack):
 
        # Handle Python exceptions
 
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
 

	
 
        # Display error documents for 401, 403, 404 status codes (and
 
        # 500 when debug is disabled)
 
        if asbool(config['debug']):
 
            #don't handle 404, since mercurial does it for us.
 
            app = StatusCodeRedirect(app, [400, 401, 403])
 
            app = StatusCodeRedirect(app, [400, 401, 403, 500])
 
        else:
 
            app = StatusCodeRedirect(app, [400, 401, 403, 500])
 
    
 
    # Establish the Registry for this application
 
    app = RegistryManager(app)
 

	
 
    if asbool(static_files):
 
        # Serve static files
 
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
 
        app = Cascade([static_app, app])
 
    
 
        app.config = config
pylons_app/controllers/admin.py
Show inline comments
 
@@ -21,26 +21,25 @@ class AdminController(BaseController):
 
        c.staticurl = g.statics
 
        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':
 
                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 {}
pylons_app/lib/auth.py
Show inline comments
 
@@ -4,24 +4,46 @@ import logging
 
from os.path import dirname as dn
 
from datetime import datetime
 
import crypt
 

	
 
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')
 

	
 
    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 and data[4]:
 
                log.info('user %s authenticated correctly', username)
 
                return True
 
        else:
 
            log.error('user %s is disabled', username)
 
            
 
    return False
 

	
 
def authfunc(environ, username, password):
 
    conn, cur = get_sqlite_conn_cur()
 
    password_crypt = crypt.crypt(password, '6a')
 

	
 
    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]:
 
@@ -56,53 +78,52 @@ def authfunc(environ, username, password
 
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
 
                        (id INTEGER PRIMARY KEY AUTOINCREMENT, 
 
                         username TEXT, 
 
                         password TEXT,
 
                         active INTEGER)''')
 
                         active INTEGER,
 
                         admin INTEGER)''')
 
        log.info('creating table %s', '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)''')
 
        conn.commit()
 
    except:
 
        conn.rollback()
 
        raise
 
    
 
    cur.close()
 
    
 
def create_user(username, password):
 
def create_user(username, password, admin=False):
 
    conn, cur = get_sqlite_conn_cur()    
 
    password_crypt = crypt.crypt(password, '6a')
 
    cur_date = datetime.now()
 
    log.info('creating user %s', username)
 
    try:
 
        cur.execute('''INSERT INTO users values (?,?,?,?) ''',
 
                    (None, username, password_crypt, 1,))     
 
        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')
 
    create_user('marcink', 'qweqwe', True)
 
    create_user('lukaszd', 'qweqwe')
 
    create_user('adriand', 'qweqwe')
 
    create_user('radek', 'qweqwe')
 
    create_user('skrzeka', 'qweqwe')
 
    create_user('bart', 'qweqwe')
 
    create_user('maho', 'qweqwe')
 
    create_user('michalg', 'qweqwe')
 
    create_user('admin', 'qwe123qwe')
 
    
 
    #authfunc('', 'marcink', 'qweqwe')
0 comments (0 inline, 0 general)