##// END OF EJS Templates
pep8ify middlewares
marcink -
r1275:27232762 beta
parent child Browse files
Show More
@@ -25,7 +25,9 b''
25
25
26 from rhodecode.lib import str2bool
26 from rhodecode.lib import str2bool
27
27
28
28 class HttpsFixup(object):
29 class HttpsFixup(object):
30
29 def __init__(self, app, config):
31 def __init__(self, app, config):
30 self.application = app
32 self.application = app
31 self.config = config
33 self.config = config
@@ -34,9 +36,9 b' class HttpsFixup(object):'
34 self.__fixup(environ)
36 self.__fixup(environ)
35 return self.application(environ, start_response)
37 return self.application(environ, start_response)
36
38
37
38 def __fixup(self, environ):
39 def __fixup(self, environ):
39 """Function to fixup the environ as needed. In order to use this
40 """
41 Function to fixup the environ as needed. In order to use this
40 middleware you should set this header inside your
42 middleware you should set this header inside your
41 proxy ie. nginx, apache etc.
43 proxy ie. nginx, apache etc.
42 """
44 """
@@ -30,12 +30,14 b' import traceback'
30
30
31 from dulwich import server as dulserver
31 from dulwich import server as dulserver
32
32
33
33 class SimpleGitUploadPackHandler(dulserver.UploadPackHandler):
34 class SimpleGitUploadPackHandler(dulserver.UploadPackHandler):
34
35
35 def handle(self):
36 def handle(self):
36 write = lambda x: self.proto.write_sideband(1, x)
37 write = lambda x: self.proto.write_sideband(1, x)
37
38
38 graph_walker = dulserver.ProtocolGraphWalker(self, self.repo.object_store,
39 graph_walker = dulserver.ProtocolGraphWalker(self,
40 self.repo.object_store,
39 self.repo.get_peeled)
41 self.repo.get_peeled)
40 objects_iter = self.repo.fetch_objects(
42 objects_iter = self.repo.fetch_objects(
41 graph_walker.determine_wants, graph_walker, self.progress,
43 graph_walker.determine_wants, graph_walker, self.progress,
@@ -46,8 +48,8 b' class SimpleGitUploadPackHandler(dulserv'
46 return
48 return
47
49
48 self.progress("counting objects: %d, done.\n" % len(objects_iter))
50 self.progress("counting objects: %d, done.\n" % len(objects_iter))
49 dulserver.write_pack_data(dulserver.ProtocolFile(None, write), objects_iter,
51 dulserver.write_pack_data(dulserver.ProtocolFile(None, write),
50 len(objects_iter))
52 objects_iter, len(objects_iter))
51 messages = []
53 messages = []
52 messages.append('thank you for using rhodecode')
54 messages.append('thank you for using rhodecode')
53
55
@@ -75,6 +77,7 b' from webob.exc import HTTPNotFound, HTTP'
75
77
76 log = logging.getLogger(__name__)
78 log = logging.getLogger(__name__)
77
79
80
78 def is_git(environ):
81 def is_git(environ):
79 """Returns True if request's target is git server.
82 """Returns True if request's target is git server.
80 ``HTTP_USER_AGENT`` would then have git client version given.
83 ``HTTP_USER_AGENT`` would then have git client version given.
@@ -86,6 +89,7 b' def is_git(environ):'
86 return True
89 return True
87 return False
90 return False
88
91
92
89 class SimpleGit(object):
93 class SimpleGit(object):
90
94
91 def __init__(self, application, config):
95 def __init__(self, application, config):
@@ -126,13 +130,14 b' class SimpleGit(object):'
126 if self.action in ['pull', 'push'] or self.action:
130 if self.action in ['pull', 'push'] or self.action:
127 anonymous_user = self.__get_user('default')
131 anonymous_user = self.__get_user('default')
128 self.username = anonymous_user.username
132 self.username = anonymous_user.username
129 anonymous_perm = self.__check_permission(self.action, anonymous_user ,
133 anonymous_perm = self.__check_permission(self.action,
134 anonymous_user,
130 self.repo_name)
135 self.repo_name)
131
136
132 if anonymous_perm is not True or anonymous_user.active is False:
137 if anonymous_perm is not True or anonymous_user.active is False:
133 if anonymous_perm is not True:
138 if anonymous_perm is not True:
134 log.debug('Not enough credentials to access this repository'
139 log.debug('Not enough credentials to access this '
135 'as anonymous user')
140 'repository as anonymous user')
136 if anonymous_user.active is False:
141 if anonymous_user.active is False:
137 log.debug('Anonymous access is disabled, running '
142 log.debug('Anonymous access is disabled, running '
138 'authentication')
143 'authentication')
@@ -142,7 +147,8 b' class SimpleGit(object):'
142 #==============================================================
147 #==============================================================
143
148
144 if not REMOTE_USER(environ):
149 if not REMOTE_USER(environ):
145 self.authenticate.realm = str(self.config['rhodecode_realm'])
150 self.authenticate.realm = str(
151 self.config['rhodecode_realm'])
146 result = self.authenticate(environ)
152 result = self.authenticate(environ)
147 if isinstance(result, str):
153 if isinstance(result, str):
148 AUTH_TYPE.update(environ, 'basic')
154 AUTH_TYPE.update(environ, 'basic')
@@ -150,7 +156,6 b' class SimpleGit(object):'
150 else:
156 else:
151 return result.wsgi_application(environ, start_response)
157 return result.wsgi_application(environ, start_response)
152
158
153
154 #==============================================================
159 #==============================================================
155 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME FROM
160 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME FROM
156 # BASIC AUTH
161 # BASIC AUTH
@@ -163,10 +168,12 b' class SimpleGit(object):'
163 self.username = user.username
168 self.username = user.username
164 except:
169 except:
165 log.error(traceback.format_exc())
170 log.error(traceback.format_exc())
166 return HTTPInternalServerError()(environ, start_response)
171 return HTTPInternalServerError()(environ,
172 start_response)
167
173
168 #check permissions for this repository
174 #check permissions for this repository
169 perm = self.__check_permission(self.action, user, self.repo_name)
175 perm = self.__check_permission(self.action, user,
176 self.repo_name)
170 if perm is not True:
177 if perm is not True:
171 print 'not allowed'
178 print 'not allowed'
172 return HTTPForbidden()(environ, start_response)
179 return HTTPForbidden()(environ, start_response)
@@ -199,9 +206,9 b' class SimpleGit(object):'
199 else:
206 else:
200 return app(environ, start_response)
207 return app(environ, start_response)
201
208
202
203 def __make_app(self):
209 def __make_app(self):
204 backend = dulserver.DictBackend({'/' + self.repo_name: Repo(self.repo_path)})
210 _d = {'/' + self.repo_name: Repo(self.repo_path)}
211 backend = dulserver.DictBackend(_d)
205 gitserve = HTTPGitApplication(backend)
212 gitserve = HTTPGitApplication(backend)
206
213
207 return gitserve
214 return gitserve
@@ -216,21 +223,20 b' class SimpleGit(object):'
216 """
223 """
217 if action == 'push':
224 if action == 'push':
218 if not HasPermissionAnyMiddleware('repository.write',
225 if not HasPermissionAnyMiddleware('repository.write',
219 'repository.admin')\
226 'repository.admin')(user,
220 (user, repo_name):
227 repo_name):
221 return False
228 return False
222
229
223 else:
230 else:
224 #any other action need at least read permission
231 #any other action need at least read permission
225 if not HasPermissionAnyMiddleware('repository.read',
232 if not HasPermissionAnyMiddleware('repository.read',
226 'repository.write',
233 'repository.write',
227 'repository.admin')\
234 'repository.admin')(user,
228 (user, repo_name):
235 repo_name):
229 return False
236 return False
230
237
231 return True
238 return True
232
239
233
234 def __get_repository(self, environ):
240 def __get_repository(self, environ):
235 """Get's repository name out of PATH_INFO header
241 """Get's repository name out of PATH_INFO header
236
242
@@ -246,7 +252,6 b' class SimpleGit(object):'
246 repo_name = repo_name.split('/')[0]
252 repo_name = repo_name.split('/')[0]
247 return repo_name
253 return repo_name
248
254
249
250 def __get_user(self, username):
255 def __get_user(self, username):
251 return UserModel().get_by_username(username, cache=True)
256 return UserModel().get_by_username(username, cache=True)
252
257
@@ -262,7 +267,8 b' class SimpleGit(object):'
262 'git-upload-pack': 'pull',
267 'git-upload-pack': 'pull',
263 }
268 }
264
269
265 return mapping.get(service_cmd, service_cmd if service_cmd else 'other')
270 return mapping.get(service_cmd,
271 service_cmd if service_cmd else 'other')
266 else:
272 else:
267 return 'other'
273 return 'other'
268
274
@@ -44,6 +44,7 b' from webob.exc import HTTPNotFound, HTTP'
44
44
45 log = logging.getLogger(__name__)
45 log = logging.getLogger(__name__)
46
46
47
47 def is_mercurial(environ):
48 def is_mercurial(environ):
48 """Returns True if request's target is mercurial server - header
49 """Returns True if request's target is mercurial server - header
49 ``HTTP_ACCEPT`` of such request would start with ``application/mercurial``.
50 ``HTTP_ACCEPT`` of such request would start with ``application/mercurial``.
@@ -53,6 +54,7 b' def is_mercurial(environ):'
53 return True
54 return True
54 return False
55 return False
55
56
57
56 class SimpleHg(object):
58 class SimpleHg(object):
57
59
58 def __init__(self, application, config):
60 def __init__(self, application, config):
@@ -93,13 +95,14 b' class SimpleHg(object):'
93 if self.action in ['pull', 'push']:
95 if self.action in ['pull', 'push']:
94 anonymous_user = self.__get_user('default')
96 anonymous_user = self.__get_user('default')
95 self.username = anonymous_user.username
97 self.username = anonymous_user.username
96 anonymous_perm = self.__check_permission(self.action, anonymous_user ,
98 anonymous_perm = self.__check_permission(self.action,
99 anonymous_user,
97 self.repo_name)
100 self.repo_name)
98
101
99 if anonymous_perm is not True or anonymous_user.active is False:
102 if anonymous_perm is not True or anonymous_user.active is False:
100 if anonymous_perm is not True:
103 if anonymous_perm is not True:
101 log.debug('Not enough credentials to access this repository'
104 log.debug('Not enough credentials to access this '
102 'as anonymous user')
105 'repository as anonymous user')
103 if anonymous_user.active is False:
106 if anonymous_user.active is False:
104 log.debug('Anonymous access is disabled, running '
107 log.debug('Anonymous access is disabled, running '
105 'authentication')
108 'authentication')
@@ -109,7 +112,8 b' class SimpleHg(object):'
109 #==============================================================
112 #==============================================================
110
113
111 if not REMOTE_USER(environ):
114 if not REMOTE_USER(environ):
112 self.authenticate.realm = str(self.config['rhodecode_realm'])
115 self.authenticate.realm = str(
116 self.config['rhodecode_realm'])
113 result = self.authenticate(environ)
117 result = self.authenticate(environ)
114 if isinstance(result, str):
118 if isinstance(result, str):
115 AUTH_TYPE.update(environ, 'basic')
119 AUTH_TYPE.update(environ, 'basic')
@@ -117,7 +121,6 b' class SimpleHg(object):'
117 else:
121 else:
118 return result.wsgi_application(environ, start_response)
122 return result.wsgi_application(environ, start_response)
119
123
120
121 #==============================================================
124 #==============================================================
122 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME FROM
125 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME FROM
123 # BASIC AUTH
126 # BASIC AUTH
@@ -130,10 +133,12 b' class SimpleHg(object):'
130 self.username = user.username
133 self.username = user.username
131 except:
134 except:
132 log.error(traceback.format_exc())
135 log.error(traceback.format_exc())
133 return HTTPInternalServerError()(environ, start_response)
136 return HTTPInternalServerError()(environ,
137 start_response)
134
138
135 #check permissions for this repository
139 #check permissions for this repository
136 perm = self.__check_permission(self.action, user, self.repo_name)
140 perm = self.__check_permission(self.action, user,
141 self.repo_name)
137 if perm is not True:
142 if perm is not True:
138 return HTTPForbidden()(environ, start_response)
143 return HTTPForbidden()(environ, start_response)
139
144
@@ -142,9 +147,9 b' class SimpleHg(object):'
142 'action':self.action,
147 'action': self.action,
143 'repository':self.repo_name}
148 'repository': self.repo_name}
144
149
145 #===================================================================
150 #======================================================================
146 # MERCURIAL REQUEST HANDLING
151 # MERCURIAL REQUEST HANDLING
147 #===================================================================
152 #======================================================================
148 environ['PATH_INFO'] = '/'#since we wrap into hgweb, reset the path
153 environ['PATH_INFO'] = '/' # since we wrap into hgweb, reset the path
149 self.baseui = make_ui('db')
154 self.baseui = make_ui('db')
150 self.basepath = self.config['base_path']
155 self.basepath = self.config['base_path']
@@ -168,7 +173,6 b' class SimpleHg(object):'
168
173
169 return app(environ, start_response)
174 return app(environ, start_response)
170
175
171
172 def __make_app(self):
176 def __make_app(self):
173 """Make an wsgi application using hgweb, and my generated baseui
177 """Make an wsgi application using hgweb, and my generated baseui
174 instance
178 instance
@@ -177,7 +181,6 b' class SimpleHg(object):'
177 hgserve = hgweb(str(self.repo_path), baseui=self.baseui)
181 hgserve = hgweb(str(self.repo_path), baseui=self.baseui)
178 return self.__load_web_settings(hgserve, self.extras)
182 return self.__load_web_settings(hgserve, self.extras)
179
183
180
181 def __check_permission(self, action, user, repo_name):
184 def __check_permission(self, action, user, repo_name):
182 """Checks permissions using action (push/pull) user and repository
185 """Checks permissions using action (push/pull) user and repository
183 name
186 name
@@ -188,21 +191,20 b' class SimpleHg(object):'
188 """
191 """
189 if action == 'push':
192 if action == 'push':
190 if not HasPermissionAnyMiddleware('repository.write',
193 if not HasPermissionAnyMiddleware('repository.write',
191 'repository.admin')\
194 'repository.admin')(user,
192 (user, repo_name):
195 repo_name):
193 return False
196 return False
194
197
195 else:
198 else:
196 #any other action need at least read permission
199 #any other action need at least read permission
197 if not HasPermissionAnyMiddleware('repository.read',
200 if not HasPermissionAnyMiddleware('repository.read',
198 'repository.write',
201 'repository.write',
199 'repository.admin')\
202 'repository.admin')(user,
200 (user, repo_name):
203 repo_name):
201 return False
204 return False
202
205
203 return True
206 return True
204
207
205
206 def __get_repository(self, environ):
208 def __get_repository(self, environ):
207 """Get's repository name out of PATH_INFO header
209 """Get's repository name out of PATH_INFO header
208
210
@@ -236,7 +238,7 b' class SimpleHg(object):'
236 for qry in environ['QUERY_STRING'].split('&'):
238 for qry in environ['QUERY_STRING'].split('&'):
237 if qry.startswith('cmd'):
239 if qry.startswith('cmd'):
238 cmd = qry.split('=')[-1]
240 cmd = qry.split('=')[-1]
239 if mapping.has_key(cmd):
241 if cmd in mapping:
240 return mapping[cmd]
242 return mapping[cmd]
241 else:
243 else:
242 return 'pull'
244 return 'pull'
@@ -247,7 +249,6 b' class SimpleHg(object):'
247 push requests"""
249 push requests"""
248 invalidate_cache('get_repo_cached_%s' % repo_name)
250 invalidate_cache('get_repo_cached_%s' % repo_name)
249
251
250
251 def __load_web_settings(self, hgserve, extras={}):
252 def __load_web_settings(self, hgserve, extras={}):
252 #set the global ui for hgserve instance passed
253 #set the global ui for hgserve instance passed
253 hgserve.repo.ui = self.baseui
254 hgserve.repo.ui = self.baseui
General Comments 0
You need to be logged in to leave comments. Login now