##// END OF EJS Templates
added clone_uri to API method for creating users
marcink -
r2006:34d009e5 beta
parent child Browse files
Show More
@@ -1,625 +1,626 b''
1 .. _api:
1 .. _api:
2
2
3
3
4 API
4 API
5 ===
5 ===
6
6
7
7
8 Starting from RhodeCode version 1.2 a simple API was implemented.
8 Starting from RhodeCode version 1.2 a simple API was implemented.
9 There's a single schema for calling all api methods. API is implemented
9 There's a single schema for calling all api methods. API is implemented
10 with JSON protocol both ways. An url to send API request in RhodeCode is
10 with JSON protocol both ways. An url to send API request in RhodeCode is
11 <your_server>/_admin/api
11 <your_server>/_admin/api
12
12
13 API ACCESS FOR WEB VIEWS
13 API ACCESS FOR WEB VIEWS
14 ++++++++++++++++++++++++
14 ++++++++++++++++++++++++
15
15
16 API access can also be turned on for each web view in RhodeCode that is
16 API access can also be turned on for each web view in RhodeCode that is
17 decorated with `@LoginRequired` decorator. To enable API access simple change
17 decorated with `@LoginRequired` decorator. To enable API access simple change
18 the standard login decorator to `@LoginRequired(api_access=True)`.
18 the standard login decorator to `@LoginRequired(api_access=True)`.
19 After this change, a rhodecode view can be accessed without login by adding a
19 After this change, a rhodecode view can be accessed without login by adding a
20 GET parameter `?api_key=<api_key>` to url. By default this is only
20 GET parameter `?api_key=<api_key>` to url. By default this is only
21 enabled on RSS/ATOM feed views.
21 enabled on RSS/ATOM feed views.
22
22
23
23
24 API ACCESS
24 API ACCESS
25 ++++++++++
25 ++++++++++
26
26
27 All clients are required to send JSON-RPC spec JSON data::
27 All clients are required to send JSON-RPC spec JSON data::
28
28
29 {
29 {
30 "id:<id>,
30 "id:<id>,
31 "api_key":"<api_key>",
31 "api_key":"<api_key>",
32 "method":"<method_name>",
32 "method":"<method_name>",
33 "args":{"<arg_key>":"<arg_val>"}
33 "args":{"<arg_key>":"<arg_val>"}
34 }
34 }
35
35
36 Example call for autopulling remotes repos using curl::
36 Example call for autopulling remotes repos using curl::
37 curl https://server.com/_admin/api -X POST -H 'content-type:text/plain' --data-binary '{"id":1,"api_key":"xe7cdb2v278e4evbdf5vs04v832v0efvcbcve4a3","method":"pull","args":{"repo":"CPython"}}'
37 curl https://server.com/_admin/api -X POST -H 'content-type:text/plain' --data-binary '{"id":1,"api_key":"xe7cdb2v278e4evbdf5vs04v832v0efvcbcve4a3","method":"pull","args":{"repo":"CPython"}}'
38
38
39 Simply provide
39 Simply provide
40 - *id* A value of any type, which is used to match the response with the request that it is replying to.
40 - *id* A value of any type, which is used to match the response with the request that it is replying to.
41 - *api_key* for access and permission validation.
41 - *api_key* for access and permission validation.
42 - *method* is name of method to call
42 - *method* is name of method to call
43 - *args* is an key:value list of arguments to pass to method
43 - *args* is an key:value list of arguments to pass to method
44
44
45 .. note::
45 .. note::
46
46
47 api_key can be found in your user account page
47 api_key can be found in your user account page
48
48
49
49
50 RhodeCode API will return always a JSON-RPC response::
50 RhodeCode API will return always a JSON-RPC response::
51
51
52 {
52 {
53 "id":<id>,
53 "id":<id>,
54 "result": "<result>",
54 "result": "<result>",
55 "error": null
55 "error": null
56 }
56 }
57
57
58 All responses from API will be `HTTP/1.0 200 OK`, if there's an error while
58 All responses from API will be `HTTP/1.0 200 OK`, if there's an error while
59 calling api *error* key from response will contain failure description
59 calling api *error* key from response will contain failure description
60 and result will be null.
60 and result will be null.
61
61
62 API METHODS
62 API METHODS
63 +++++++++++
63 +++++++++++
64
64
65
65
66 pull
66 pull
67 ----
67 ----
68
68
69 Pulls given repo from remote location. Can be used to automatically keep
69 Pulls given repo from remote location. Can be used to automatically keep
70 remote repos up to date. This command can be executed only using api_key
70 remote repos up to date. This command can be executed only using api_key
71 belonging to user with admin rights
71 belonging to user with admin rights
72
72
73 INPUT::
73 INPUT::
74
74
75 api_key : "<api_key>"
75 api_key : "<api_key>"
76 method : "pull"
76 method : "pull"
77 args : {
77 args : {
78 "repo_name" : "<reponame>"
78 "repo_name" : "<reponame>"
79 }
79 }
80
80
81 OUTPUT::
81 OUTPUT::
82
82
83 result : "Pulled from <reponame>"
83 result : "Pulled from <reponame>"
84 error : null
84 error : null
85
85
86
86
87 get_user
87 get_user
88 --------
88 --------
89
89
90 Get's an user by username, Returns empty result if user is not found.
90 Get's an user by username, Returns empty result if user is not found.
91 This command can be executed only using api_key belonging to user with admin
91 This command can be executed only using api_key belonging to user with admin
92 rights.
92 rights.
93
93
94
94
95 INPUT::
95 INPUT::
96
96
97 api_key : "<api_key>"
97 api_key : "<api_key>"
98 method : "get_user"
98 method : "get_user"
99 args : {
99 args : {
100 "username" : "<username>"
100 "username" : "<username>"
101 }
101 }
102
102
103 OUTPUT::
103 OUTPUT::
104
104
105 result: None if user does not exist or
105 result: None if user does not exist or
106 {
106 {
107 "id" : "<id>",
107 "id" : "<id>",
108 "username" : "<username>",
108 "username" : "<username>",
109 "firstname": "<firstname>",
109 "firstname": "<firstname>",
110 "lastname" : "<lastname>",
110 "lastname" : "<lastname>",
111 "email" : "<email>",
111 "email" : "<email>",
112 "active" : "<bool>",
112 "active" : "<bool>",
113 "admin" :Β  "<bool>",
113 "admin" :Β  "<bool>",
114 "ldap" : "<ldap_dn>"
114 "ldap" : "<ldap_dn>"
115 }
115 }
116
116
117 error: null
117 error: null
118
118
119
119
120 get_users
120 get_users
121 ---------
121 ---------
122
122
123 Lists all existing users. This command can be executed only using api_key
123 Lists all existing users. This command can be executed only using api_key
124 belonging to user with admin rights.
124 belonging to user with admin rights.
125
125
126
126
127 INPUT::
127 INPUT::
128
128
129 api_key : "<api_key>"
129 api_key : "<api_key>"
130 method : "get_users"
130 method : "get_users"
131 args : { }
131 args : { }
132
132
133 OUTPUT::
133 OUTPUT::
134
134
135 result: [
135 result: [
136 {
136 {
137 "id" : "<id>",
137 "id" : "<id>",
138 "username" : "<username>",
138 "username" : "<username>",
139 "firstname": "<firstname>",
139 "firstname": "<firstname>",
140 "lastname" : "<lastname>",
140 "lastname" : "<lastname>",
141 "email" : "<email>",
141 "email" : "<email>",
142 "active" : "<bool>",
142 "active" : "<bool>",
143 "admin" :Β  "<bool>",
143 "admin" :Β  "<bool>",
144 "ldap" : "<ldap_dn>"
144 "ldap" : "<ldap_dn>"
145 },
145 },
146 …
146 …
147 ]
147 ]
148 error: null
148 error: null
149
149
150
150
151 create_user
151 create_user
152 -----------
152 -----------
153
153
154 Creates new user. This command can
154 Creates new user. This command can
155 be executed only using api_key belonging to user with admin rights.
155 be executed only using api_key belonging to user with admin rights.
156
156
157
157
158 INPUT::
158 INPUT::
159
159
160 api_key : "<api_key>"
160 api_key : "<api_key>"
161 method : "create_user"
161 method : "create_user"
162 args : {
162 args : {
163 "username" : "<username>",
163 "username" : "<username>",
164 "password" : "<password>",
164 "password" : "<password>",
165 "email" : "<useremail>",
165 "email" : "<useremail>",
166 "firstname" : "<firstname> = None",
166 "firstname" : "<firstname> = None",
167 "lastname" : "<lastname> = None",
167 "lastname" : "<lastname> = None",
168 "active" : "<bool> = True",
168 "active" : "<bool> = True",
169 "admin" : "<bool> = False",
169 "admin" : "<bool> = False",
170 "ldap_dn" : "<ldap_dn> = None"
170 "ldap_dn" : "<ldap_dn> = None"
171 }
171 }
172
172
173 OUTPUT::
173 OUTPUT::
174
174
175 result: {
175 result: {
176 "id" : "<new_user_id>",
176 "id" : "<new_user_id>",
177 "msg" : "created new user <username>"
177 "msg" : "created new user <username>"
178 }
178 }
179 error: null
179 error: null
180
180
181
181
182 update_user
182 update_user
183 -----------
183 -----------
184
184
185 updates current one if such user exists. This command can
185 updates current one if such user exists. This command can
186 be executed only using api_key belonging to user with admin rights.
186 be executed only using api_key belonging to user with admin rights.
187
187
188
188
189 INPUT::
189 INPUT::
190
190
191 api_key : "<api_key>"
191 api_key : "<api_key>"
192 method : "update_user"
192 method : "update_user"
193 args : {
193 args : {
194 "username" : "<username>",
194 "username" : "<username>",
195 "password" : "<password>",
195 "password" : "<password>",
196 "email" : "<useremail>",
196 "email" : "<useremail>",
197 "firstname" : "<firstname> = None",
197 "firstname" : "<firstname> = None",
198 "lastname" : "<lastname> = None",
198 "lastname" : "<lastname> = None",
199 "active" : "<bool> = True",
199 "active" : "<bool> = True",
200 "admin" : "<bool> = False",
200 "admin" : "<bool> = False",
201 "ldap_dn" : "<ldap_dn> = None"
201 "ldap_dn" : "<ldap_dn> = None"
202 }
202 }
203
203
204 OUTPUT::
204 OUTPUT::
205
205
206 result: {
206 result: {
207 "id" : "<edited_user_id>",
207 "id" : "<edited_user_id>",
208 "msg" : "updated user <username>"
208 "msg" : "updated user <username>"
209 }
209 }
210 error: null
210 error: null
211
211
212
212
213 get_users_group
213 get_users_group
214 ---------------
214 ---------------
215
215
216 Gets an existing users group. This command can be executed only using api_key
216 Gets an existing users group. This command can be executed only using api_key
217 belonging to user with admin rights.
217 belonging to user with admin rights.
218
218
219
219
220 INPUT::
220 INPUT::
221
221
222 api_key : "<api_key>"
222 api_key : "<api_key>"
223 method : "get_users_group"
223 method : "get_users_group"
224 args : {
224 args : {
225 "group_name" : "<name>"
225 "group_name" : "<name>"
226 }
226 }
227
227
228 OUTPUT::
228 OUTPUT::
229
229
230 result : None if group not exist
230 result : None if group not exist
231 {
231 {
232 "id" : "<id>",
232 "id" : "<id>",
233 "group_name" : "<groupname>",
233 "group_name" : "<groupname>",
234 "active": "<bool>",
234 "active": "<bool>",
235 "members" : [
235 "members" : [
236 { "id" : "<userid>",
236 { "id" : "<userid>",
237 "username" : "<username>",
237 "username" : "<username>",
238 "firstname": "<firstname>",
238 "firstname": "<firstname>",
239 "lastname" : "<lastname>",
239 "lastname" : "<lastname>",
240 "email" : "<email>",
240 "email" : "<email>",
241 "active" : "<bool>",
241 "active" : "<bool>",
242 "admin" :Β  "<bool>",
242 "admin" :Β  "<bool>",
243 "ldap" : "<ldap_dn>"
243 "ldap" : "<ldap_dn>"
244 },
244 },
245 …
245 …
246 ]
246 ]
247 }
247 }
248 error : null
248 error : null
249
249
250
250
251 get_users_groups
251 get_users_groups
252 ----------------
252 ----------------
253
253
254 Lists all existing users groups. This command can be executed only using
254 Lists all existing users groups. This command can be executed only using
255 api_key belonging to user with admin rights.
255 api_key belonging to user with admin rights.
256
256
257
257
258 INPUT::
258 INPUT::
259
259
260 api_key : "<api_key>"
260 api_key : "<api_key>"
261 method : "get_users_groups"
261 method : "get_users_groups"
262 args : { }
262 args : { }
263
263
264 OUTPUT::
264 OUTPUT::
265
265
266 result : [
266 result : [
267 {
267 {
268 "id" : "<id>",
268 "id" : "<id>",
269 "group_name" : "<groupname>",
269 "group_name" : "<groupname>",
270 "active": "<bool>",
270 "active": "<bool>",
271 "members" : [
271 "members" : [
272 {
272 {
273 "id" : "<userid>",
273 "id" : "<userid>",
274 "username" : "<username>",
274 "username" : "<username>",
275 "firstname": "<firstname>",
275 "firstname": "<firstname>",
276 "lastname" : "<lastname>",
276 "lastname" : "<lastname>",
277 "email" : "<email>",
277 "email" : "<email>",
278 "active" : "<bool>",
278 "active" : "<bool>",
279 "admin" :Β  "<bool>",
279 "admin" :Β  "<bool>",
280 "ldap" : "<ldap_dn>"
280 "ldap" : "<ldap_dn>"
281 },
281 },
282 …
282 …
283 ]
283 ]
284 }
284 }
285 ]
285 ]
286 error : null
286 error : null
287
287
288
288
289 create_users_group
289 create_users_group
290 ------------------
290 ------------------
291
291
292 Creates new users group. This command can be executed only using api_key
292 Creates new users group. This command can be executed only using api_key
293 belonging to user with admin rights
293 belonging to user with admin rights
294
294
295
295
296 INPUT::
296 INPUT::
297
297
298 api_key : "<api_key>"
298 api_key : "<api_key>"
299 method : "create_users_group"
299 method : "create_users_group"
300 args: {
300 args: {
301 "group_name": "<groupname>",
301 "group_name": "<groupname>",
302 "active":"<bool> = True"
302 "active":"<bool> = True"
303 }
303 }
304
304
305 OUTPUT::
305 OUTPUT::
306
306
307 result: {
307 result: {
308 "id": "<newusersgroupid>",
308 "id": "<newusersgroupid>",
309 "msg": "created new users group <groupname>"
309 "msg": "created new users group <groupname>"
310 }
310 }
311 error: null
311 error: null
312
312
313
313
314 add_user_to_users_group
314 add_user_to_users_group
315 -----------------------
315 -----------------------
316
316
317 Adds a user to a users group. If user exists in that group success will be
317 Adds a user to a users group. If user exists in that group success will be
318 `false`. This command can be executed only using api_key
318 `false`. This command can be executed only using api_key
319 belonging to user with admin rights
319 belonging to user with admin rights
320
320
321
321
322 INPUT::
322 INPUT::
323
323
324 api_key : "<api_key>"
324 api_key : "<api_key>"
325 method : "add_user_users_group"
325 method : "add_user_users_group"
326 args: {
326 args: {
327 "group_name" : "<groupname>",
327 "group_name" : "<groupname>",
328 "username" : "<username>"
328 "username" : "<username>"
329 }
329 }
330
330
331 OUTPUT::
331 OUTPUT::
332
332
333 result: {
333 result: {
334 "id": "<newusersgroupmemberid>",
334 "id": "<newusersgroupmemberid>",
335 "success": True|False # depends on if member is in group
335 "success": True|False # depends on if member is in group
336 "msg": "added member <username> to users group <groupname> |
336 "msg": "added member <username> to users group <groupname> |
337 User is already in that group"
337 User is already in that group"
338 }
338 }
339 error: null
339 error: null
340
340
341
341
342 remove_user_from_users_group
342 remove_user_from_users_group
343 ----------------------------
343 ----------------------------
344
344
345 Removes a user from a users group. If user is not in given group success will
345 Removes a user from a users group. If user is not in given group success will
346 be `false`. This command can be executed only
346 be `false`. This command can be executed only
347 using api_key belonging to user with admin rights
347 using api_key belonging to user with admin rights
348
348
349
349
350 INPUT::
350 INPUT::
351
351
352 api_key : "<api_key>"
352 api_key : "<api_key>"
353 method : "remove_user_from_users_group"
353 method : "remove_user_from_users_group"
354 args: {
354 args: {
355 "group_name" : "<groupname>",
355 "group_name" : "<groupname>",
356 "username" : "<username>"
356 "username" : "<username>"
357 }
357 }
358
358
359 OUTPUT::
359 OUTPUT::
360
360
361 result: {
361 result: {
362 "success": True|False, # depends on if member is in group
362 "success": True|False, # depends on if member is in group
363 "msg": "removed member <username> from users group <groupname> |
363 "msg": "removed member <username> from users group <groupname> |
364 User wasn't in group"
364 User wasn't in group"
365 }
365 }
366 error: null
366 error: null
367
367
368
368
369 get_repo
369 get_repo
370 --------
370 --------
371
371
372 Gets an existing repository. This command can be executed only using api_key
372 Gets an existing repository. This command can be executed only using api_key
373 belonging to user with admin rights
373 belonging to user with admin rights
374
374
375
375
376 INPUT::
376 INPUT::
377
377
378 api_key : "<api_key>"
378 api_key : "<api_key>"
379 method : "get_repo"
379 method : "get_repo"
380 args: {
380 args: {
381 "repo_name" : "<reponame>"
381 "repo_name" : "<reponame>"
382 }
382 }
383
383
384 OUTPUT::
384 OUTPUT::
385
385
386 result: None if repository does not exist or
386 result: None if repository does not exist or
387 {
387 {
388 "id" : "<id>",
388 "id" : "<id>",
389 "repo_name" : "<reponame>"
389 "repo_name" : "<reponame>"
390 "type" : "<type>",
390 "type" : "<type>",
391 "description" : "<description>",
391 "description" : "<description>",
392 "members" : [
392 "members" : [
393 { "id" : "<userid>",
393 { "id" : "<userid>",
394 "username" : "<username>",
394 "username" : "<username>",
395 "firstname": "<firstname>",
395 "firstname": "<firstname>",
396 "lastname" : "<lastname>",
396 "lastname" : "<lastname>",
397 "email" : "<email>",
397 "email" : "<email>",
398 "active" : "<bool>",
398 "active" : "<bool>",
399 "admin" :Β  "<bool>",
399 "admin" :Β  "<bool>",
400 "ldap" : "<ldap_dn>",
400 "ldap" : "<ldap_dn>",
401 "permission" : "repository.(read|write|admin)"
401 "permission" : "repository.(read|write|admin)"
402 },
402 },
403 …
403 …
404 {
404 {
405 "id" : "<usersgroupid>",
405 "id" : "<usersgroupid>",
406 "name" : "<usersgroupname>",
406 "name" : "<usersgroupname>",
407 "active": "<bool>",
407 "active": "<bool>",
408 "permission" : "repository.(read|write|admin)"
408 "permission" : "repository.(read|write|admin)"
409 },
409 },
410 …
410 …
411 ]
411 ]
412 }
412 }
413 error: null
413 error: null
414
414
415
415
416 get_repos
416 get_repos
417 ---------
417 ---------
418
418
419 Lists all existing repositories. This command can be executed only using api_key
419 Lists all existing repositories. This command can be executed only using api_key
420 belonging to user with admin rights
420 belonging to user with admin rights
421
421
422
422
423 INPUT::
423 INPUT::
424
424
425 api_key : "<api_key>"
425 api_key : "<api_key>"
426 method : "get_repos"
426 method : "get_repos"
427 args: { }
427 args: { }
428
428
429 OUTPUT::
429 OUTPUT::
430
430
431 result: [
431 result: [
432 {
432 {
433 "id" : "<id>",
433 "id" : "<id>",
434 "repo_name" : "<reponame>"
434 "repo_name" : "<reponame>"
435 "type" : "<type>",
435 "type" : "<type>",
436 "description" : "<description>"
436 "description" : "<description>"
437 },
437 },
438 …
438 …
439 ]
439 ]
440 error: null
440 error: null
441
441
442
442
443 get_repo_nodes
443 get_repo_nodes
444 --------------
444 --------------
445
445
446 returns a list of nodes and it's children in a flat list for a given path
446 returns a list of nodes and it's children in a flat list for a given path
447 at given revision. It's possible to specify ret_type to show only `files` or
447 at given revision. It's possible to specify ret_type to show only `files` or
448 `dirs`. This command can be executed only using api_key belonging to user
448 `dirs`. This command can be executed only using api_key belonging to user
449 with admin rights
449 with admin rights
450
450
451
451
452 INPUT::
452 INPUT::
453
453
454 api_key : "<api_key>"
454 api_key : "<api_key>"
455 method : "get_repo_nodes"
455 method : "get_repo_nodes"
456 args: {
456 args: {
457 "repo_name" : "<reponame>",
457 "repo_name" : "<reponame>",
458 "revision" : "<revision>",
458 "revision" : "<revision>",
459 "root_path" : "<root_path>",
459 "root_path" : "<root_path>",
460 "ret_type" : "<ret_type>" = 'all'
460 "ret_type" : "<ret_type>" = 'all'
461 }
461 }
462
462
463 OUTPUT::
463 OUTPUT::
464
464
465 result: [
465 result: [
466 {
466 {
467 "name" : "<name>"
467 "name" : "<name>"
468 "type" : "<type>",
468 "type" : "<type>",
469 },
469 },
470 …
470 …
471 ]
471 ]
472 error: null
472 error: null
473
473
474
474
475 create_repo
475 create_repo
476 -----------
476 -----------
477
477
478 Creates a repository. This command can be executed only using api_key
478 Creates a repository. This command can be executed only using api_key
479 belonging to user with admin rights.
479 belonging to user with admin rights.
480 If repository name contains "/", all needed repository groups will be created.
480 If repository name contains "/", all needed repository groups will be created.
481 For example "foo/bar/baz" will create groups "foo", "bar" (with "foo" as parent),
481 For example "foo/bar/baz" will create groups "foo", "bar" (with "foo" as parent),
482 and create "baz" repository with "bar" as group.
482 and create "baz" repository with "bar" as group.
483
483
484
484
485 INPUT::
485 INPUT::
486
486
487 api_key : "<api_key>"
487 api_key : "<api_key>"
488 method : "create_repo"
488 method : "create_repo"
489 args: {
489 args: {
490 "repo_name" : "<reponame>",
490 "repo_name" : "<reponame>",
491 "owner_name" : "<ownername>",
491 "owner_name" : "<ownername>",
492 "description" : "<description> = ''",
492 "description" : "<description> = ''",
493 "repo_type" : "<type> = 'hg'",
493 "repo_type" : "<type> = 'hg'",
494 "private" : "<bool> = False"
494 "private" : "<bool> = False",
495 "clone_uri" : "<clone_uri> = None",
495 }
496 }
496
497
497 OUTPUT::
498 OUTPUT::
498
499
499 result: {
500 result: {
500 "id": "<newrepoid>",
501 "id": "<newrepoid>",
501 "msg": "Created new repository <reponame>",
502 "msg": "Created new repository <reponame>",
502 }
503 }
503 error: null
504 error: null
504
505
505
506
506 delete_repo
507 delete_repo
507 -----------
508 -----------
508
509
509 Deletes a repository. This command can be executed only using api_key
510 Deletes a repository. This command can be executed only using api_key
510 belonging to user with admin rights.
511 belonging to user with admin rights.
511
512
512
513
513 INPUT::
514 INPUT::
514
515
515 api_key : "<api_key>"
516 api_key : "<api_key>"
516 method : "delete_repo"
517 method : "delete_repo"
517 args: {
518 args: {
518 "repo_name" : "<reponame>",
519 "repo_name" : "<reponame>",
519 }
520 }
520
521
521 OUTPUT::
522 OUTPUT::
522
523
523 result: {
524 result: {
524 "msg": "Deleted repository <reponame>",
525 "msg": "Deleted repository <reponame>",
525 }
526 }
526 error: null
527 error: null
527
528
528
529
529 grant_user_permission
530 grant_user_permission
530 ---------------------
531 ---------------------
531
532
532 Grant permission for user on given repository, or update existing one
533 Grant permission for user on given repository, or update existing one
533 if found. This command can be executed only using api_key belonging to user
534 if found. This command can be executed only using api_key belonging to user
534 with admin rights.
535 with admin rights.
535
536
536
537
537 INPUT::
538 INPUT::
538
539
539 api_key : "<api_key>"
540 api_key : "<api_key>"
540 method : "grant_user_permission"
541 method : "grant_user_permission"
541 args: {
542 args: {
542 "repo_name" : "<reponame>",
543 "repo_name" : "<reponame>",
543 "username" : "<username>",
544 "username" : "<username>",
544 "perm" : "(repository.(none|read|write|admin))",
545 "perm" : "(repository.(none|read|write|admin))",
545 }
546 }
546
547
547 OUTPUT::
548 OUTPUT::
548
549
549 result: {
550 result: {
550 "msg" : "Granted perm: <perm> for user: <username> in repo: <reponame>"
551 "msg" : "Granted perm: <perm> for user: <username> in repo: <reponame>"
551 }
552 }
552 error: null
553 error: null
553
554
554
555
555 revoke_user_permission
556 revoke_user_permission
556 ----------------------
557 ----------------------
557
558
558 Revoke permission for user on given repository. This command can be executed
559 Revoke permission for user on given repository. This command can be executed
559 only using api_key belonging to user with admin rights.
560 only using api_key belonging to user with admin rights.
560
561
561
562
562 INPUT::
563 INPUT::
563
564
564 api_key : "<api_key>"
565 api_key : "<api_key>"
565 method : "revoke_user_permission"
566 method : "revoke_user_permission"
566 args: {
567 args: {
567 "repo_name" : "<reponame>",
568 "repo_name" : "<reponame>",
568 "username" : "<username>",
569 "username" : "<username>",
569 }
570 }
570
571
571 OUTPUT::
572 OUTPUT::
572
573
573 result: {
574 result: {
574 "msg" : "Revoked perm for user: <suername> in repo: <reponame>"
575 "msg" : "Revoked perm for user: <suername> in repo: <reponame>"
575 }
576 }
576 error: null
577 error: null
577
578
578
579
579 grant_users_group_permission
580 grant_users_group_permission
580 ----------------------------
581 ----------------------------
581
582
582 Grant permission for users group on given repository, or update
583 Grant permission for users group on given repository, or update
583 existing one if found. This command can be executed only using
584 existing one if found. This command can be executed only using
584 api_key belonging to user with admin rights.
585 api_key belonging to user with admin rights.
585
586
586
587
587 INPUT::
588 INPUT::
588
589
589 api_key : "<api_key>"
590 api_key : "<api_key>"
590 method : "grant_users_group_permission"
591 method : "grant_users_group_permission"
591 args: {
592 args: {
592 "repo_name" : "<reponame>",
593 "repo_name" : "<reponame>",
593 "group_name" : "<usersgroupname>",
594 "group_name" : "<usersgroupname>",
594 "perm" : "(repository.(none|read|write|admin))",
595 "perm" : "(repository.(none|read|write|admin))",
595 }
596 }
596
597
597 OUTPUT::
598 OUTPUT::
598
599
599 result: {
600 result: {
600 "msg" : "Granted perm: <perm> for group: <usersgroupname> in repo: <reponame>"
601 "msg" : "Granted perm: <perm> for group: <usersgroupname> in repo: <reponame>"
601 }
602 }
602 error: null
603 error: null
603
604
604
605
605 revoke_users_group_permission
606 revoke_users_group_permission
606 -----------------------------
607 -----------------------------
607
608
608 Revoke permission for users group on given repository.This command can be
609 Revoke permission for users group on given repository.This command can be
609 executed only using api_key belonging to user with admin rights.
610 executed only using api_key belonging to user with admin rights.
610
611
611 INPUT::
612 INPUT::
612
613
613 api_key : "<api_key>"
614 api_key : "<api_key>"
614 method : "revoke_users_group_permission"
615 method : "revoke_users_group_permission"
615 args: {
616 args: {
616 "repo_name" : "<reponame>",
617 "repo_name" : "<reponame>",
617 "users_group" : "<usersgroupname>",
618 "users_group" : "<usersgroupname>",
618 }
619 }
619
620
620 OUTPUT::
621 OUTPUT::
621
622
622 result: {
623 result: {
623 "msg" : "Revoked perm for group: <usersgroupname> in repo: <reponame>"
624 "msg" : "Revoked perm for group: <usersgroupname> in repo: <reponame>"
624 }
625 }
625 error: null No newline at end of file
626 error: null
@@ -1,655 +1,656 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 rhodecode.controllers.api
3 rhodecode.controllers.api
4 ~~~~~~~~~~~~~~~~~~~~~~~~~
4 ~~~~~~~~~~~~~~~~~~~~~~~~~
5
5
6 API controller for RhodeCode
6 API controller for RhodeCode
7
7
8 :created_on: Aug 20, 2011
8 :created_on: Aug 20, 2011
9 :author: marcink
9 :author: marcink
10 :copyright: (C) 2011-2012 Marcin Kuzminski <marcin@python-works.com>
10 :copyright: (C) 2011-2012 Marcin Kuzminski <marcin@python-works.com>
11 :license: GPLv3, see COPYING for more details.
11 :license: GPLv3, see COPYING for more details.
12 """
12 """
13 # This program is free software; you can redistribute it and/or
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation; version 2
15 # as published by the Free Software Foundation; version 2
16 # of the License or (at your opinion) any later version of the license.
16 # of the License or (at your opinion) any later version of the license.
17 #
17 #
18 # This program is distributed in the hope that it will be useful,
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
21 # GNU General Public License for more details.
22 #
22 #
23 # You should have received a copy of the GNU General Public License
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
26 # MA 02110-1301, USA.
26 # MA 02110-1301, USA.
27
27
28 import traceback
28 import traceback
29 import logging
29 import logging
30
30
31 from sqlalchemy.orm.exc import NoResultFound
31 from sqlalchemy.orm.exc import NoResultFound
32
32
33 from rhodecode.controllers.api import JSONRPCController, JSONRPCError
33 from rhodecode.controllers.api import JSONRPCController, JSONRPCError
34 from rhodecode.lib.auth import HasPermissionAllDecorator, \
34 from rhodecode.lib.auth import HasPermissionAllDecorator, \
35 HasPermissionAnyDecorator
35 HasPermissionAnyDecorator
36
36
37 from rhodecode.model.meta import Session
37 from rhodecode.model.meta import Session
38 from rhodecode.model.scm import ScmModel
38 from rhodecode.model.scm import ScmModel
39 from rhodecode.model.db import User, UsersGroup, RepoGroup, Repository
39 from rhodecode.model.db import User, UsersGroup, RepoGroup, Repository
40 from rhodecode.model.repo import RepoModel
40 from rhodecode.model.repo import RepoModel
41 from rhodecode.model.user import UserModel
41 from rhodecode.model.user import UserModel
42 from rhodecode.model.repo_permission import RepositoryPermissionModel
42 from rhodecode.model.repo_permission import RepositoryPermissionModel
43 from rhodecode.model.users_group import UsersGroupModel
43 from rhodecode.model.users_group import UsersGroupModel
44 from rhodecode.model.repos_group import ReposGroupModel
44 from rhodecode.model.repos_group import ReposGroupModel
45
45
46
46
47 log = logging.getLogger(__name__)
47 log = logging.getLogger(__name__)
48
48
49
49
50 class ApiController(JSONRPCController):
50 class ApiController(JSONRPCController):
51 """
51 """
52 API Controller
52 API Controller
53
53
54
54
55 Each method needs to have USER as argument this is then based on given
55 Each method needs to have USER as argument this is then based on given
56 API_KEY propagated as instance of user object
56 API_KEY propagated as instance of user object
57
57
58 Preferably this should be first argument also
58 Preferably this should be first argument also
59
59
60
60
61 Each function should also **raise** JSONRPCError for any
61 Each function should also **raise** JSONRPCError for any
62 errors that happens
62 errors that happens
63
63
64 """
64 """
65
65
66 @HasPermissionAllDecorator('hg.admin')
66 @HasPermissionAllDecorator('hg.admin')
67 def pull(self, apiuser, repo_name):
67 def pull(self, apiuser, repo_name):
68 """
68 """
69 Dispatch pull action on given repo
69 Dispatch pull action on given repo
70
70
71
71
72 :param user:
72 :param user:
73 :param repo_name:
73 :param repo_name:
74 """
74 """
75
75
76 if Repository.is_valid(repo_name) is False:
76 if Repository.is_valid(repo_name) is False:
77 raise JSONRPCError('Unknown repo "%s"' % repo_name)
77 raise JSONRPCError('Unknown repo "%s"' % repo_name)
78
78
79 try:
79 try:
80 ScmModel().pull_changes(repo_name, self.rhodecode_user.username)
80 ScmModel().pull_changes(repo_name, self.rhodecode_user.username)
81 return 'Pulled from %s' % repo_name
81 return 'Pulled from %s' % repo_name
82 except Exception:
82 except Exception:
83 raise JSONRPCError('Unable to pull changes from "%s"' % repo_name)
83 raise JSONRPCError('Unable to pull changes from "%s"' % repo_name)
84
84
85 @HasPermissionAllDecorator('hg.admin')
85 @HasPermissionAllDecorator('hg.admin')
86 def get_user(self, apiuser, username):
86 def get_user(self, apiuser, username):
87 """"
87 """"
88 Get a user by username
88 Get a user by username
89
89
90 :param apiuser:
90 :param apiuser:
91 :param username:
91 :param username:
92 """
92 """
93
93
94 user = User.get_by_username(username)
94 user = User.get_by_username(username)
95 if user is None:
95 if user is None:
96 return user
96 return user
97
97
98 return dict(
98 return dict(
99 id=user.user_id,
99 id=user.user_id,
100 username=user.username,
100 username=user.username,
101 firstname=user.name,
101 firstname=user.name,
102 lastname=user.lastname,
102 lastname=user.lastname,
103 email=user.email,
103 email=user.email,
104 active=user.active,
104 active=user.active,
105 admin=user.admin,
105 admin=user.admin,
106 ldap=user.ldap_dn
106 ldap=user.ldap_dn
107 )
107 )
108
108
109 @HasPermissionAllDecorator('hg.admin')
109 @HasPermissionAllDecorator('hg.admin')
110 def get_users(self, apiuser):
110 def get_users(self, apiuser):
111 """"
111 """"
112 Get all users
112 Get all users
113
113
114 :param apiuser:
114 :param apiuser:
115 """
115 """
116
116
117 result = []
117 result = []
118 for user in User.getAll():
118 for user in User.getAll():
119 result.append(
119 result.append(
120 dict(
120 dict(
121 id=user.user_id,
121 id=user.user_id,
122 username=user.username,
122 username=user.username,
123 firstname=user.name,
123 firstname=user.name,
124 lastname=user.lastname,
124 lastname=user.lastname,
125 email=user.email,
125 email=user.email,
126 active=user.active,
126 active=user.active,
127 admin=user.admin,
127 admin=user.admin,
128 ldap=user.ldap_dn
128 ldap=user.ldap_dn
129 )
129 )
130 )
130 )
131 return result
131 return result
132
132
133 @HasPermissionAllDecorator('hg.admin')
133 @HasPermissionAllDecorator('hg.admin')
134 def create_user(self, apiuser, username, password, email, firstname=None,
134 def create_user(self, apiuser, username, password, email, firstname=None,
135 lastname=None, active=True, admin=False, ldap_dn=None):
135 lastname=None, active=True, admin=False, ldap_dn=None):
136 """
136 """
137 Create new user
137 Create new user
138
138
139 :param apiuser:
139 :param apiuser:
140 :param username:
140 :param username:
141 :param password:
141 :param password:
142 :param email:
142 :param email:
143 :param name:
143 :param name:
144 :param lastname:
144 :param lastname:
145 :param active:
145 :param active:
146 :param admin:
146 :param admin:
147 :param ldap_dn:
147 :param ldap_dn:
148 """
148 """
149 if User.get_by_username(username):
149 if User.get_by_username(username):
150 raise JSONRPCError("user %s already exist" % username)
150 raise JSONRPCError("user %s already exist" % username)
151
151
152 try:
152 try:
153 usr = UserModel().create_or_update(
153 usr = UserModel().create_or_update(
154 username, password, email, firstname,
154 username, password, email, firstname,
155 lastname, active, admin, ldap_dn
155 lastname, active, admin, ldap_dn
156 )
156 )
157 Session.commit()
157 Session.commit()
158 return dict(
158 return dict(
159 id=usr.user_id,
159 id=usr.user_id,
160 msg='created new user %s' % username
160 msg='created new user %s' % username
161 )
161 )
162 except Exception:
162 except Exception:
163 log.error(traceback.format_exc())
163 log.error(traceback.format_exc())
164 raise JSONRPCError('failed to create user %s' % username)
164 raise JSONRPCError('failed to create user %s' % username)
165
165
166 @HasPermissionAllDecorator('hg.admin')
166 @HasPermissionAllDecorator('hg.admin')
167 def update_user(self, apiuser, username, password, email, firstname=None,
167 def update_user(self, apiuser, username, password, email, firstname=None,
168 lastname=None, active=True, admin=False, ldap_dn=None):
168 lastname=None, active=True, admin=False, ldap_dn=None):
169 """
169 """
170 Updates given user
170 Updates given user
171
171
172 :param apiuser:
172 :param apiuser:
173 :param username:
173 :param username:
174 :param password:
174 :param password:
175 :param email:
175 :param email:
176 :param name:
176 :param name:
177 :param lastname:
177 :param lastname:
178 :param active:
178 :param active:
179 :param admin:
179 :param admin:
180 :param ldap_dn:
180 :param ldap_dn:
181 """
181 """
182 if not User.get_by_username(username):
182 if not User.get_by_username(username):
183 raise JSONRPCError("user %s does not exist" % username)
183 raise JSONRPCError("user %s does not exist" % username)
184
184
185 try:
185 try:
186 usr = UserModel().create_or_update(
186 usr = UserModel().create_or_update(
187 username, password, email, firstname,
187 username, password, email, firstname,
188 lastname, active, admin, ldap_dn
188 lastname, active, admin, ldap_dn
189 )
189 )
190 Session.commit()
190 Session.commit()
191 return dict(
191 return dict(
192 id=usr.user_id,
192 id=usr.user_id,
193 msg='updated user %s' % username
193 msg='updated user %s' % username
194 )
194 )
195 except Exception:
195 except Exception:
196 log.error(traceback.format_exc())
196 log.error(traceback.format_exc())
197 raise JSONRPCError('failed to update user %s' % username)
197 raise JSONRPCError('failed to update user %s' % username)
198
198
199 @HasPermissionAllDecorator('hg.admin')
199 @HasPermissionAllDecorator('hg.admin')
200 def get_users_group(self, apiuser, group_name):
200 def get_users_group(self, apiuser, group_name):
201 """"
201 """"
202 Get users group by name
202 Get users group by name
203
203
204 :param apiuser:
204 :param apiuser:
205 :param group_name:
205 :param group_name:
206 """
206 """
207
207
208 users_group = UsersGroup.get_by_group_name(group_name)
208 users_group = UsersGroup.get_by_group_name(group_name)
209 if not users_group:
209 if not users_group:
210 return None
210 return None
211
211
212 members = []
212 members = []
213 for user in users_group.members:
213 for user in users_group.members:
214 user = user.user
214 user = user.user
215 members.append(dict(id=user.user_id,
215 members.append(dict(id=user.user_id,
216 username=user.username,
216 username=user.username,
217 firstname=user.name,
217 firstname=user.name,
218 lastname=user.lastname,
218 lastname=user.lastname,
219 email=user.email,
219 email=user.email,
220 active=user.active,
220 active=user.active,
221 admin=user.admin,
221 admin=user.admin,
222 ldap=user.ldap_dn))
222 ldap=user.ldap_dn))
223
223
224 return dict(id=users_group.users_group_id,
224 return dict(id=users_group.users_group_id,
225 group_name=users_group.users_group_name,
225 group_name=users_group.users_group_name,
226 active=users_group.users_group_active,
226 active=users_group.users_group_active,
227 members=members)
227 members=members)
228
228
229 @HasPermissionAllDecorator('hg.admin')
229 @HasPermissionAllDecorator('hg.admin')
230 def get_users_groups(self, apiuser):
230 def get_users_groups(self, apiuser):
231 """"
231 """"
232 Get all users groups
232 Get all users groups
233
233
234 :param apiuser:
234 :param apiuser:
235 """
235 """
236
236
237 result = []
237 result = []
238 for users_group in UsersGroup.getAll():
238 for users_group in UsersGroup.getAll():
239 members = []
239 members = []
240 for user in users_group.members:
240 for user in users_group.members:
241 user = user.user
241 user = user.user
242 members.append(dict(id=user.user_id,
242 members.append(dict(id=user.user_id,
243 username=user.username,
243 username=user.username,
244 firstname=user.name,
244 firstname=user.name,
245 lastname=user.lastname,
245 lastname=user.lastname,
246 email=user.email,
246 email=user.email,
247 active=user.active,
247 active=user.active,
248 admin=user.admin,
248 admin=user.admin,
249 ldap=user.ldap_dn))
249 ldap=user.ldap_dn))
250
250
251 result.append(dict(id=users_group.users_group_id,
251 result.append(dict(id=users_group.users_group_id,
252 group_name=users_group.users_group_name,
252 group_name=users_group.users_group_name,
253 active=users_group.users_group_active,
253 active=users_group.users_group_active,
254 members=members))
254 members=members))
255 return result
255 return result
256
256
257 @HasPermissionAllDecorator('hg.admin')
257 @HasPermissionAllDecorator('hg.admin')
258 def create_users_group(self, apiuser, group_name, active=True):
258 def create_users_group(self, apiuser, group_name, active=True):
259 """
259 """
260 Creates an new usergroup
260 Creates an new usergroup
261
261
262 :param group_name:
262 :param group_name:
263 :param active:
263 :param active:
264 """
264 """
265
265
266 if self.get_users_group(apiuser, group_name):
266 if self.get_users_group(apiuser, group_name):
267 raise JSONRPCError("users group %s already exist" % group_name)
267 raise JSONRPCError("users group %s already exist" % group_name)
268
268
269 try:
269 try:
270 ug = UsersGroupModel().create(name=group_name, active=active)
270 ug = UsersGroupModel().create(name=group_name, active=active)
271 Session.commit()
271 Session.commit()
272 return dict(id=ug.users_group_id,
272 return dict(id=ug.users_group_id,
273 msg='created new users group %s' % group_name)
273 msg='created new users group %s' % group_name)
274 except Exception:
274 except Exception:
275 log.error(traceback.format_exc())
275 log.error(traceback.format_exc())
276 raise JSONRPCError('failed to create group %s' % group_name)
276 raise JSONRPCError('failed to create group %s' % group_name)
277
277
278 @HasPermissionAllDecorator('hg.admin')
278 @HasPermissionAllDecorator('hg.admin')
279 def add_user_to_users_group(self, apiuser, group_name, username):
279 def add_user_to_users_group(self, apiuser, group_name, username):
280 """"
280 """"
281 Add a user to a group
281 Add a user to a group
282
282
283 :param apiuser:
283 :param apiuser:
284 :param group_name:
284 :param group_name:
285 :param username:
285 :param username:
286 """
286 """
287
287
288 try:
288 try:
289 users_group = UsersGroup.get_by_group_name(group_name)
289 users_group = UsersGroup.get_by_group_name(group_name)
290 if not users_group:
290 if not users_group:
291 raise JSONRPCError('unknown users group %s' % group_name)
291 raise JSONRPCError('unknown users group %s' % group_name)
292
292
293 user = User.get_by_username(username)
293 user = User.get_by_username(username)
294 if user is None:
294 if user is None:
295 raise JSONRPCError('unknown user %s' % username)
295 raise JSONRPCError('unknown user %s' % username)
296
296
297 ugm = UsersGroupModel().add_user_to_group(users_group, user)
297 ugm = UsersGroupModel().add_user_to_group(users_group, user)
298 success = True if ugm != True else False
298 success = True if ugm != True else False
299 msg = 'added member %s to users group %s' % (username, group_name)
299 msg = 'added member %s to users group %s' % (username, group_name)
300 msg = msg if success else 'User is already in that group'
300 msg = msg if success else 'User is already in that group'
301 Session.commit()
301 Session.commit()
302
302
303 return dict(
303 return dict(
304 id=ugm.users_group_member_id if ugm != True else None,
304 id=ugm.users_group_member_id if ugm != True else None,
305 success=success,
305 success=success,
306 msg=msg
306 msg=msg
307 )
307 )
308 except Exception:
308 except Exception:
309 log.error(traceback.format_exc())
309 log.error(traceback.format_exc())
310 raise JSONRPCError('failed to add users group member')
310 raise JSONRPCError('failed to add users group member')
311
311
312 @HasPermissionAllDecorator('hg.admin')
312 @HasPermissionAllDecorator('hg.admin')
313 def remove_user_from_users_group(self, apiuser, group_name, username):
313 def remove_user_from_users_group(self, apiuser, group_name, username):
314 """
314 """
315 Remove user from a group
315 Remove user from a group
316
316
317 :param apiuser
317 :param apiuser
318 :param group_name
318 :param group_name
319 :param username
319 :param username
320 """
320 """
321
321
322 try:
322 try:
323 users_group = UsersGroup.get_by_group_name(group_name)
323 users_group = UsersGroup.get_by_group_name(group_name)
324 if not users_group:
324 if not users_group:
325 raise JSONRPCError('unknown users group %s' % group_name)
325 raise JSONRPCError('unknown users group %s' % group_name)
326
326
327 user = User.get_by_username(username)
327 user = User.get_by_username(username)
328 if user is None:
328 if user is None:
329 raise JSONRPCError('unknown user %s' % username)
329 raise JSONRPCError('unknown user %s' % username)
330
330
331 success = UsersGroupModel().remove_user_from_group(users_group, user)
331 success = UsersGroupModel().remove_user_from_group(users_group, user)
332 msg = 'removed member %s from users group %s' % (username, group_name)
332 msg = 'removed member %s from users group %s' % (username, group_name)
333 msg = msg if success else "User wasn't in group"
333 msg = msg if success else "User wasn't in group"
334 Session.commit()
334 Session.commit()
335 return dict(success=success, msg=msg)
335 return dict(success=success, msg=msg)
336 except Exception:
336 except Exception:
337 log.error(traceback.format_exc())
337 log.error(traceback.format_exc())
338 raise JSONRPCError('failed to remove user from group')
338 raise JSONRPCError('failed to remove user from group')
339
339
340 @HasPermissionAnyDecorator('hg.admin')
340 @HasPermissionAnyDecorator('hg.admin')
341 def get_repo(self, apiuser, repo_name):
341 def get_repo(self, apiuser, repo_name):
342 """"
342 """"
343 Get repository by name
343 Get repository by name
344
344
345 :param apiuser:
345 :param apiuser:
346 :param repo_name:
346 :param repo_name:
347 """
347 """
348
348
349 repo = Repository.get_by_repo_name(repo_name)
349 repo = Repository.get_by_repo_name(repo_name)
350 if repo is None:
350 if repo is None:
351 raise JSONRPCError('unknown repository %s' % repo)
351 raise JSONRPCError('unknown repository %s' % repo)
352
352
353 members = []
353 members = []
354 for user in repo.repo_to_perm:
354 for user in repo.repo_to_perm:
355 perm = user.permission.permission_name
355 perm = user.permission.permission_name
356 user = user.user
356 user = user.user
357 members.append(
357 members.append(
358 dict(
358 dict(
359 type_="user",
359 type_="user",
360 id=user.user_id,
360 id=user.user_id,
361 username=user.username,
361 username=user.username,
362 firstname=user.name,
362 firstname=user.name,
363 lastname=user.lastname,
363 lastname=user.lastname,
364 email=user.email,
364 email=user.email,
365 active=user.active,
365 active=user.active,
366 admin=user.admin,
366 admin=user.admin,
367 ldap=user.ldap_dn,
367 ldap=user.ldap_dn,
368 permission=perm
368 permission=perm
369 )
369 )
370 )
370 )
371 for users_group in repo.users_group_to_perm:
371 for users_group in repo.users_group_to_perm:
372 perm = users_group.permission.permission_name
372 perm = users_group.permission.permission_name
373 users_group = users_group.users_group
373 users_group = users_group.users_group
374 members.append(
374 members.append(
375 dict(
375 dict(
376 type_="users_group",
376 type_="users_group",
377 id=users_group.users_group_id,
377 id=users_group.users_group_id,
378 name=users_group.users_group_name,
378 name=users_group.users_group_name,
379 active=users_group.users_group_active,
379 active=users_group.users_group_active,
380 permission=perm
380 permission=perm
381 )
381 )
382 )
382 )
383
383
384 return dict(
384 return dict(
385 id=repo.repo_id,
385 id=repo.repo_id,
386 repo_name=repo.repo_name,
386 repo_name=repo.repo_name,
387 type=repo.repo_type,
387 type=repo.repo_type,
388 description=repo.description,
388 description=repo.description,
389 members=members
389 members=members
390 )
390 )
391
391
392 @HasPermissionAnyDecorator('hg.admin')
392 @HasPermissionAnyDecorator('hg.admin')
393 def get_repos(self, apiuser):
393 def get_repos(self, apiuser):
394 """"
394 """"
395 Get all repositories
395 Get all repositories
396
396
397 :param apiuser:
397 :param apiuser:
398 """
398 """
399
399
400 result = []
400 result = []
401 for repository in Repository.getAll():
401 for repository in Repository.getAll():
402 result.append(
402 result.append(
403 dict(
403 dict(
404 id=repository.repo_id,
404 id=repository.repo_id,
405 repo_name=repository.repo_name,
405 repo_name=repository.repo_name,
406 type=repository.repo_type,
406 type=repository.repo_type,
407 description=repository.description
407 description=repository.description
408 )
408 )
409 )
409 )
410 return result
410 return result
411
411
412 @HasPermissionAnyDecorator('hg.admin')
412 @HasPermissionAnyDecorator('hg.admin')
413 def get_repo_nodes(self, apiuser, repo_name, revision, root_path,
413 def get_repo_nodes(self, apiuser, repo_name, revision, root_path,
414 ret_type='all'):
414 ret_type='all'):
415 """
415 """
416 returns a list of nodes and it's children
416 returns a list of nodes and it's children
417 for a given path at given revision. It's possible to specify ret_type
417 for a given path at given revision. It's possible to specify ret_type
418 to show only files or dirs
418 to show only files or dirs
419
419
420 :param apiuser:
420 :param apiuser:
421 :param repo_name: name of repository
421 :param repo_name: name of repository
422 :param revision: revision for which listing should be done
422 :param revision: revision for which listing should be done
423 :param root_path: path from which start displaying
423 :param root_path: path from which start displaying
424 :param ret_type: return type 'all|files|dirs' nodes
424 :param ret_type: return type 'all|files|dirs' nodes
425 """
425 """
426 try:
426 try:
427 _d, _f = ScmModel().get_nodes(repo_name, revision, root_path,
427 _d, _f = ScmModel().get_nodes(repo_name, revision, root_path,
428 flat=False)
428 flat=False)
429 _map = {
429 _map = {
430 'all': _d + _f,
430 'all': _d + _f,
431 'files': _f,
431 'files': _f,
432 'dirs': _d,
432 'dirs': _d,
433 }
433 }
434 return _map[ret_type]
434 return _map[ret_type]
435 except KeyError:
435 except KeyError:
436 raise JSONRPCError('ret_type must be one of %s' % _map.keys())
436 raise JSONRPCError('ret_type must be one of %s' % _map.keys())
437 except Exception, e:
437 except Exception, e:
438 raise JSONRPCError(e)
438 raise JSONRPCError(e)
439
439
440 @HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
440 @HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
441 def create_repo(self, apiuser, repo_name, owner_name, description='',
441 def create_repo(self, apiuser, repo_name, owner_name, description='',
442 repo_type='hg', private=False):
442 repo_type='hg', private=False, clone_uri=None):
443 """
443 """
444 Create a repository
444 Create repository, if clone_url is given it makes a remote clone
445
445
446 :param apiuser:
446 :param apiuser:
447 :param repo_name:
447 :param repo_name:
448 :param owner_name:
448 :param description:
449 :param description:
449 :param type:
450 :param repo_type:
450 :param private:
451 :param private:
451 :param owner_name:
452 :param clone_uri:
452 """
453 """
453
454
454 try:
455 try:
455 owner = User.get_by_username(owner_name)
456 owner = User.get_by_username(owner_name)
456 if owner is None:
457 if owner is None:
457 raise JSONRPCError('unknown user %s' % owner_name)
458 raise JSONRPCError('unknown user %s' % owner_name)
458
459
459 if Repository.get_by_repo_name(repo_name):
460 if Repository.get_by_repo_name(repo_name):
460 raise JSONRPCError("repo %s already exist" % repo_name)
461 raise JSONRPCError("repo %s already exist" % repo_name)
461
462
462 groups = repo_name.split('/')
463 groups = repo_name.split('/')
463 real_name = groups[-1]
464 real_name = groups[-1]
464 groups = groups[:-1]
465 groups = groups[:-1]
465 parent_id = None
466 parent_id = None
466 for g in groups:
467 for g in groups:
467 group = RepoGroup.get_by_group_name(g)
468 group = RepoGroup.get_by_group_name(g)
468 if not group:
469 if not group:
469 group = ReposGroupModel().create(g, '', parent_id)
470 group = ReposGroupModel().create(g, '', parent_id)
470 parent_id = group.group_id
471 parent_id = group.group_id
471
472
472 repo = RepoModel().create(
473 repo = RepoModel().create(
473 dict(
474 dict(
474 repo_name=real_name,
475 repo_name=real_name,
475 repo_name_full=repo_name,
476 repo_name_full=repo_name,
476 description=description,
477 description=description,
477 private=private,
478 private=private,
478 repo_type=repo_type,
479 repo_type=repo_type,
479 repo_group=parent_id,
480 repo_group=parent_id,
480 clone_uri=None
481 clone_uri=clone_uri
481 ),
482 ),
482 owner
483 owner
483 )
484 )
484 Session.commit()
485 Session.commit()
485
486
486 return dict(
487 return dict(
487 id=repo.repo_id,
488 id=repo.repo_id,
488 msg="Created new repository %s" % repo.repo_name
489 msg="Created new repository %s" % repo.repo_name
489 )
490 )
490
491
491 except Exception:
492 except Exception:
492 log.error(traceback.format_exc())
493 log.error(traceback.format_exc())
493 raise JSONRPCError('failed to create repository %s' % repo_name)
494 raise JSONRPCError('failed to create repository %s' % repo_name)
494
495
495 @HasPermissionAnyDecorator('hg.admin')
496 @HasPermissionAnyDecorator('hg.admin')
496 def delete_repo(self, apiuser, repo_name):
497 def delete_repo(self, apiuser, repo_name):
497 """
498 """
498 Deletes a given repository
499 Deletes a given repository
499
500
500 :param repo_name:
501 :param repo_name:
501 """
502 """
502 if not Repository.get_by_repo_name(repo_name):
503 if not Repository.get_by_repo_name(repo_name):
503 raise JSONRPCError("repo %s does not exist" % repo_name)
504 raise JSONRPCError("repo %s does not exist" % repo_name)
504 try:
505 try:
505 RepoModel().delete(repo_name)
506 RepoModel().delete(repo_name)
506 Session.commit()
507 Session.commit()
507 return dict(
508 return dict(
508 msg='Deleted repository %s' % repo_name
509 msg='Deleted repository %s' % repo_name
509 )
510 )
510 except Exception:
511 except Exception:
511 log.error(traceback.format_exc())
512 log.error(traceback.format_exc())
512 raise JSONRPCError('failed to delete repository %s' % repo_name)
513 raise JSONRPCError('failed to delete repository %s' % repo_name)
513
514
514 @HasPermissionAnyDecorator('hg.admin')
515 @HasPermissionAnyDecorator('hg.admin')
515 def grant_user_permission(self, apiuser, repo_name, username, perm):
516 def grant_user_permission(self, apiuser, repo_name, username, perm):
516 """
517 """
517 Grant permission for user on given repository, or update existing one
518 Grant permission for user on given repository, or update existing one
518 if found
519 if found
519
520
520 :param repo_name:
521 :param repo_name:
521 :param username:
522 :param username:
522 :param perm:
523 :param perm:
523 """
524 """
524
525
525 try:
526 try:
526 repo = Repository.get_by_repo_name(repo_name)
527 repo = Repository.get_by_repo_name(repo_name)
527 if repo is None:
528 if repo is None:
528 raise JSONRPCError('unknown repository %s' % repo)
529 raise JSONRPCError('unknown repository %s' % repo)
529
530
530 user = User.get_by_username(username)
531 user = User.get_by_username(username)
531 if user is None:
532 if user is None:
532 raise JSONRPCError('unknown user %s' % username)
533 raise JSONRPCError('unknown user %s' % username)
533
534
534 RepoModel().grant_user_permission(repo=repo, user=user, perm=perm)
535 RepoModel().grant_user_permission(repo=repo, user=user, perm=perm)
535
536
536 Session.commit()
537 Session.commit()
537 return dict(
538 return dict(
538 msg='Granted perm: %s for user: %s in repo: %s' % (
539 msg='Granted perm: %s for user: %s in repo: %s' % (
539 perm, username, repo_name
540 perm, username, repo_name
540 )
541 )
541 )
542 )
542 except Exception:
543 except Exception:
543 log.error(traceback.format_exc())
544 log.error(traceback.format_exc())
544 raise JSONRPCError(
545 raise JSONRPCError(
545 'failed to edit permission %(repo)s for %(user)s' % dict(
546 'failed to edit permission %(repo)s for %(user)s' % dict(
546 user=username, repo=repo_name
547 user=username, repo=repo_name
547 )
548 )
548 )
549 )
549
550
550 @HasPermissionAnyDecorator('hg.admin')
551 @HasPermissionAnyDecorator('hg.admin')
551 def revoke_user_permission(self, apiuser, repo_name, username):
552 def revoke_user_permission(self, apiuser, repo_name, username):
552 """
553 """
553 Revoke permission for user on given repository
554 Revoke permission for user on given repository
554
555
555 :param repo_name:
556 :param repo_name:
556 :param username:
557 :param username:
557 """
558 """
558
559
559 try:
560 try:
560 repo = Repository.get_by_repo_name(repo_name)
561 repo = Repository.get_by_repo_name(repo_name)
561 if repo is None:
562 if repo is None:
562 raise JSONRPCError('unknown repository %s' % repo)
563 raise JSONRPCError('unknown repository %s' % repo)
563
564
564 user = User.get_by_username(username)
565 user = User.get_by_username(username)
565 if user is None:
566 if user is None:
566 raise JSONRPCError('unknown user %s' % username)
567 raise JSONRPCError('unknown user %s' % username)
567
568
568 RepoModel().revoke_user_permission(repo=repo_name, user=username)
569 RepoModel().revoke_user_permission(repo=repo_name, user=username)
569
570
570 Session.commit()
571 Session.commit()
571 return dict(
572 return dict(
572 msg='Revoked perm for user: %s in repo: %s' % (
573 msg='Revoked perm for user: %s in repo: %s' % (
573 username, repo_name
574 username, repo_name
574 )
575 )
575 )
576 )
576 except Exception:
577 except Exception:
577 log.error(traceback.format_exc())
578 log.error(traceback.format_exc())
578 raise JSONRPCError(
579 raise JSONRPCError(
579 'failed to edit permission %(repo)s for %(user)s' % dict(
580 'failed to edit permission %(repo)s for %(user)s' % dict(
580 user=username, repo=repo_name
581 user=username, repo=repo_name
581 )
582 )
582 )
583 )
583
584
584 @HasPermissionAnyDecorator('hg.admin')
585 @HasPermissionAnyDecorator('hg.admin')
585 def grant_users_group_permission(self, apiuser, repo_name, group_name, perm):
586 def grant_users_group_permission(self, apiuser, repo_name, group_name, perm):
586 """
587 """
587 Grant permission for users group on given repository, or update
588 Grant permission for users group on given repository, or update
588 existing one if found
589 existing one if found
589
590
590 :param repo_name:
591 :param repo_name:
591 :param group_name:
592 :param group_name:
592 :param perm:
593 :param perm:
593 """
594 """
594
595
595 try:
596 try:
596 repo = Repository.get_by_repo_name(repo_name)
597 repo = Repository.get_by_repo_name(repo_name)
597 if repo is None:
598 if repo is None:
598 raise JSONRPCError('unknown repository %s' % repo)
599 raise JSONRPCError('unknown repository %s' % repo)
599
600
600 user_group = UsersGroup.get_by_group_name(group_name)
601 user_group = UsersGroup.get_by_group_name(group_name)
601 if user_group is None:
602 if user_group is None:
602 raise JSONRPCError('unknown users group %s' % user_group)
603 raise JSONRPCError('unknown users group %s' % user_group)
603
604
604 RepoModel().grant_users_group_permission(repo=repo_name,
605 RepoModel().grant_users_group_permission(repo=repo_name,
605 group_name=group_name,
606 group_name=group_name,
606 perm=perm)
607 perm=perm)
607
608
608 Session.commit()
609 Session.commit()
609 return dict(
610 return dict(
610 msg='Granted perm: %s for group: %s in repo: %s' % (
611 msg='Granted perm: %s for group: %s in repo: %s' % (
611 perm, group_name, repo_name
612 perm, group_name, repo_name
612 )
613 )
613 )
614 )
614 except Exception:
615 except Exception:
615 log.error(traceback.format_exc())
616 log.error(traceback.format_exc())
616 raise JSONRPCError(
617 raise JSONRPCError(
617 'failed to edit permission %(repo)s for %(usersgr)s' % dict(
618 'failed to edit permission %(repo)s for %(usersgr)s' % dict(
618 usersgr=group_name, repo=repo_name
619 usersgr=group_name, repo=repo_name
619 )
620 )
620 )
621 )
621
622
622 @HasPermissionAnyDecorator('hg.admin')
623 @HasPermissionAnyDecorator('hg.admin')
623 def revoke_users_group_permission(self, apiuser, repo_name, group_name):
624 def revoke_users_group_permission(self, apiuser, repo_name, group_name):
624 """
625 """
625 Revoke permission for users group on given repository
626 Revoke permission for users group on given repository
626
627
627 :param repo_name:
628 :param repo_name:
628 :param group_name:
629 :param group_name:
629 """
630 """
630
631
631 try:
632 try:
632 repo = Repository.get_by_repo_name(repo_name)
633 repo = Repository.get_by_repo_name(repo_name)
633 if repo is None:
634 if repo is None:
634 raise JSONRPCError('unknown repository %s' % repo)
635 raise JSONRPCError('unknown repository %s' % repo)
635
636
636 user_group = UsersGroup.get_by_group_name(group_name)
637 user_group = UsersGroup.get_by_group_name(group_name)
637 if user_group is None:
638 if user_group is None:
638 raise JSONRPCError('unknown users group %s' % user_group)
639 raise JSONRPCError('unknown users group %s' % user_group)
639
640
640 RepoModel().revoke_users_group_permission(repo=repo_name,
641 RepoModel().revoke_users_group_permission(repo=repo_name,
641 group_name=group_name)
642 group_name=group_name)
642
643
643 Session.commit()
644 Session.commit()
644 return dict(
645 return dict(
645 msg='Revoked perm for group: %s in repo: %s' % (
646 msg='Revoked perm for group: %s in repo: %s' % (
646 group_name, repo_name
647 group_name, repo_name
647 )
648 )
648 )
649 )
649 except Exception:
650 except Exception:
650 log.error(traceback.format_exc())
651 log.error(traceback.format_exc())
651 raise JSONRPCError(
652 raise JSONRPCError(
652 'failed to edit permission %(repo)s for %(usersgr)s' % dict(
653 'failed to edit permission %(repo)s for %(usersgr)s' % dict(
653 usersgr=group_name, repo=repo_name
654 usersgr=group_name, repo=repo_name
654 )
655 )
655 )
656 )
@@ -1,523 +1,523 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 rhodecode.lib.db_manage
3 rhodecode.lib.db_manage
4 ~~~~~~~~~~~~~~~~~~~~~~~
4 ~~~~~~~~~~~~~~~~~~~~~~~
5
5
6 Database creation, and setup module for RhodeCode. Used for creation
6 Database creation, and setup module for RhodeCode. Used for creation
7 of database as well as for migration operations
7 of database as well as for migration operations
8
8
9 :created_on: Apr 10, 2010
9 :created_on: Apr 10, 2010
10 :author: marcink
10 :author: marcink
11 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
11 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
12 :license: GPLv3, see COPYING for more details.
12 :license: GPLv3, see COPYING for more details.
13 """
13 """
14 # This program is free software: you can redistribute it and/or modify
14 # This program is free software: you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published by
15 # it under the terms of the GNU General Public License as published by
16 # the Free Software Foundation, either version 3 of the License, or
16 # the Free Software Foundation, either version 3 of the License, or
17 # (at your option) any later version.
17 # (at your option) any later version.
18 #
18 #
19 # This program is distributed in the hope that it will be useful,
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
22 # GNU General Public License for more details.
23 #
23 #
24 # You should have received a copy of the GNU General Public License
24 # You should have received a copy of the GNU General Public License
25 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 # along with this program. If not, see <http://www.gnu.org/licenses/>.
26
26
27 import os
27 import os
28 import sys
28 import sys
29 import uuid
29 import uuid
30 import logging
30 import logging
31 from os.path import dirname as dn, join as jn
31 from os.path import dirname as dn, join as jn
32
32
33 from rhodecode import __dbversion__
33 from rhodecode import __dbversion__
34 from rhodecode.model import meta
34 from rhodecode.model import meta
35
35
36 from rhodecode.model.user import UserModel
36 from rhodecode.model.user import UserModel
37 from rhodecode.lib.utils import ask_ok
37 from rhodecode.lib.utils import ask_ok
38 from rhodecode.model import init_model
38 from rhodecode.model import init_model
39 from rhodecode.model.db import User, Permission, RhodeCodeUi, \
39 from rhodecode.model.db import User, Permission, RhodeCodeUi, \
40 RhodeCodeSetting, UserToPerm, DbMigrateVersion, RepoGroup,\
40 RhodeCodeSetting, UserToPerm, DbMigrateVersion, RepoGroup,\
41 UserRepoGroupToPerm
41 UserRepoGroupToPerm
42
42
43 from sqlalchemy.engine import create_engine
43 from sqlalchemy.engine import create_engine
44 from rhodecode.model.repos_group import ReposGroupModel
44 from rhodecode.model.repos_group import ReposGroupModel
45
45
46 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
47
47
48
48
49 class DbManage(object):
49 class DbManage(object):
50 def __init__(self, log_sql, dbconf, root, tests=False):
50 def __init__(self, log_sql, dbconf, root, tests=False):
51 self.dbname = dbconf.split('/')[-1]
51 self.dbname = dbconf.split('/')[-1]
52 self.tests = tests
52 self.tests = tests
53 self.root = root
53 self.root = root
54 self.dburi = dbconf
54 self.dburi = dbconf
55 self.log_sql = log_sql
55 self.log_sql = log_sql
56 self.db_exists = False
56 self.db_exists = False
57 self.init_db()
57 self.init_db()
58
58
59 def init_db(self):
59 def init_db(self):
60 engine = create_engine(self.dburi, echo=self.log_sql)
60 engine = create_engine(self.dburi, echo=self.log_sql)
61 init_model(engine)
61 init_model(engine)
62 self.sa = meta.Session
62 self.sa = meta.Session
63
63
64 def create_tables(self, override=False):
64 def create_tables(self, override=False):
65 """
65 """
66 Create a auth database
66 Create a auth database
67 """
67 """
68
68
69 log.info("Any existing database is going to be destroyed")
69 log.info("Any existing database is going to be destroyed")
70 if self.tests:
70 if self.tests:
71 destroy = True
71 destroy = True
72 else:
72 else:
73 destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
73 destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
74 if not destroy:
74 if not destroy:
75 sys.exit()
75 sys.exit()
76 if destroy:
76 if destroy:
77 meta.Base.metadata.drop_all()
77 meta.Base.metadata.drop_all()
78
78
79 checkfirst = not override
79 checkfirst = not override
80 meta.Base.metadata.create_all(checkfirst=checkfirst)
80 meta.Base.metadata.create_all(checkfirst=checkfirst)
81 log.info('Created tables for %s' % self.dbname)
81 log.info('Created tables for %s' % self.dbname)
82
82
83 def set_db_version(self):
83 def set_db_version(self):
84 ver = DbMigrateVersion()
84 ver = DbMigrateVersion()
85 ver.version = __dbversion__
85 ver.version = __dbversion__
86 ver.repository_id = 'rhodecode_db_migrations'
86 ver.repository_id = 'rhodecode_db_migrations'
87 ver.repository_path = 'versions'
87 ver.repository_path = 'versions'
88 self.sa.add(ver)
88 self.sa.add(ver)
89 log.info('db version set to: %s' % __dbversion__)
89 log.info('db version set to: %s' % __dbversion__)
90
90
91 def upgrade(self):
91 def upgrade(self):
92 """
92 """
93 Upgrades given database schema to given revision following
93 Upgrades given database schema to given revision following
94 all needed steps, to perform the upgrade
94 all needed steps, to perform the upgrade
95
95
96 """
96 """
97
97
98 from rhodecode.lib.dbmigrate.migrate.versioning import api
98 from rhodecode.lib.dbmigrate.migrate.versioning import api
99 from rhodecode.lib.dbmigrate.migrate.exceptions import \
99 from rhodecode.lib.dbmigrate.migrate.exceptions import \
100 DatabaseNotControlledError
100 DatabaseNotControlledError
101
101
102 if 'sqlite' in self.dburi:
102 if 'sqlite' in self.dburi:
103 print (
103 print (
104 '********************** WARNING **********************\n'
104 '********************** WARNING **********************\n'
105 'Make sure your version of sqlite is at least 3.7.X. \n'
105 'Make sure your version of sqlite is at least 3.7.X. \n'
106 'Earlier versions are known to fail on some migrations\n'
106 'Earlier versions are known to fail on some migrations\n'
107 '*****************************************************\n'
107 '*****************************************************\n'
108 )
108 )
109 upgrade = ask_ok('You are about to perform database upgrade, make '
109 upgrade = ask_ok('You are about to perform database upgrade, make '
110 'sure You backed up your database before. '
110 'sure You backed up your database before. '
111 'Continue ? [y/n]')
111 'Continue ? [y/n]')
112 if not upgrade:
112 if not upgrade:
113 sys.exit('Nothing done')
113 sys.exit('Nothing done')
114
114
115 repository_path = jn(dn(dn(dn(os.path.realpath(__file__)))),
115 repository_path = jn(dn(dn(dn(os.path.realpath(__file__)))),
116 'rhodecode/lib/dbmigrate')
116 'rhodecode/lib/dbmigrate')
117 db_uri = self.dburi
117 db_uri = self.dburi
118
118
119 try:
119 try:
120 curr_version = api.db_version(db_uri, repository_path)
120 curr_version = api.db_version(db_uri, repository_path)
121 msg = ('Found current database under version'
121 msg = ('Found current database under version'
122 ' control with version %s' % curr_version)
122 ' control with version %s' % curr_version)
123
123
124 except (RuntimeError, DatabaseNotControlledError):
124 except (RuntimeError, DatabaseNotControlledError):
125 curr_version = 1
125 curr_version = 1
126 msg = ('Current database is not under version control. Setting'
126 msg = ('Current database is not under version control. Setting'
127 ' as version %s' % curr_version)
127 ' as version %s' % curr_version)
128 api.version_control(db_uri, repository_path, curr_version)
128 api.version_control(db_uri, repository_path, curr_version)
129
129
130 print (msg)
130 print (msg)
131
131
132 if curr_version == __dbversion__:
132 if curr_version == __dbversion__:
133 sys.exit('This database is already at the newest version')
133 sys.exit('This database is already at the newest version')
134
134
135 #======================================================================
135 #======================================================================
136 # UPGRADE STEPS
136 # UPGRADE STEPS
137 #======================================================================
137 #======================================================================
138 class UpgradeSteps(object):
138 class UpgradeSteps(object):
139 """
139 """
140 Those steps follow schema versions so for example schema
140 Those steps follow schema versions so for example schema
141 for example schema with seq 002 == step_2 and so on.
141 for example schema with seq 002 == step_2 and so on.
142 """
142 """
143
143
144 def __init__(self, klass):
144 def __init__(self, klass):
145 self.klass = klass
145 self.klass = klass
146
146
147 def step_0(self):
147 def step_0(self):
148 # step 0 is the schema upgrade, and than follow proper upgrades
148 # step 0 is the schema upgrade, and than follow proper upgrades
149 print ('attempting to do database upgrade to version %s' \
149 print ('attempting to do database upgrade to version %s' \
150 % __dbversion__)
150 % __dbversion__)
151 api.upgrade(db_uri, repository_path, __dbversion__)
151 api.upgrade(db_uri, repository_path, __dbversion__)
152 print ('Schema upgrade completed')
152 print ('Schema upgrade completed')
153
153
154 def step_1(self):
154 def step_1(self):
155 pass
155 pass
156
156
157 def step_2(self):
157 def step_2(self):
158 print ('Patching repo paths for newer version of RhodeCode')
158 print ('Patching repo paths for newer version of RhodeCode')
159 self.klass.fix_repo_paths()
159 self.klass.fix_repo_paths()
160
160
161 print ('Patching default user of RhodeCode')
161 print ('Patching default user of RhodeCode')
162 self.klass.fix_default_user()
162 self.klass.fix_default_user()
163
163
164 log.info('Changing ui settings')
164 log.info('Changing ui settings')
165 self.klass.create_ui_settings()
165 self.klass.create_ui_settings()
166
166
167 def step_3(self):
167 def step_3(self):
168 print ('Adding additional settings into RhodeCode db')
168 print ('Adding additional settings into RhodeCode db')
169 self.klass.fix_settings()
169 self.klass.fix_settings()
170 print ('Adding ldap defaults')
170 print ('Adding ldap defaults')
171 self.klass.create_ldap_options(skip_existing=True)
171 self.klass.create_ldap_options(skip_existing=True)
172
172
173 def step_4(self):
173 def step_4(self):
174 print ('create permissions and fix groups')
174 print ('create permissions and fix groups')
175 self.klass.create_permissions()
175 self.klass.create_permissions()
176 self.klass.fixup_groups()
176 self.klass.fixup_groups()
177
177
178 def step_5(self):
178 def step_5(self):
179 pass
179 pass
180
180
181 upgrade_steps = [0] + range(curr_version + 1, __dbversion__ + 1)
181 upgrade_steps = [0] + range(curr_version + 1, __dbversion__ + 1)
182
182
183 # CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
183 # CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
184 for step in upgrade_steps:
184 for step in upgrade_steps:
185 print ('performing upgrade step %s' % step)
185 print ('performing upgrade step %s' % step)
186 getattr(UpgradeSteps(self), 'step_%s' % step)()
186 getattr(UpgradeSteps(self), 'step_%s' % step)()
187 self.sa.commit()
187 self.sa.commit()
188
188
189 def fix_repo_paths(self):
189 def fix_repo_paths(self):
190 """
190 """
191 Fixes a old rhodecode version path into new one without a '*'
191 Fixes a old rhodecode version path into new one without a '*'
192 """
192 """
193
193
194 paths = self.sa.query(RhodeCodeUi)\
194 paths = self.sa.query(RhodeCodeUi)\
195 .filter(RhodeCodeUi.ui_key == '/')\
195 .filter(RhodeCodeUi.ui_key == '/')\
196 .scalar()
196 .scalar()
197
197
198 paths.ui_value = paths.ui_value.replace('*', '')
198 paths.ui_value = paths.ui_value.replace('*', '')
199
199
200 try:
200 try:
201 self.sa.add(paths)
201 self.sa.add(paths)
202 self.sa.commit()
202 self.sa.commit()
203 except:
203 except:
204 self.sa.rollback()
204 self.sa.rollback()
205 raise
205 raise
206
206
207 def fix_default_user(self):
207 def fix_default_user(self):
208 """
208 """
209 Fixes a old default user with some 'nicer' default values,
209 Fixes a old default user with some 'nicer' default values,
210 used mostly for anonymous access
210 used mostly for anonymous access
211 """
211 """
212 def_user = self.sa.query(User)\
212 def_user = self.sa.query(User)\
213 .filter(User.username == 'default')\
213 .filter(User.username == 'default')\
214 .one()
214 .one()
215
215
216 def_user.name = 'Anonymous'
216 def_user.name = 'Anonymous'
217 def_user.lastname = 'User'
217 def_user.lastname = 'User'
218 def_user.email = 'anonymous@rhodecode.org'
218 def_user.email = 'anonymous@rhodecode.org'
219
219
220 try:
220 try:
221 self.sa.add(def_user)
221 self.sa.add(def_user)
222 self.sa.commit()
222 self.sa.commit()
223 except:
223 except:
224 self.sa.rollback()
224 self.sa.rollback()
225 raise
225 raise
226
226
227 def fix_settings(self):
227 def fix_settings(self):
228 """
228 """
229 Fixes rhodecode settings adds ga_code key for google analytics
229 Fixes rhodecode settings adds ga_code key for google analytics
230 """
230 """
231
231
232 hgsettings3 = RhodeCodeSetting('ga_code', '')
232 hgsettings3 = RhodeCodeSetting('ga_code', '')
233
233
234 try:
234 try:
235 self.sa.add(hgsettings3)
235 self.sa.add(hgsettings3)
236 self.sa.commit()
236 self.sa.commit()
237 except:
237 except:
238 self.sa.rollback()
238 self.sa.rollback()
239 raise
239 raise
240
240
241 def admin_prompt(self, second=False):
241 def admin_prompt(self, second=False):
242 if not self.tests:
242 if not self.tests:
243 import getpass
243 import getpass
244
244
245 def get_password():
245 def get_password():
246 password = getpass.getpass('Specify admin password '
246 password = getpass.getpass('Specify admin password '
247 '(min 6 chars):')
247 '(min 6 chars):')
248 confirm = getpass.getpass('Confirm password:')
248 confirm = getpass.getpass('Confirm password:')
249
249
250 if password != confirm:
250 if password != confirm:
251 log.error('passwords mismatch')
251 log.error('passwords mismatch')
252 return False
252 return False
253 if len(password) < 6:
253 if len(password) < 6:
254 log.error('password is to short use at least 6 characters')
254 log.error('password is to short use at least 6 characters')
255 return False
255 return False
256
256
257 return password
257 return password
258
258
259 username = raw_input('Specify admin username:')
259 username = raw_input('Specify admin username:')
260
260
261 password = get_password()
261 password = get_password()
262 if not password:
262 if not password:
263 #second try
263 #second try
264 password = get_password()
264 password = get_password()
265 if not password:
265 if not password:
266 sys.exit()
266 sys.exit()
267
267
268 email = raw_input('Specify admin email:')
268 email = raw_input('Specify admin email:')
269 self.create_user(username, password, email, True)
269 self.create_user(username, password, email, True)
270 else:
270 else:
271 log.info('creating admin and regular test users')
271 log.info('creating admin and regular test users')
272 from rhodecode.tests import TEST_USER_ADMIN_LOGIN,\
272 from rhodecode.tests import TEST_USER_ADMIN_LOGIN,\
273 TEST_USER_ADMIN_PASS, TEST_USER_ADMIN_EMAIL,\
273 TEST_USER_ADMIN_PASS, TEST_USER_ADMIN_EMAIL,\
274 TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS,\
274 TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS,\
275 TEST_USER_REGULAR_EMAIL, TEST_USER_REGULAR2_LOGIN, \
275 TEST_USER_REGULAR_EMAIL, TEST_USER_REGULAR2_LOGIN, \
276 TEST_USER_REGULAR2_PASS, TEST_USER_REGULAR2_EMAIL
276 TEST_USER_REGULAR2_PASS, TEST_USER_REGULAR2_EMAIL
277
277
278 self.create_user(TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS,
278 self.create_user(TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS,
279 TEST_USER_ADMIN_EMAIL, True)
279 TEST_USER_ADMIN_EMAIL, True)
280
280
281 self.create_user(TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS,
281 self.create_user(TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS,
282 TEST_USER_REGULAR_EMAIL, False)
282 TEST_USER_REGULAR_EMAIL, False)
283
283
284 self.create_user(TEST_USER_REGULAR2_LOGIN, TEST_USER_REGULAR2_PASS,
284 self.create_user(TEST_USER_REGULAR2_LOGIN, TEST_USER_REGULAR2_PASS,
285 TEST_USER_REGULAR2_EMAIL, False)
285 TEST_USER_REGULAR2_EMAIL, False)
286
286
287 def create_ui_settings(self):
287 def create_ui_settings(self):
288 """
288 """
289 Creates ui settings, fills out hooks
289 Creates ui settings, fills out hooks
290 and disables dotencode
290 and disables dotencode
291 """
291 """
292
292
293 #HOOKS
293 #HOOKS
294 hooks1_key = RhodeCodeUi.HOOK_UPDATE
294 hooks1_key = RhodeCodeUi.HOOK_UPDATE
295 hooks1_ = self.sa.query(RhodeCodeUi)\
295 hooks1_ = self.sa.query(RhodeCodeUi)\
296 .filter(RhodeCodeUi.ui_key == hooks1_key).scalar()
296 .filter(RhodeCodeUi.ui_key == hooks1_key).scalar()
297
297
298 hooks1 = RhodeCodeUi() if hooks1_ is None else hooks1_
298 hooks1 = RhodeCodeUi() if hooks1_ is None else hooks1_
299 hooks1.ui_section = 'hooks'
299 hooks1.ui_section = 'hooks'
300 hooks1.ui_key = hooks1_key
300 hooks1.ui_key = hooks1_key
301 hooks1.ui_value = 'hg update >&2'
301 hooks1.ui_value = 'hg update >&2'
302 hooks1.ui_active = False
302 hooks1.ui_active = False
303
303
304 hooks2_key = RhodeCodeUi.HOOK_REPO_SIZE
304 hooks2_key = RhodeCodeUi.HOOK_REPO_SIZE
305 hooks2_ = self.sa.query(RhodeCodeUi)\
305 hooks2_ = self.sa.query(RhodeCodeUi)\
306 .filter(RhodeCodeUi.ui_key == hooks2_key).scalar()
306 .filter(RhodeCodeUi.ui_key == hooks2_key).scalar()
307
307
308 hooks2 = RhodeCodeUi() if hooks2_ is None else hooks2_
308 hooks2 = RhodeCodeUi() if hooks2_ is None else hooks2_
309 hooks2.ui_section = 'hooks'
309 hooks2.ui_section = 'hooks'
310 hooks2.ui_key = hooks2_key
310 hooks2.ui_key = hooks2_key
311 hooks2.ui_value = 'python:rhodecode.lib.hooks.repo_size'
311 hooks2.ui_value = 'python:rhodecode.lib.hooks.repo_size'
312
312
313 hooks3 = RhodeCodeUi()
313 hooks3 = RhodeCodeUi()
314 hooks3.ui_section = 'hooks'
314 hooks3.ui_section = 'hooks'
315 hooks3.ui_key = RhodeCodeUi.HOOK_PUSH
315 hooks3.ui_key = RhodeCodeUi.HOOK_PUSH
316 hooks3.ui_value = 'python:rhodecode.lib.hooks.log_push_action'
316 hooks3.ui_value = 'python:rhodecode.lib.hooks.log_push_action'
317
317
318 hooks4 = RhodeCodeUi()
318 hooks4 = RhodeCodeUi()
319 hooks4.ui_section = 'hooks'
319 hooks4.ui_section = 'hooks'
320 hooks4.ui_key = RhodeCodeUi.HOOK_PULL
320 hooks4.ui_key = RhodeCodeUi.HOOK_PULL
321 hooks4.ui_value = 'python:rhodecode.lib.hooks.log_pull_action'
321 hooks4.ui_value = 'python:rhodecode.lib.hooks.log_pull_action'
322
322
323 # For mercurial 1.7 set backward comapatibility with format
323 # For mercurial 1.7 set backward comapatibility with format
324 dotencode_disable = RhodeCodeUi()
324 dotencode_disable = RhodeCodeUi()
325 dotencode_disable.ui_section = 'format'
325 dotencode_disable.ui_section = 'format'
326 dotencode_disable.ui_key = 'dotencode'
326 dotencode_disable.ui_key = 'dotencode'
327 dotencode_disable.ui_value = 'false'
327 dotencode_disable.ui_value = 'false'
328
328
329 # enable largefiles
329 # enable largefiles
330 largefiles = RhodeCodeUi()
330 largefiles = RhodeCodeUi()
331 largefiles.ui_section = 'extensions'
331 largefiles.ui_section = 'extensions'
332 largefiles.ui_key = 'largefiles'
332 largefiles.ui_key = 'largefiles'
333 largefiles.ui_value = ''
333 largefiles.ui_value = ''
334
334
335 self.sa.add(hooks1)
335 self.sa.add(hooks1)
336 self.sa.add(hooks2)
336 self.sa.add(hooks2)
337 self.sa.add(hooks3)
337 self.sa.add(hooks3)
338 self.sa.add(hooks4)
338 self.sa.add(hooks4)
339 self.sa.add(largefiles)
339 self.sa.add(largefiles)
340
340
341 def create_ldap_options(self, skip_existing=False):
341 def create_ldap_options(self, skip_existing=False):
342 """Creates ldap settings"""
342 """Creates ldap settings"""
343
343
344 for k, v in [('ldap_active', 'false'), ('ldap_host', ''),
344 for k, v in [('ldap_active', 'false'), ('ldap_host', ''),
345 ('ldap_port', '389'), ('ldap_tls_kind', 'PLAIN'),
345 ('ldap_port', '389'), ('ldap_tls_kind', 'PLAIN'),
346 ('ldap_tls_reqcert', ''), ('ldap_dn_user', ''),
346 ('ldap_tls_reqcert', ''), ('ldap_dn_user', ''),
347 ('ldap_dn_pass', ''), ('ldap_base_dn', ''),
347 ('ldap_dn_pass', ''), ('ldap_base_dn', ''),
348 ('ldap_filter', ''), ('ldap_search_scope', ''),
348 ('ldap_filter', ''), ('ldap_search_scope', ''),
349 ('ldap_attr_login', ''), ('ldap_attr_firstname', ''),
349 ('ldap_attr_login', ''), ('ldap_attr_firstname', ''),
350 ('ldap_attr_lastname', ''), ('ldap_attr_email', '')]:
350 ('ldap_attr_lastname', ''), ('ldap_attr_email', '')]:
351
351
352 if skip_existing and RhodeCodeSetting.get_by_name(k) != None:
352 if skip_existing and RhodeCodeSetting.get_by_name(k) != None:
353 log.debug('Skipping option %s' % k)
353 log.debug('Skipping option %s' % k)
354 continue
354 continue
355 setting = RhodeCodeSetting(k, v)
355 setting = RhodeCodeSetting(k, v)
356 self.sa.add(setting)
356 self.sa.add(setting)
357
357
358 def fixup_groups(self):
358 def fixup_groups(self):
359 def_usr = User.get_by_username('default')
359 def_usr = User.get_by_username('default')
360 for g in RepoGroup.query().all():
360 for g in RepoGroup.query().all():
361 g.group_name = g.get_new_name(g.name)
361 g.group_name = g.get_new_name(g.name)
362 self.sa.add(g)
362 self.sa.add(g)
363 # get default perm
363 # get default perm
364 default = UserRepoGroupToPerm.query()\
364 default = UserRepoGroupToPerm.query()\
365 .filter(UserRepoGroupToPerm.group == g)\
365 .filter(UserRepoGroupToPerm.group == g)\
366 .filter(UserRepoGroupToPerm.user == def_usr)\
366 .filter(UserRepoGroupToPerm.user == def_usr)\
367 .scalar()
367 .scalar()
368
368
369 if default is None:
369 if default is None:
370 log.debug('missing default permission for group %s adding' % g)
370 log.debug('missing default permission for group %s adding' % g)
371 ReposGroupModel()._create_default_perms(g)
371 ReposGroupModel()._create_default_perms(g)
372
372
373 def config_prompt(self, test_repo_path='', retries=3):
373 def config_prompt(self, test_repo_path='', retries=3):
374 if retries == 3:
374 if retries == 3:
375 log.info('Setting up repositories config')
375 log.info('Setting up repositories config')
376
376
377 if not self.tests and not test_repo_path:
377 if not self.tests and not test_repo_path:
378 path = raw_input(
378 path = raw_input(
379 'Enter a valid path to store repositories. '
379 'Enter a valid path to store repositories. '
380 'All repositories in that path will be added automatically:'
380 'All repositories in that path will be added automatically:'
381 )
381 )
382 else:
382 else:
383 path = test_repo_path
383 path = test_repo_path
384 path_ok = True
384 path_ok = True
385
385
386 # check proper dir
386 # check proper dir
387 if not os.path.isdir(path):
387 if not os.path.isdir(path):
388 path_ok = False
388 path_ok = False
389 log.error('Given path %s is not a valid directory' % path)
389 log.error('Given path %s is not a valid directory' % path)
390
390
391 # check write access
391 # check write access
392 if not os.access(path, os.W_OK) and path_ok:
392 if not os.access(path, os.W_OK) and path_ok:
393 path_ok = False
393 path_ok = False
394 log.error('No write permission to given path %s' % path)
394 log.error('No write permission to given path %s' % path)
395
395
396 if retries == 0:
396 if retries == 0:
397 sys.exit('max retries reached')
397 sys.exit('max retries reached')
398 if path_ok is False:
398 if path_ok is False:
399 retries -= 1
399 retries -= 1
400 return self.config_prompt(test_repo_path, retries)
400 return self.config_prompt(test_repo_path, retries)
401
401
402 return path
402 return path
403
403
404 def create_settings(self, path):
404 def create_settings(self, path):
405
405
406 self.create_ui_settings()
406 self.create_ui_settings()
407
407
408 #HG UI OPTIONS
408 #HG UI OPTIONS
409 web1 = RhodeCodeUi()
409 web1 = RhodeCodeUi()
410 web1.ui_section = 'web'
410 web1.ui_section = 'web'
411 web1.ui_key = 'push_ssl'
411 web1.ui_key = 'push_ssl'
412 web1.ui_value = 'false'
412 web1.ui_value = 'false'
413
413
414 web2 = RhodeCodeUi()
414 web2 = RhodeCodeUi()
415 web2.ui_section = 'web'
415 web2.ui_section = 'web'
416 web2.ui_key = 'allow_archive'
416 web2.ui_key = 'allow_archive'
417 web2.ui_value = 'gz zip bz2'
417 web2.ui_value = 'gz zip bz2'
418
418
419 web3 = RhodeCodeUi()
419 web3 = RhodeCodeUi()
420 web3.ui_section = 'web'
420 web3.ui_section = 'web'
421 web3.ui_key = 'allow_push'
421 web3.ui_key = 'allow_push'
422 web3.ui_value = '*'
422 web3.ui_value = '*'
423
423
424 web4 = RhodeCodeUi()
424 web4 = RhodeCodeUi()
425 web4.ui_section = 'web'
425 web4.ui_section = 'web'
426 web4.ui_key = 'baseurl'
426 web4.ui_key = 'baseurl'
427 web4.ui_value = '/'
427 web4.ui_value = '/'
428
428
429 paths = RhodeCodeUi()
429 paths = RhodeCodeUi()
430 paths.ui_section = 'paths'
430 paths.ui_section = 'paths'
431 paths.ui_key = '/'
431 paths.ui_key = '/'
432 paths.ui_value = path
432 paths.ui_value = path
433
433
434 hgsettings1 = RhodeCodeSetting('realm', 'RhodeCode authentication')
434 hgsettings1 = RhodeCodeSetting('realm', 'RhodeCode authentication')
435 hgsettings2 = RhodeCodeSetting('title', 'RhodeCode')
435 hgsettings2 = RhodeCodeSetting('title', 'RhodeCode')
436 hgsettings3 = RhodeCodeSetting('ga_code', '')
436 hgsettings3 = RhodeCodeSetting('ga_code', '')
437
437
438 self.sa.add(web1)
438 self.sa.add(web1)
439 self.sa.add(web2)
439 self.sa.add(web2)
440 self.sa.add(web3)
440 self.sa.add(web3)
441 self.sa.add(web4)
441 self.sa.add(web4)
442 self.sa.add(paths)
442 self.sa.add(paths)
443 self.sa.add(hgsettings1)
443 self.sa.add(hgsettings1)
444 self.sa.add(hgsettings2)
444 self.sa.add(hgsettings2)
445 self.sa.add(hgsettings3)
445 self.sa.add(hgsettings3)
446
446
447 self.create_ldap_options()
447 self.create_ldap_options()
448
448
449 log.info('created ui config')
449 log.info('created ui config')
450
450
451 def create_user(self, username, password, email='', admin=False):
451 def create_user(self, username, password, email='', admin=False):
452 log.info('creating user %s' % username)
452 log.info('creating user %s' % username)
453 UserModel().create_or_update(username, password, email,
453 UserModel().create_or_update(username, password, email,
454 name='RhodeCode', lastname='Admin',
454 name='RhodeCode', lastname='Admin',
455 active=True, admin=admin)
455 active=True, admin=admin)
456
456
457 def create_default_user(self):
457 def create_default_user(self):
458 log.info('creating default user')
458 log.info('creating default user')
459 # create default user for handling default permissions.
459 # create default user for handling default permissions.
460 UserModel().create_or_update(username='default',
460 UserModel().create_or_update(username='default',
461 password=str(uuid.uuid1())[:8],
461 password=str(uuid.uuid1())[:8],
462 email='anonymous@rhodecode.org',
462 email='anonymous@rhodecode.org',
463 name='Anonymous', lastname='User')
463 name='Anonymous', lastname='User')
464
464
465 def create_permissions(self):
465 def create_permissions(self):
466 # module.(access|create|change|delete)_[name]
466 # module.(access|create|change|delete)_[name]
467 # module.(none|read|write|admin)
467 # module.(none|read|write|admin)
468 perms = [
468 perms = [
469 ('repository.none', 'Repository no access'),
469 ('repository.none', 'Repository no access'),
470 ('repository.read', 'Repository read access'),
470 ('repository.read', 'Repository read access'),
471 ('repository.write', 'Repository write access'),
471 ('repository.write', 'Repository write access'),
472 ('repository.admin', 'Repository admin access'),
472 ('repository.admin', 'Repository admin access'),
473
473
474 ('group.none', 'Repositories Group no access'),
474 ('group.none', 'Repositories Group no access'),
475 ('group.read', 'Repositories Group read access'),
475 ('group.read', 'Repositories Group read access'),
476 ('group.write', 'Repositories Group write access'),
476 ('group.write', 'Repositories Group write access'),
477 ('group.admin', 'Repositories Group admin access'),
477 ('group.admin', 'Repositories Group admin access'),
478
478
479 ('hg.admin', 'Hg Administrator'),
479 ('hg.admin', 'Hg Administrator'),
480 ('hg.create.repository', 'Repository create'),
480 ('hg.create.repository', 'Repository create'),
481 ('hg.create.none', 'Repository creation disabled'),
481 ('hg.create.none', 'Repository creation disabled'),
482 ('hg.register.none', 'Register disabled'),
482 ('hg.register.none', 'Register disabled'),
483 ('hg.register.manual_activate', 'Register new user with RhodeCode '
483 ('hg.register.manual_activate', 'Register new user with RhodeCode '
484 'without manual activation'),
484 'without manual activation'),
485
485
486 ('hg.register.auto_activate', 'Register new user with RhodeCode '
486 ('hg.register.auto_activate', 'Register new user with RhodeCode '
487 'without auto activation'),
487 'without auto activation'),
488 ]
488 ]
489
489
490 for p in perms:
490 for p in perms:
491 if not Permission.get_by_key(p[0]):
491 if not Permission.get_by_key(p[0]):
492 new_perm = Permission()
492 new_perm = Permission()
493 new_perm.permission_name = p[0]
493 new_perm.permission_name = p[0]
494 new_perm.permission_longname = p[1]
494 new_perm.permission_longname = p[1]
495 self.sa.add(new_perm)
495 self.sa.add(new_perm)
496
496
497 def populate_default_permissions(self):
497 def populate_default_permissions(self):
498 log.info('creating default user permissions')
498 log.info('creating default user permissions')
499
499
500 default_user = self.sa.query(User)\
500 default_user = self.sa.query(User)\
501 .filter(User.username == 'default').scalar()
501 .filter(User.username == 'default').scalar()
502
502
503 reg_perm = UserToPerm()
503 reg_perm = UserToPerm()
504 reg_perm.user = default_user
504 reg_perm.user = default_user
505 reg_perm.permission = self.sa.query(Permission)\
505 reg_perm.permission = self.sa.query(Permission)\
506 .filter(Permission.permission_name == 'hg.register.manual_activate')\
506 .filter(Permission.permission_name == 'hg.register.manual_activate')\
507 .scalar()
507 .scalar()
508
508
509 create_repo_perm = UserToPerm()
509 create_repo_perm = UserToPerm()
510 create_repo_perm.user = default_user
510 create_repo_perm.user = default_user
511 create_repo_perm.permission = self.sa.query(Permission)\
511 create_repo_perm.permission = self.sa.query(Permission)\
512 .filter(Permission.permission_name == 'hg.create.repository')\
512 .filter(Permission.permission_name == 'hg.create.repository')\
513 .scalar()
513 .scalar()
514
514
515 default_repo_perm = UserToPerm()
515 default_repo_perm = UserToPerm()
516 default_repo_perm.user = default_user
516 default_repo_perm.user = default_user
517 default_repo_perm.permission = self.sa.query(Permission)\
517 default_repo_perm.permission = self.sa.query(Permission)\
518 .filter(Permission.permission_name == 'repository.read')\
518 .filter(Permission.permission_name == 'repository.read')\
519 .scalar()
519 .scalar()
520
520
521 self.sa.add(reg_perm)
521 self.sa.add(reg_perm)
522 self.sa.add(create_repo_perm)
522 self.sa.add(create_repo_perm)
523 self.sa.add(default_repo_perm)
523 self.sa.add(default_repo_perm)
General Comments 0
You need to be logged in to leave comments. Login now