##// END OF EJS Templates
Moved check_repo function to utils, error controller check for first name in url, for this repo and only prints 404 make repo template if repo does not exists, moded check repo from admin
marcink -
r125:2811259d default
parent child Browse files
Show More
@@ -1,127 +1,100 b''
1 1 import logging
2 2
3 3 from pylons import request, response, session, tmpl_context as c, url, app_globals as g
4 4 from pylons.controllers.util import abort, redirect
5 5
6 6 from pylons_app.lib.base import BaseController, render
7 7 import os
8 from mercurial import ui, hg
9 from mercurial.error import RepoError
10 from ConfigParser import ConfigParser
11 8 from pylons_app.lib import auth
12 9 from pylons_app.model.forms import LoginForm
13 10 import formencode
14 11 import formencode.htmlfill as htmlfill
15 12 from pylons_app.model import meta
16 13 from pylons_app.model.db import Users, UserLogs
17 14 from webhelpers.paginate import Page
15 from pylons_app.lib.utils import check_repo
18 16 log = logging.getLogger(__name__)
19 17
20 18 class AdminController(BaseController):
21 19
22 20 def __before__(self):
23 21
24 22 c.admin_user = session.get('admin_user', False)
25 23 c.admin_username = session.get('admin_username')
26 24
27 25 def index(self):
28 26 # Return a rendered template
29 27 if request.POST:
30 28 #import Login Form validator class
31 29 login_form = LoginForm()
32 30
33 31 try:
34 32 c.form_result = login_form.to_python(dict(request.params))
35 33 if auth.admin_auth(c.form_result['username'], c.form_result['password']):
36 34 session['admin_user'] = True
37 35 session['admin_username'] = c.form_result['username']
38 36 session.save()
39 37 return redirect(url('admin_home'))
40 38 else:
41 39 raise formencode.Invalid('Login Error', None, None,
42 40 error_dict={'username':'invalid login',
43 41 'password':'invalid password'})
44 42
45 43 except formencode.Invalid, error:
46 44 c.form_result = error.value
47 45 c.form_errors = error.error_dict or {}
48 46 html = render('/admin.html')
49 47
50 48 return htmlfill.render(
51 49 html,
52 50 defaults=c.form_result,
53 51 encoding="UTF-8"
54 52 )
55 53 if c.admin_user:
56 54 sa = meta.Session
57 55
58 56 users_log = sa.query(UserLogs)\
59 57 .order_by(UserLogs.action_date.desc())
60 58 p = int(request.params.get('page', 1))
61 59 c.users_log = Page(users_log, page=p, items_per_page=10)
62 60 c.log_data = render('admin_log.html')
63 61 if request.params.get('partial'):
64 62 return c.log_data
65 63 return render('/admin.html')
66 64
67 65 def hgrc(self, dirname):
68 66 filename = os.path.join(dirname, '.hg', 'hgrc')
69 67 return filename
70 68
71 69 def add_repo(self, new_repo):
72 70
73 71
74 72 #extra check it can be add since it's the command
75 73 if new_repo == '_admin':
76 74 c.msg = 'DENIED'
77 75 c.new_repo = ''
78 76 return render('add.html')
79 77
80 78 new_repo = new_repo.replace(" ", "_")
81 79 new_repo = new_repo.replace("-", "_")
82 80
83 81 try:
84 82 self._create_repo(new_repo)
85 83 c.new_repo = new_repo
86 84 c.msg = 'added repo'
87 85 except Exception as e:
88 86 c.new_repo = 'Exception when adding: %s' % new_repo
89 87 c.msg = str(e)
90 88
91 89 return render('add.html')
92 90
93 def _check_repo(self, repo_name):
94 p = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
95 config_path = os.path.join(p, 'hgwebdir.config')
96
97 cp = ConfigParser()
98
99 cp.read(config_path)
100 repos_path = cp.get('paths', '/').replace("**", '')
101
102 if not repos_path:
103 raise Exception('Could not read config !')
104
105 self.repo_path = os.path.join(repos_path, repo_name)
106
107 try:
108 r = hg.repository(ui.ui(), self.repo_path)
109 hg.verify(r)
110 #here we hnow that repo exists it was verified
111 log.info('%s repo is already created', repo_name)
112 raise Exception('Repo exists')
113 except RepoError:
114 log.info('%s repo is free for creation', repo_name)
115 #it means that there is no valid repo there...
116 return True
117
118 91
119 92 def _create_repo(self, repo_name):
120 93 if repo_name in [None, '', 'add']:
121 94 raise Exception('undefined repo_name of repo')
122 95
123 if self._check_repo(repo_name):
96 if check_repo(repo_name, g.base_path):
124 97 log.info('creating repo %s in %s', repo_name, self.repo_path)
125 98 cmd = """mkdir %s && hg init %s""" \
126 99 % (self.repo_path, self.repo_path)
127 100 os.popen(cmd)
@@ -1,88 +1,90 b''
1 1 import logging
2 from paste.urlparser import PkgResourcesParser
2 import cgi
3 import os
3 4 import paste.fileapp
4 5 from pylons import tmpl_context as c, app_globals as g, request, config
5 6 from pylons.controllers.util import forward
6 7 from pylons.i18n.translation import _
7 8 from pylons_app.lib.base import BaseController, render
8 from pylons.middleware import error_document_template, media_path
9 import cgi
10 import os
9 from pylons.middleware import media_path
10 from pylons_app.lib.utils import check_repo
11 11
12 12 log = logging.getLogger(__name__)
13 13 class ErrorController(BaseController):
14 14 """
15 15 Generates error documents as and when they are required.
16 16
17 17 The ErrorDocuments middleware forwards to ErrorController when error
18 18 related status codes are returned from the application.
19 19
20 20 This behaviour can be altered by changing the parameters to the
21 21 ErrorDocuments middleware in your config/middleware.py file.
22 22 """
23 23 #
24 24 def __before__(self):
25 25 c.repos_prefix = config['repos_name']
26 26
27 27 c.repo_name = request.environ['pylons.original_request']\
28 .environ.get('PATH_INFO').split('/')[-1]
28 .environ.get('PATH_INFO').split('/')[1]
29 29
30 30 def document(self):
31 31 resp = request.environ.get('pylons.original_response')
32 32 log.debug(resp.status)
33 33
34 34 e = request.environ
35 35 c.serv_p = r'%(protocol)s://%(host)s/' % {
36 36 'protocol': e.get('wsgi.url_scheme'),
37 37 'host':e.get('HTTP_HOST'),
38 38 }
39
39
40
40 41 if resp.status_int == 404:
41 return render('/errors/error_404.html')
42 if check_repo(c.repo_name, g.base_path):
43 return render('/errors/error_404.html')
42 44
43 45 c.error_message = cgi.escape(request.GET.get('code', str(resp.status)))
44 46 c.error_explanation = self.get_error_explanation(resp.status_int)
45 47
46 48 #redirect to when error with given seconds
47 49 c.redirect_time = 0
48 50 c.redirect_module = _('Home page')# name to what your going to be redirected
49 51 c.url_redirect = "/"
50 52
51 53 return render('/errors/error_document.html')
52 54
53 55
54 56 def img(self, id):
55 57 """Serve Pylons' stock images"""
56 58 return self._serve_file(os.path.join(media_path, 'img', id))
57 59
58 60 def style(self, id):
59 61 """Serve Pylons' stock stylesheets"""
60 62 return self._serve_file(os.path.join(media_path, 'style', id))
61 63
62 64 def _serve_file(self, path):
63 65 """Call Paste's FileApp (a WSGI application) to serve the file
64 66 at the specified path
65 67 """
66 68 fapp = paste.fileapp.FileApp(path)
67 69 return fapp(request.environ, self.start_response)
68 70
69 71 def get_error_explanation(self, code):
70 72 ''' get the error explanations of int codes
71 73 [400, 401, 403, 404, 500]'''
72 74 try:
73 75 code = int(code)
74 76 except:
75 77 code = 500
76 78
77 79 if code == 400:
78 80 return _('The request could not be understood by the server due to malformed syntax.')
79 81 if code == 401:
80 82 return _('Unathorized access to resource')
81 83 if code == 403:
82 84 return _("You don't have permission to view this page")
83 85 if code == 404:
84 86 return _('The resource could not be found')
85 87 if code == 500:
86 88 return _('The server encountered an unexpected condition which prevented it from fulfilling the request.')
87 89
88 90
@@ -1,75 +1,94 b''
1 from mercurial import ui, config
2 1 import os
3 2 import logging
4
3 from mercurial import ui, config, hg
4 from mercurial.error import RepoError
5 log = logging.getLogger(__name__)
6
7
5 8 def get_repo_slug(request):
6 9 path_info = request.environ.get('PATH_INFO')
7 10 uri_lst = path_info.split('/')
8 11 repo_name = uri_lst[1]
9 12 return repo_name
10 13
11 14 def is_mercurial(environ):
12 15 """
13 16 Returns True if request's target is mercurial server - header
14 17 ``HTTP_ACCEPT`` of such request would start with ``application/mercurial``.
15 18 """
16 19 http_accept = environ.get('HTTP_ACCEPT')
17 20 if http_accept and http_accept.startswith('application/mercurial'):
18 21 return True
19 22 return False
20 23
21 24 def check_repo_dir(paths):
22 25 repos_path = paths[0][1].split('/')
23 26 if repos_path[-1] in ['*', '**']:
24 27 repos_path = repos_path[:-1]
25 28 if repos_path[0] != '/':
26 29 repos_path[0] = '/'
27 30 if not os.path.isdir(os.path.join(*repos_path)):
28 31 raise Exception('Not a valid repository in %s' % paths[0][1])
29
32
33 def check_repo(repo_name, base_path):
34
35 repo_path = os.path.join(base_path, repo_name)
36
37 try:
38 r = hg.repository(ui.ui(), repo_path)
39 hg.verify(r)
40 #here we hnow that repo exists it was verified
41 log.info('%s repo is already created', repo_name)
42 return False
43 #raise Exception('Repo exists')
44 except RepoError:
45 log.info('%s repo is free for creation', repo_name)
46 #it means that there is no valid repo there...
47 return True
48
30 49 def make_ui(path='hgwebdir.config', checkpaths=True):
31 50 """
32 51 A funcion that will read python rc files and make an ui from read options
33 52
34 53 @param path: path to mercurial config file
35 54 """
36 55 if not os.path.isfile(path):
37 logging.error('Unable to read config file %s' % path)
56 log.error('Unable to read config file %s' % path)
38 57 return False
39 58 #propagated from mercurial documentation
40 59 sections = [
41 60 'alias',
42 61 'auth',
43 62 'decode/encode',
44 63 'defaults',
45 64 'diff',
46 65 'email',
47 66 'extensions',
48 67 'format',
49 68 'merge-patterns',
50 69 'merge-tools',
51 70 'hooks',
52 71 'http_proxy',
53 72 'smtp',
54 73 'patch',
55 74 'paths',
56 75 'profiling',
57 76 'server',
58 77 'trusted',
59 78 'ui',
60 79 'web',
61 80 ]
62 81
63 82 baseui = ui.ui()
64 83 cfg = config.config()
65 84 cfg.read(path)
66 85 if checkpaths:check_repo_dir(cfg.items('paths'))
67 86
68 87 for section in sections:
69 88 for k, v in cfg.items(section):
70 89 baseui.setconfig(section, k, v)
71 90
72 91 return baseui
73 92
74 93
75 94
General Comments 0
You need to be logged in to leave comments. Login now