##// 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 static_files = true
29 static_files = true
30 lang=en
30 lang=en
31 cache_dir = %(here)s/data
31 cache_dir = %(here)s/data
32 repos_name = etelko
32
33
33 ################################################################################
34 ################################################################################
34 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
35 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
@@ -29,6 +29,7 b' full_stack = true'
29 static_files = false
29 static_files = false
30 lang=en
30 lang=en
31 cache_dir = %(here)s/data
31 cache_dir = %(here)s/data
32 repos_name = etelko
32
33
33 ################################################################################
34 ################################################################################
34 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
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 template_engine='mako', paths=paths)
28 template_engine='mako', paths=paths)
29
29
30 config['routes.map'] = make_map()
30 config['routes.map'] = make_map()
31 config['pylons.g'] = app_globals.Globals()
31 config['pylons.app_globals'] = app_globals.Globals()
32 config['pylons.h'] = pylons_app.lib.helpers
32 config['pylons.h'] = pylons_app.lib.helpers
33
33
34 # Create the Mako TemplateLookup, with the default auto-escaping
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 directories=paths['templates'],
36 directories=paths['templates'],
37 error_handler=handle_mako_error,
37 error_handler=handle_mako_error,
38 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
38 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
39 output_encoding='utf-8',
39 input_encoding='utf-8', default_filters=['escape'],
40 imports=['from webhelpers.html import escape'],
40 imports=['from webhelpers.html import escape'])
41 default_filters=['escape'])
42
41
43 # CONFIGURATION OPTIONS HERE (note: all config options will override
42 # CONFIGURATION OPTIONS HERE (note: all config options will override
44 # any Pylons config options)
43 # any Pylons config options)
@@ -8,9 +8,9 b' from pylons import config'
8 from pylons.middleware import ErrorHandler, StatusCodeRedirect
8 from pylons.middleware import ErrorHandler, StatusCodeRedirect
9 from pylons.wsgiapp import PylonsApp
9 from pylons.wsgiapp import PylonsApp
10 from routes.middleware import RoutesMiddleware
10 from routes.middleware import RoutesMiddleware
11
11 from paste.auth.basic import AuthBasicHandler
12 from pylons_app.config.environment import load_environment
12 from pylons_app.config.environment import load_environment
13
13 from pylons_app.lib.auth import authfunc
14
14
15 def make_app(global_conf, full_stack=True, **app_conf):
15 def make_app(global_conf, full_stack=True, **app_conf):
16 """Create a Pylons WSGI application and return it
16 """Create a Pylons WSGI application and return it
@@ -43,7 +43,8 b' def make_app(global_conf, full_stack=Tru'
43 app = RoutesMiddleware(app, config['routes.map'])
43 app = RoutesMiddleware(app, config['routes.map'])
44 app = SessionMiddleware(app, config)
44 app = SessionMiddleware(app, config)
45 app = CacheMiddleware(app, config)
45 app = CacheMiddleware(app, config)
46
46 app = AuthBasicHandler(app, config['repos_name'] + ' mercurial repository', authfunc)
47
47 if asbool(full_stack):
48 if asbool(full_stack):
48 # Handle Python exceptions
49 # Handle Python exceptions
49 app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
50 app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
@@ -55,7 +56,7 b' def make_app(global_conf, full_stack=Tru'
55 app = StatusCodeRedirect(app, [400, 401, 403, 500])
56 app = StatusCodeRedirect(app, [400, 401, 403, 500])
56 else:
57 else:
57 app = StatusCodeRedirect(app, [400, 401, 403, 500])
58 app = StatusCodeRedirect(app, [400, 401, 403, 500])
58
59
59 # Establish the Registry for this application
60 # Establish the Registry for this application
60 app = RegistryManager(app)
61 app = RegistryManager(app)
61
62
@@ -1,23 +1,22 b''
1 #!/usr/bin/python
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
2 # -*- coding: utf-8 -*-
3 import logging
3 import logging
4 import os
4 from pylons_app.lib.base import BaseController, render
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 from pylons_app.lib import helpers as h
7 from pylons_app.lib import helpers as h
7 from mako.template import Template
8 from mako.template import Template
8 from pprint import pprint
9 import os
10 from mercurial import ui, hg
9 from mercurial import ui, hg
11 from mercurial.error import RepoError
10 from mercurial.error import RepoError
12 from ConfigParser import ConfigParser
11 from ConfigParser import ConfigParser
13 import encodings
14 from pylons.controllers.util import abort
12 from pylons.controllers.util import abort
13
15 log = logging.getLogger(__name__)
14 log = logging.getLogger(__name__)
16
15
17 class HgController(BaseController):
16 class HgController(BaseController):
18
17
19 def __before__(self):
18 def __before__(self):
20 c.repos_prefix = 'etelko'
19 c.repos_prefix = config['repos_name']
21
20
22 def view(self, *args, **kwargs):
21 def view(self, *args, **kwargs):
23 response = g.hgapp(request.environ, self.start_response)
22 response = g.hgapp(request.environ, self.start_response)
@@ -33,14 +32,14 b' class HgController(BaseController):'
33 try:
32 try:
34 tmpl = u''.join(response)
33 tmpl = u''.join(response)
35 template = Template(tmpl, lookup=request.environ['pylons.pylons']\
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 except (RuntimeError, UnicodeDecodeError):
37 except (RuntimeError, UnicodeDecodeError):
39 log.info('disabling unicode due to encoding error')
38 log.info('disabling unicode due to encoding error')
40 response = g.hgapp(request.environ, self.start_response)
39 response = g.hgapp(request.environ, self.start_response)
41 tmpl = ''.join(response)
40 tmpl = ''.join(response)
42 template = Template(tmpl, lookup=request.environ['pylons.pylons']\
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 return template.render(g=g, c=c, session=session, h=h)
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