##// END OF EJS Templates
Static files for production fixed...
Marcin Kuzminski -
r46:9db77827 default
parent child Browse files
Show More
@@ -1,95 +1,94 b''
1 ################################################################################
1 ################################################################################
2 ################################################################################
2 ################################################################################
3 # pylons_app - Pylons environment configuration #
3 # pylons_app - Pylons environment configuration #
4 # #
4 # #
5 # The %(here)s variable will be replaced with the parent directory of this file#
5 # The %(here)s variable will be replaced with the parent directory of this file#
6 ################################################################################
6 ################################################################################
7
7
8 [DEFAULT]
8 [DEFAULT]
9 debug = true
9 debug = true
10 ############################################
10 ############################################
11 ## Uncomment and replace with the address ##
11 ## Uncomment and replace with the address ##
12 ## which should receive any error reports ##
12 ## which should receive any error reports ##
13 ############################################
13 ############################################
14 #email_to = marcin.kuzminski@etelko.pl
14 #email_to = marcin.kuzminski@etelko.pl
15 #smtp_server = mail.etelko.pl
15 #smtp_server = mail.etelko.pl
16 #error_email_from = paste_error@localhost
16 #error_email_from = paste_error@localhost
17 #smtp_username =
17 #smtp_username =
18 #smtp_password =
18 #smtp_password =
19 #error_message = 'mercurial crash !'
19 #error_message = 'mercurial crash !'
20
20
21 [server:main]
21 [server:main]
22 use = egg:Paste#http
22 use = egg:Paste#http
23 host = 127.0.0.1
23 host = 127.0.0.1
24 port = 5000
24 port = 5000
25
25
26 [app:main]
26 [app:main]
27 use = egg:pylons_app
27 use = egg:pylons_app
28 full_stack = true
28 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 repos_name = etelko
33
33
34 ################################################################################
34 ################################################################################
35 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
35 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
36 ## Debug mode will enable the interactive debugging tool, allowing ANYONE to ##
36 ## Debug mode will enable the interactive debugging tool, allowing ANYONE to ##
37 ## execute malicious code after an exception is raised. ##
37 ## execute malicious code after an exception is raised. ##
38 ################################################################################
38 ################################################################################
39 #set debug = false
39 #set debug = false
40
40
41
42 ################################
41 ################################
43 ### LOGGING CONFIGURATION ####
42 ### LOGGING CONFIGURATION ####
44 ################################
43 ################################
45 [loggers]
44 [loggers]
46 keys = root, routes, pylons_app, sqlalchemy
45 keys = root, routes, pylons_app, sqlalchemy
47
46
48 [handlers]
47 [handlers]
49 keys = console
48 keys = console
50
49
51 [formatters]
50 [formatters]
52 keys = generic
51 keys = generic
53
52
54 #############
53 #############
55 ## LOGGERS ##
54 ## LOGGERS ##
56 #############
55 #############
57 [logger_root]
56 [logger_root]
58 level = NOTSET
57 level = NOTSET
59 handlers = console
58 handlers = console
60
59
61 [logger_routes]
60 [logger_routes]
62 level = INFO
61 level = INFO
63 handlers = console
62 handlers = console
64 qualname = routes.middleware
63 qualname = routes.middleware
65 # "level = DEBUG" logs the route matched and routing variables.
64 # "level = DEBUG" logs the route matched and routing variables.
66
65
67 [logger_pylons_app]
66 [logger_pylons_app]
68 level = DEBUG
67 level = DEBUG
69 handlers = console
68 handlers = console
70 qualname = pylons_app
69 qualname = pylons_app
71
70
72
71
73 [logger_sqlalchemy]
72 [logger_sqlalchemy]
74 level = DEBUG
73 level = DEBUG
75 handlers = console
74 handlers = console
76 qualname = sqlalchemy.engine
75 qualname = sqlalchemy.engine
77
76
78 ##############
77 ##############
79 ## HANDLERS ##
78 ## HANDLERS ##
80 ##############
79 ##############
81
80
82 [handler_console]
81 [handler_console]
83 class = StreamHandler
82 class = StreamHandler
84 args = (sys.stderr,)
83 args = (sys.stderr,)
85 level = NOTSET
84 level = NOTSET
86 formatter = generic
85 formatter = generic
87
86
88 ################
87 ################
89 ## FORMATTERS ##
88 ## FORMATTERS ##
90 ################
89 ################
91
90
92 [formatter_generic]
91 [formatter_generic]
93 format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
92 format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
94 datefmt = %H:%M:%S
93 datefmt = %Y-%m-%d %H:%M:%S
95
94
@@ -1,94 +1,94 b''
1 ################################################################################
1 ################################################################################
2 ################################################################################
2 ################################################################################
3 # pylons_app - Pylons environment configuration #
3 # pylons_app - Pylons environment configuration #
4 # #
4 # #
5 # The %(here)s variable will be replaced with the parent directory of this file#
5 # The %(here)s variable will be replaced with the parent directory of this file#
6 ################################################################################
6 ################################################################################
7
7
8 [DEFAULT]
8 [DEFAULT]
9 debug = true
9 debug = true
10 ############################################
10 ############################################
11 ## Uncomment and replace with the address ##
11 ## Uncomment and replace with the address ##
12 ## which should receive any error reports ##
12 ## which should receive any error reports ##
13 ############################################
13 ############################################
14 #email_to = marcin.kuzminski@etelko.pl
14 #email_to = marcin.kuzminski@etelko.pl
15 #smtp_server = mail.etelko.pl
15 #smtp_server = mail.etelko.pl
16 #error_email_from = paste_error@localhost
16 #error_email_from = paste_error@localhost
17 #smtp_username =
17 #smtp_username =
18 #smtp_password =
18 #smtp_password =
19 #error_message = 'mercurial crash !'
19 #error_message = 'mercurial crash !'
20
20
21 [server:main]
21 [server:main]
22 use = egg:Paste#http
22 use = egg:Paste#http
23 host = 127.0.0.1
23 host = 127.0.0.1
24 port = 8001
24 port = 8001
25
25
26 [app:main]
26 [app:main]
27 use = egg:pylons_app
27 use = egg:pylons_app
28 full_stack = true
28 full_stack = true
29 static_files = false
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 repos_name = etelko
33
33
34 ################################################################################
34 ################################################################################
35 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
35 ## WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* ##
36 ## Debug mode will enable the interactive debugging tool, allowing ANYONE to ##
36 ## Debug mode will enable the interactive debugging tool, allowing ANYONE to ##
37 ## execute malicious code after an exception is raised. ##
37 ## execute malicious code after an exception is raised. ##
38 ################################################################################
38 ################################################################################
39 #set debug = false
39 #set debug = false
40
40
41 ################################
41 ################################
42 ### LOGGING CONFIGURATION ####
42 ### LOGGING CONFIGURATION ####
43 ################################
43 ################################
44 [loggers]
44 [loggers]
45 keys = root, routes, pylons_app, sqlalchemy
45 keys = root, routes, pylons_app, sqlalchemy
46
46
47 [handlers]
47 [handlers]
48 keys = console
48 keys = console
49
49
50 [formatters]
50 [formatters]
51 keys = generic
51 keys = generic
52
52
53 #############
53 #############
54 ## LOGGERS ##
54 ## LOGGERS ##
55 #############
55 #############
56 [logger_root]
56 [logger_root]
57 level = INFO
57 level = INFO
58 handlers = console
58 handlers = console
59
59
60 [logger_routes]
60 [logger_routes]
61 level = INFO
61 level = INFO
62 handlers = console
62 handlers = console
63 qualname = routes.middleware
63 qualname = routes.middleware
64 # "level = DEBUG" logs the route matched and routing variables.
64 # "level = DEBUG" logs the route matched and routing variables.
65
65
66 [logger_pylons_app]
66 [logger_pylons_app]
67 level = DEBUG
67 level = DEBUG
68 handlers = console
68 handlers = console
69 qualname = pylons_app
69 qualname = pylons_app
70
70
71
71
72 [logger_sqlalchemy]
72 [logger_sqlalchemy]
73 level = DEBUG
73 level = DEBUG
74 handlers = console
74 handlers = console
75 qualname = sqlalchemy.engine
75 qualname = sqlalchemy.engine
76
76
77 ##############
77 ##############
78 ## HANDLERS ##
78 ## HANDLERS ##
79 ##############
79 ##############
80
80
81 [handler_console]
81 [handler_console]
82 class = StreamHandler
82 class = StreamHandler
83 args = (sys.stderr,)
83 args = (sys.stderr,)
84 level = NOTSET
84 level = NOTSET
85 formatter = generic
85 formatter = generic
86
86
87 ################
87 ################
88 ## FORMATTERS ##
88 ## FORMATTERS ##
89 ################
89 ################
90
90
91 [formatter_generic]
91 [formatter_generic]
92 format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
92 format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
93 datefmt = %H:%M:%S
93 datefmt = %Y-%m-%d %H:%M:%S
94
94
@@ -1,70 +1,70 b''
1 """Pylons middleware initialization"""
1 """Pylons middleware initialization"""
2 from beaker.middleware import SessionMiddleware
2 from beaker.middleware import SessionMiddleware
3 from paste.cascade import Cascade
3 from paste.cascade import Cascade
4 from paste.registry import RegistryManager
4 from paste.registry import RegistryManager
5 from paste.urlparser import StaticURLParser
5 from paste.urlparser import StaticURLParser
6 from paste.deploy.converters import asbool
6 from paste.deploy.converters import asbool
7 from pylons.middleware import ErrorHandler, StatusCodeRedirect
7 from pylons.middleware import ErrorHandler, StatusCodeRedirect
8 from pylons.wsgiapp import PylonsApp
8 from pylons.wsgiapp import PylonsApp
9 from routes.middleware import RoutesMiddleware
9 from routes.middleware import RoutesMiddleware
10 from paste.auth.basic import AuthBasicHandler
10 from paste.auth.basic import AuthBasicHandler
11 from pylons_app.config.environment import load_environment
11 from pylons_app.config.environment import load_environment
12 from pylons_app.lib.auth import authfunc
12 from pylons_app.lib.auth import authfunc
13
13
14 def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
14 def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
15 """Create a Pylons WSGI application and return it
15 """Create a Pylons WSGI application and return it
16
16
17 ``global_conf``
17 ``global_conf``
18 The inherited configuration for this application. Normally from
18 The inherited configuration for this application. Normally from
19 the [DEFAULT] section of the Paste ini file.
19 the [DEFAULT] section of the Paste ini file.
20
20
21 ``full_stack``
21 ``full_stack``
22 Whether or not this application provides a full WSGI stack (by
22 Whether or not this application provides a full WSGI stack (by
23 default, meaning it handles its own exceptions and errors).
23 default, meaning it handles its own exceptions and errors).
24 Disable full_stack when this application is "managed" by
24 Disable full_stack when this application is "managed" by
25 another WSGI middleware.
25 another WSGI middleware.
26
26
27 ``app_conf``
27 ``app_conf``
28 The application's local configuration. Normally specified in
28 The application's local configuration. Normally specified in
29 the [app:<name>] section of the Paste ini file (where <name>
29 the [app:<name>] section of the Paste ini file (where <name>
30 defaults to main).
30 defaults to main).
31
31
32 """
32 """
33 # Configure the Pylons environment
33 # Configure the Pylons environment
34 config = load_environment(global_conf, app_conf)
34 config = load_environment(global_conf, app_conf)
35
35
36
36
37 # The Pylons WSGI app
37 # The Pylons WSGI app
38 app = PylonsApp(config=config)
38 app = PylonsApp(config=config)
39
39
40 # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
40 # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
41
41
42 # Routing/Session/Cache Middleware
42 # Routing/Session/Cache Middleware
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 = AuthBasicHandler(app, config['repos_name'] + ' mercurial repository', authfunc)
45 app = AuthBasicHandler(app, config['repos_name'] + ' mercurial repository', authfunc)
46
46
47 if asbool(full_stack):
47 if asbool(full_stack):
48 # Handle Python exceptions
48 # Handle Python exceptions
49 app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
49 app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
50
50
51 # Display error documents for 401, 403, 404 status codes (and
51 # Display error documents for 401, 403, 404 status codes (and
52 # 500 when debug is disabled)
52 # 500 when debug is disabled)
53 if asbool(config['debug']):
53 if asbool(config['debug']):
54 #don't handle 404, since mercurial does it for us.
54 #don't handle 404, since mercurial does it for us.
55 app = StatusCodeRedirect(app, [400, 401, 403])
55 app = StatusCodeRedirect(app, [400, 401, 403, 500])
56 else:
56 else:
57 app = StatusCodeRedirect(app, [400, 401, 403, 500])
57 app = StatusCodeRedirect(app, [400, 401, 403, 500])
58
58
59 # Establish the Registry for this application
59 # Establish the Registry for this application
60 app = RegistryManager(app)
60 app = RegistryManager(app)
61
61
62 if asbool(static_files):
62 if asbool(static_files):
63 # Serve static files
63 # Serve static files
64 static_app = StaticURLParser(config['pylons.paths']['static_files'])
64 static_app = StaticURLParser(config['pylons.paths']['static_files'])
65 app = Cascade([static_app, app])
65 app = Cascade([static_app, app])
66
66
67 app.config = config
67 app.config = config
68
68
69 return app
69 return app
70
70
@@ -1,128 +1,127 b''
1 import logging
1 import logging
2
2
3 from pylons import request, response, session, tmpl_context as c, url, app_globals as g
3 from pylons import request, response, session, tmpl_context as c, url, app_globals as g
4 from pylons.controllers.util import abort, redirect
4 from pylons.controllers.util import abort, redirect
5
5
6 from pylons_app.lib.base import BaseController, render
6 from pylons_app.lib.base import BaseController, render
7 import os
7 import os
8 from mercurial import ui, hg
8 from mercurial import ui, hg
9 from mercurial.error import RepoError
9 from mercurial.error import RepoError
10 from ConfigParser import ConfigParser
10 from ConfigParser import ConfigParser
11 from pylons_app.lib import auth
11 from pylons_app.lib import auth
12 from pylons_app.model.forms import LoginForm
12 from pylons_app.model.forms import LoginForm
13 import formencode
13 import formencode
14 import formencode.htmlfill as htmlfill
14 import formencode.htmlfill as htmlfill
15 log = logging.getLogger(__name__)
15 log = logging.getLogger(__name__)
16
16
17 class AdminController(BaseController):
17 class AdminController(BaseController):
18
18
19
19
20 def __before__(self):
20 def __before__(self):
21 c.staticurl = g.statics
21 c.staticurl = g.statics
22 c.admin_user = session.get('admin_user')
22 c.admin_user = session.get('admin_user')
23 c.admin_username = session.get('admin_username')
23 c.admin_username = session.get('admin_username')
24
24
25 def index(self):
25 def index(self):
26 # Return a rendered template
26 # Return a rendered template
27 if request.POST:
27 if request.POST:
28 #import Login Form validator class
28 #import Login Form validator class
29 login_form = LoginForm()
29 login_form = LoginForm()
30
30
31 try:
31 try:
32 c.form_result = login_form.to_python(dict(request.params))
32 c.form_result = login_form.to_python(dict(request.params))
33 if auth.authfunc(None, c.form_result['username'], c.form_result['password']) and\
33 if auth.admin_auth(c.form_result['username'], c.form_result['password']):
34 c.form_result['username'] == 'admin':
35 session['admin_user'] = True
34 session['admin_user'] = True
36 session['admin_username'] = c.form_result['username']
35 session['admin_username'] = c.form_result['username']
37 session.save()
36 session.save()
38 return redirect(url('admin_home'))
37 return redirect(url('admin_home'))
39 else:
38 else:
40 raise formencode.Invalid('Login Error', None, None,
39 raise formencode.Invalid('Login Error', None, None,
41 error_dict={'username':'invalid login',
40 error_dict={'username':'invalid login',
42 'password':'invalid password'})
41 'password':'invalid password'})
43
42
44 except formencode.Invalid, error:
43 except formencode.Invalid, error:
45 c.form_result = error.value
44 c.form_result = error.value
46 c.form_errors = error.error_dict or {}
45 c.form_errors = error.error_dict or {}
47 html = render('/admin.html')
46 html = render('/admin.html')
48
47
49 return htmlfill.render(
48 return htmlfill.render(
50 html,
49 html,
51 defaults=c.form_result,
50 defaults=c.form_result,
52 encoding="UTF-8"
51 encoding="UTF-8"
53 )
52 )
54 return render('/admin.html')
53 return render('/admin.html')
55
54
56 def repos_manage(self):
55 def repos_manage(self):
57 return render('/repos_manage.html')
56 return render('/repos_manage.html')
58
57
59 def users_manage(self):
58 def users_manage(self):
60 conn, cur = auth.get_sqlite_conn_cur()
59 conn, cur = auth.get_sqlite_conn_cur()
61 cur.execute('SELECT * FROM users')
60 cur.execute('SELECT * FROM users')
62 c.users_list = cur.fetchall()
61 c.users_list = cur.fetchall()
63 return render('/users_manage.html')
62 return render('/users_manage.html')
64
63
65 def manage_hgrc(self):
64 def manage_hgrc(self):
66 pass
65 pass
67
66
68 def hgrc(self, dirname):
67 def hgrc(self, dirname):
69 filename = os.path.join(dirname, '.hg', 'hgrc')
68 filename = os.path.join(dirname, '.hg', 'hgrc')
70 return filename
69 return filename
71
70
72 def add_repo(self, new_repo):
71 def add_repo(self, new_repo):
73
72
74
73
75 #extra check it can be add since it's the command
74 #extra check it can be add since it's the command
76 if new_repo == '_admin':
75 if new_repo == '_admin':
77 c.msg = 'DENIED'
76 c.msg = 'DENIED'
78 c.new_repo = ''
77 c.new_repo = ''
79 return render('add.html')
78 return render('add.html')
80
79
81 new_repo = new_repo.replace(" ", "_")
80 new_repo = new_repo.replace(" ", "_")
82 new_repo = new_repo.replace("-", "_")
81 new_repo = new_repo.replace("-", "_")
83
82
84 try:
83 try:
85 self._create_repo(new_repo)
84 self._create_repo(new_repo)
86 c.new_repo = new_repo
85 c.new_repo = new_repo
87 c.msg = 'added repo'
86 c.msg = 'added repo'
88 except Exception as e:
87 except Exception as e:
89 c.new_repo = 'Exception when adding: %s' % new_repo
88 c.new_repo = 'Exception when adding: %s' % new_repo
90 c.msg = str(e)
89 c.msg = str(e)
91
90
92 return render('add.html')
91 return render('add.html')
93
92
94 def _check_repo(self, repo_name):
93 def _check_repo(self, repo_name):
95 p = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
94 p = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
96 config_path = os.path.join(p, 'hgwebdir.config')
95 config_path = os.path.join(p, 'hgwebdir.config')
97
96
98 cp = ConfigParser()
97 cp = ConfigParser()
99
98
100 cp.read(config_path)
99 cp.read(config_path)
101 repos_path = cp.get('paths', '/').replace("**", '')
100 repos_path = cp.get('paths', '/').replace("**", '')
102
101
103 if not repos_path:
102 if not repos_path:
104 raise Exception('Could not read config !')
103 raise Exception('Could not read config !')
105
104
106 self.repo_path = os.path.join(repos_path, repo_name)
105 self.repo_path = os.path.join(repos_path, repo_name)
107
106
108 try:
107 try:
109 r = hg.repository(ui.ui(), self.repo_path)
108 r = hg.repository(ui.ui(), self.repo_path)
110 hg.verify(r)
109 hg.verify(r)
111 #here we hnow that repo exists it was verified
110 #here we hnow that repo exists it was verified
112 log.info('%s repo is already created', repo_name)
111 log.info('%s repo is already created', repo_name)
113 raise Exception('Repo exists')
112 raise Exception('Repo exists')
114 except RepoError:
113 except RepoError:
115 log.info('%s repo is free for creation', repo_name)
114 log.info('%s repo is free for creation', repo_name)
116 #it means that there is no valid repo there...
115 #it means that there is no valid repo there...
117 return True
116 return True
118
117
119
118
120 def _create_repo(self, repo_name):
119 def _create_repo(self, repo_name):
121 if repo_name in [None, '', 'add']:
120 if repo_name in [None, '', 'add']:
122 raise Exception('undefined repo_name of repo')
121 raise Exception('undefined repo_name of repo')
123
122
124 if self._check_repo(repo_name):
123 if self._check_repo(repo_name):
125 log.info('creating repo %s in %s', repo_name, self.repo_path)
124 log.info('creating repo %s in %s', repo_name, self.repo_path)
126 cmd = """mkdir %s && hg init %s""" \
125 cmd = """mkdir %s && hg init %s""" \
127 % (self.repo_path, self.repo_path)
126 % (self.repo_path, self.repo_path)
128 os.popen(cmd)
127 os.popen(cmd)
@@ -1,108 +1,129 b''
1 import sqlite3
1 import sqlite3
2 import os
2 import os
3 import logging
3 import logging
4 from os.path import dirname as dn
4 from os.path import dirname as dn
5 from datetime import datetime
5 from datetime import datetime
6 import crypt
6 import crypt
7
7
8 log = logging.getLogger(__name__)
8 log = logging.getLogger(__name__)
9 ROOT = dn(dn(dn(os.path.realpath(__file__))))
9 ROOT = dn(dn(dn(os.path.realpath(__file__))))
10
10
11 def get_sqlite_conn_cur():
11 def get_sqlite_conn_cur():
12 conn = sqlite3.connect(os.path.join(ROOT, 'auth.sqlite'))
12 conn = sqlite3.connect(os.path.join(ROOT, 'auth.sqlite'))
13 cur = conn.cursor()
13 cur = conn.cursor()
14 return conn, cur
14 return conn, cur
15
15
16
17 def admin_auth(username, password):
18 conn, cur = get_sqlite_conn_cur()
19 password_crypt = crypt.crypt(password, '6a')
20
21 try:
22 cur.execute("SELECT * FROM users WHERE username=?", (username,))
23 data = cur.fetchone()
24 except sqlite3.OperationalError as e:
25 data = None
26 log.error(e)
27
28 if data:
29 if data[3]:
30 if data[1] == username and data[2] == password_crypt and data[4]:
31 log.info('user %s authenticated correctly', username)
32 return True
33 else:
34 log.error('user %s is disabled', username)
35
36 return False
37
16 def authfunc(environ, username, password):
38 def authfunc(environ, username, password):
17 conn, cur = get_sqlite_conn_cur()
39 conn, cur = get_sqlite_conn_cur()
18 password_crypt = crypt.crypt(password, '6a')
40 password_crypt = crypt.crypt(password, '6a')
19
41
20 try:
42 try:
21 cur.execute("SELECT * FROM users WHERE username=?", (username,))
43 cur.execute("SELECT * FROM users WHERE username=?", (username,))
22 data = cur.fetchone()
44 data = cur.fetchone()
23 except sqlite3.OperationalError as e:
45 except sqlite3.OperationalError as e:
24 data = None
46 data = None
25 log.error(e)
47 log.error(e)
26 if data:
48 if data:
27 if data[3]:
49 if data[3]:
28 if data[1] == username and data[2] == password_crypt:
50 if data[1] == username and data[2] == password_crypt:
29 log.info('user %s authenticated correctly', username)
51 log.info('user %s authenticated correctly', username)
30 if environ:
52 if environ:
31 http_accept = environ.get('HTTP_ACCEPT')
53 http_accept = environ.get('HTTP_ACCEPT')
32
54
33 if http_accept.startswith('application/mercurial') or \
55 if http_accept.startswith('application/mercurial') or \
34 environ['PATH_INFO'].find('raw-file') != -1:
56 environ['PATH_INFO'].find('raw-file') != -1:
35 cmd = environ['PATH_INFO']
57 cmd = environ['PATH_INFO']
36 for qry in environ['QUERY_STRING'].split('&'):
58 for qry in environ['QUERY_STRING'].split('&'):
37 if qry.startswith('cmd'):
59 if qry.startswith('cmd'):
38 cmd += "|" + qry
60 cmd += "|" + qry
39
61
40 try:
62 try:
41 cur.execute('''INSERT INTO
63 cur.execute('''INSERT INTO
42 user_logs
64 user_logs
43 VALUES(?,?,?,?)''',
65 VALUES(?,?,?,?)''',
44 (None, data[0], cmd, datetime.now()))
66 (None, data[0], cmd, datetime.now()))
45 conn.commit()
67 conn.commit()
46 except Exception as e:
68 except Exception as e:
47 conn.rollback()
69 conn.rollback()
48 log.error(e)
70 log.error(e)
49
71
50 return True
72 return True
51 else:
73 else:
52 log.error('user %s is disabled', username)
74 log.error('user %s is disabled', username)
53
75
54 return False
76 return False
55
77
56 def create_user_table():
78 def create_user_table():
57 '''
79 '''
58 Create a auth database
80 Create a auth database
59 '''
81 '''
60 conn, cur = get_sqlite_conn_cur()
82 conn, cur = get_sqlite_conn_cur()
61 try:
83 try:
62 log.info('creating table %s', 'users')
84 log.info('creating table %s', 'users')
63 cur.execute('''DROP TABLE IF EXISTS users ''')
85 cur.execute('''DROP TABLE IF EXISTS users ''')
64 cur.execute('''CREATE TABLE users
86 cur.execute('''CREATE TABLE users
65 (id INTEGER PRIMARY KEY AUTOINCREMENT,
87 (id INTEGER PRIMARY KEY AUTOINCREMENT,
66 username TEXT,
88 username TEXT,
67 password TEXT,
89 password TEXT,
68 active INTEGER)''')
90 active INTEGER,
91 admin INTEGER)''')
69 log.info('creating table %s', 'user_logs')
92 log.info('creating table %s', 'user_logs')
70 cur.execute('''DROP TABLE IF EXISTS user_logs ''')
93 cur.execute('''DROP TABLE IF EXISTS user_logs ''')
71 cur.execute('''CREATE TABLE user_logs
94 cur.execute('''CREATE TABLE user_logs
72 (id INTEGER PRIMARY KEY AUTOINCREMENT,
95 (id INTEGER PRIMARY KEY AUTOINCREMENT,
73 user_id INTEGER,
96 user_id INTEGER,
74 last_action TEXT,
97 last_action TEXT,
75 last_action_date DATETIME)''')
98 last_action_date DATETIME)''')
76 conn.commit()
99 conn.commit()
77 except:
100 except:
78 conn.rollback()
101 conn.rollback()
79 raise
102 raise
80
103
81 cur.close()
104 cur.close()
82
105
83 def create_user(username, password):
106 def create_user(username, password, admin=False):
84 conn, cur = get_sqlite_conn_cur()
107 conn, cur = get_sqlite_conn_cur()
85 password_crypt = crypt.crypt(password, '6a')
108 password_crypt = crypt.crypt(password, '6a')
86 cur_date = datetime.now()
87 log.info('creating user %s', username)
109 log.info('creating user %s', username)
88 try:
110 try:
89 cur.execute('''INSERT INTO users values (?,?,?,?) ''',
111 cur.execute('''INSERT INTO users values (?,?,?,?,?) ''',
90 (None, username, password_crypt, 1,))
112 (None, username, password_crypt, 1, admin))
91 conn.commit()
113 conn.commit()
92 except:
114 except:
93 conn.rollback()
115 conn.rollback()
94 raise
116 raise
95
117
96 if __name__ == "__main__":
118 if __name__ == "__main__":
97 create_user_table()
119 create_user_table()
98 create_user('marcink', 'qweqwe')
120 create_user('marcink', 'qweqwe', True)
99 create_user('lukaszd', 'qweqwe')
121 create_user('lukaszd', 'qweqwe')
100 create_user('adriand', 'qweqwe')
122 create_user('adriand', 'qweqwe')
101 create_user('radek', 'qweqwe')
123 create_user('radek', 'qweqwe')
102 create_user('skrzeka', 'qweqwe')
124 create_user('skrzeka', 'qweqwe')
103 create_user('bart', 'qweqwe')
125 create_user('bart', 'qweqwe')
104 create_user('maho', 'qweqwe')
126 create_user('maho', 'qweqwe')
105 create_user('michalg', 'qweqwe')
127 create_user('michalg', 'qweqwe')
106 create_user('admin', 'qwe123qwe')
107
128
108 #authfunc('', 'marcink', 'qweqwe')
129 #authfunc('', 'marcink', 'qweqwe')
General Comments 0
You need to be logged in to leave comments. Login now