##// END OF EJS Templates
Added app basic auth....
Marcin Kuzminski -
r41:71ffa932 default
parent child Browse files
Show More
@@ -0,0 +1,105 b''
1 import sqlite3
2 import os
3 import logging
4 from os.path import dirname as dn
5 from datetime import datetime
6 import crypt
7
8 log = logging.getLogger(__name__)
9 ROOT = dn(dn(dn(os.path.realpath(__file__))))
10
11 def get_sqlite_cur_conn():
12 conn = sqlite3.connect(os.path.join(ROOT, 'auth.sqlite'))
13 cur = conn.cursor()
14 return conn, cur
15
16 def authfunc(environ, username, password):
17 conn, cur = get_sqlite_cur_conn()
18 password_crypt = crypt.crypt(password, '6a')
19
20 cur.execute("SELECT * FROM users WHERE username=?", (username,))
21 data = cur.fetchone()
22
23 if data:
24 if data[3]:
25 if data[1] == username and data[2] == password_crypt:
26 log.info('user %s authenticated correctly', username)
27
28 http_accept = environ.get('HTTP_ACCEPT')
29
30 if http_accept.startswith('application/mercurial') or \
31 environ['PATH_INFO'].find('raw-file') != -1:
32 cmd = environ['PATH_INFO']
33 for qry in environ['QUERY_STRING'].split('&'):
34 if qry.startswith('cmd'):
35 cmd += "|" + qry
36
37 try:
38 cur.execute('''INSERT INTO
39 user_logs
40 VALUES(?,?,?,?)''',
41 (None, data[0], cmd, datetime.now()))
42 conn.commit()
43 except Exception as e:
44 conn.rollback()
45 log.error(e)
46
47
48 return True
49 else:
50 log.error('user %s is disabled', username)
51
52 return False
53
54 def create_user_table():
55 '''
56 Create a auth database
57 '''
58 conn, cur = get_sqlite_cur_conn()
59 try:
60 log.info('creating table %s', 'users')
61 cur.execute('''DROP TABLE IF EXISTS users ''')
62 cur.execute('''CREATE TABLE users
63 (id INTEGER PRIMARY KEY AUTOINCREMENT,
64 username TEXT,
65 password TEXT,
66 active INTEGER)''')
67 log.info('creating table %s', 'user_logs')
68 cur.execute('''DROP TABLE IF EXISTS user_logs ''')
69 cur.execute('''CREATE TABLE user_logs
70 (id INTEGER PRIMARY KEY AUTOINCREMENT,
71 user_id INTEGER,
72 last_action TEXT,
73 last_action_date DATETIME)''')
74 conn.commit()
75 except:
76 conn.rollback()
77 raise
78
79 cur.close()
80
81 def create_user(username, password):
82 conn, cur = get_sqlite_cur_conn()
83 password_crypt = crypt.crypt(password, '6a')
84 cur_date = datetime.now()
85 log.info('creating user %s', username)
86 try:
87 cur.execute('''INSERT INTO users values (?,?,?,?) ''',
88 (None, username, password_crypt, 1,))
89 conn.commit()
90 except:
91 conn.rollback()
92 raise
93
94 if __name__ == "__main__":
95 create_user_table()
96 create_user('marcink', 'qweqwe')
97 create_user('lukaszd', 'qweqwe')
98 create_user('adriand', 'qweqwe')
99 create_user('radek', 'qweqwe')
100 create_user('skrzeka', 'qweqwe')
101 create_user('bart', 'qweqwe')
102 create_user('maho', 'qweqwe')
103 create_user('michalg', 'qweqwe')
104
105 #authfunc('', 'marcink', 'qweqwe')
@@ -29,6 +29,7 b' full_stack = true'
29 29 static_files = true
30 30 lang=en
31 31 cache_dir = %(here)s/data
32 repos_name = etelko
32 33
33 34 ################################################################################
34 35 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
@@ -29,6 +29,7 b' full_stack = true'
29 29 static_files = false
30 30 lang=en
31 31 cache_dir = %(here)s/data
32 repos_name = etelko
32 33
33 34 ################################################################################
34 35 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
@@ -28,17 +28,16 b' def load_environment(global_conf, app_co'
28 28 template_engine='mako', paths=paths)
29 29
30 30 config['routes.map'] = make_map()
31 config['pylons.g'] = app_globals.Globals()
31 config['pylons.app_globals'] = app_globals.Globals()
32 32 config['pylons.h'] = pylons_app.lib.helpers
33 33
34 34 # Create the Mako TemplateLookup, with the default auto-escaping
35 config['pylons.g'].mako_lookup = TemplateLookup(
35 config['pylons.app_globals'].mako_lookup = TemplateLookup(
36 36 directories=paths['templates'],
37 37 error_handler=handle_mako_error,
38 38 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
39 output_encoding='utf-8',
40 imports=['from webhelpers.html import escape'],
41 default_filters=['escape'])
39 input_encoding='utf-8', default_filters=['escape'],
40 imports=['from webhelpers.html import escape'])
42 41
43 42 # CONFIGURATION OPTIONS HERE (note: all config options will override
44 43 # any Pylons config options)
@@ -8,9 +8,9 b' from pylons import config'
8 8 from pylons.middleware import ErrorHandler, StatusCodeRedirect
9 9 from pylons.wsgiapp import PylonsApp
10 10 from routes.middleware import RoutesMiddleware
11
11 from paste.auth.basic import AuthBasicHandler
12 12 from pylons_app.config.environment import load_environment
13
13 from pylons_app.lib.auth import authfunc
14 14
15 15 def make_app(global_conf, full_stack=True, **app_conf):
16 16 """Create a Pylons WSGI application and return it
@@ -43,6 +43,7 b' def make_app(global_conf, full_stack=Tru'
43 43 app = RoutesMiddleware(app, config['routes.map'])
44 44 app = SessionMiddleware(app, config)
45 45 app = CacheMiddleware(app, config)
46 app = AuthBasicHandler(app, config['repos_name'] + ' mercurial repository', authfunc)
46 47
47 48 if asbool(full_stack):
48 49 # Handle Python exceptions
@@ -1,23 +1,22 b''
1 1 #!/usr/bin/python
2 2 # -*- coding: utf-8 -*-
3 3 import logging
4 import os
4 5 from pylons_app.lib.base import BaseController, render
5 from pylons import c, g, session, request
6 from pylons import tmpl_context as c, app_globals as g, session, request, config
6 7 from pylons_app.lib import helpers as h
7 8 from mako.template import Template
8 from pprint import pprint
9 import os
10 9 from mercurial import ui, hg
11 10 from mercurial.error import RepoError
12 11 from ConfigParser import ConfigParser
13 import encodings
14 12 from pylons.controllers.util import abort
13
15 14 log = logging.getLogger(__name__)
16 15
17 16 class HgController(BaseController):
18 17
19 18 def __before__(self):
20 c.repos_prefix = 'etelko'
19 c.repos_prefix = config['repos_name']
21 20
22 21 def view(self, *args, **kwargs):
23 22 response = g.hgapp(request.environ, self.start_response)
@@ -33,14 +32,14 b' class HgController(BaseController):'
33 32 try:
34 33 tmpl = u''.join(response)
35 34 template = Template(tmpl, lookup=request.environ['pylons.pylons']\
36 .config['pylons.g'].mako_lookup)
35 .config['pylons.app_globals'].mako_lookup)
37 36
38 37 except (RuntimeError, UnicodeDecodeError):
39 38 log.info('disabling unicode due to encoding error')
40 39 response = g.hgapp(request.environ, self.start_response)
41 40 tmpl = ''.join(response)
42 41 template = Template(tmpl, lookup=request.environ['pylons.pylons']\
43 .config['pylons.g'].mako_lookup, disable_unicode=True)
42 .config['pylons.app_globals'].mako_lookup, disable_unicode=True)
44 43
45 44
46 45 return template.render(g=g, c=c, session=session, h=h)
General Comments 0
You need to be logged in to leave comments. Login now