Show More
@@ -0,0 +1,24 b'' | |||||
|
1 | .. _user-admin-tasks: | |||
|
2 | ||||
|
3 | Common Admin Tasks for Users | |||
|
4 | ---------------------------- | |||
|
5 | ||||
|
6 | ||||
|
7 | Manually Set Personal Repository Group | |||
|
8 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | |||
|
9 | ||||
|
10 | Here is how to set a repository group as personal for a user using ishell. | |||
|
11 | ||||
|
12 | ||||
|
13 | .. code-block:: bash | |||
|
14 | ||||
|
15 | # starts the ishell interactive prompt | |||
|
16 | $ rccontrol ishell enterprise-1 | |||
|
17 | ||||
|
18 | .. code-block:: python | |||
|
19 | ||||
|
20 | In [1]: repo_group = RepoGroup.get_by_group_name('some_group_name') | |||
|
21 | In [2]: user = User.get_by_username('some_user') | |||
|
22 | In [3]: repo_group.user = user | |||
|
23 | In [4]: repo_group.personal = True | |||
|
24 | In [5]: Session().add(repo_group);Session().commit() |
@@ -1,23 +1,24 b'' | |||||
1 | .. _user-admin-set: |
|
1 | .. _user-admin-set: | |
2 |
|
2 | |||
3 | User Administration |
|
3 | User Administration | |
4 | =================== |
|
4 | =================== | |
5 |
|
5 | |||
6 | |RCE| enables you to define permissions for the following entities within the |
|
6 | |RCE| enables you to define permissions for the following entities within the | |
7 | system; **users**, **user groups**, **repositories**, **repository groups**. |
|
7 | system; **users**, **user groups**, **repositories**, **repository groups**. | |
8 |
|
8 | |||
9 | Within each one of these entities you can set default settings, |
|
9 | Within each one of these entities you can set default settings, | |
10 | and then all users or |repos| inherit those default permission settings |
|
10 | and then all users or |repos| inherit those default permission settings | |
11 | unless individually defined. Each of these entities can have the following |
|
11 | unless individually defined. Each of these entities can have the following | |
12 | permissions applied to it; |perm|. |
|
12 | permissions applied to it; |perm|. | |
13 |
|
13 | |||
14 | .. toctree:: |
|
14 | .. toctree:: | |
15 |
|
15 | |||
16 | public-access |
|
16 | user_admin/public-access | |
17 | default-user-perms |
|
17 | user_admin/default-user-perms | |
18 | adding-anonymous-user |
|
18 | user_admin/adding-anonymous-user | |
19 | adding-new-user |
|
19 | user_admin/adding-new-user | |
20 | setting-default-permissions |
|
20 | user_admin/setting-default-permissions | |
21 | setting-usergroup-permissions |
|
21 | user_admin/setting-usergroup-permissions | |
|
22 | user_admin/user-admin-tasks | |||
22 |
|
23 | |||
23 | .. |perm| replace:: **None**, **Read**, **Write**, or **Admin** No newline at end of file |
|
24 | .. |perm| replace:: **None**, **Read**, **Write**, or **Admin** |
1 | NO CONTENT: file renamed from docs/admin/adding-anonymous-user.rst to docs/admin/user_admin/adding-anonymous-user.rst |
|
NO CONTENT: file renamed from docs/admin/adding-anonymous-user.rst to docs/admin/user_admin/adding-anonymous-user.rst |
1 | NO CONTENT: file renamed from docs/admin/adding-new-user.rst to docs/admin/user_admin/adding-new-user.rst |
|
NO CONTENT: file renamed from docs/admin/adding-new-user.rst to docs/admin/user_admin/adding-new-user.rst |
1 | NO CONTENT: file renamed from docs/admin/default-user-perms.rst to docs/admin/user_admin/default-user-perms.rst |
|
NO CONTENT: file renamed from docs/admin/default-user-perms.rst to docs/admin/user_admin/default-user-perms.rst |
1 | NO CONTENT: file renamed from docs/admin/public-access.rst to docs/admin/user_admin/public-access.rst |
|
NO CONTENT: file renamed from docs/admin/public-access.rst to docs/admin/user_admin/public-access.rst |
1 | NO CONTENT: file renamed from docs/admin/setting-default-permissions.rst to docs/admin/user_admin/setting-default-permissions.rst |
|
NO CONTENT: file renamed from docs/admin/setting-default-permissions.rst to docs/admin/user_admin/setting-default-permissions.rst |
1 | NO CONTENT: file renamed from docs/admin/setting-usergroup-permissions.rst to docs/admin/user_admin/setting-usergroup-permissions.rst |
|
NO CONTENT: file renamed from docs/admin/setting-usergroup-permissions.rst to docs/admin/user_admin/setting-usergroup-permissions.rst |
@@ -1,87 +1,87 b'' | |||||
1 | |RCE| |
|
1 | |RCE| | |
2 | ===== |
|
2 | ===== | |
3 |
|
3 | |||
4 | |RCE| is a high-performance source code management and collaboration system. |
|
4 | |RCE| is a high-performance source code management and collaboration system. | |
5 | It enables you to develop projects securely behind the firewall while |
|
5 | It enables you to develop projects securely behind the firewall while | |
6 | providing collaboration tools that work with |git|, |hg|, |
|
6 | providing collaboration tools that work with |git|, |hg|, | |
7 | and |svn| |repos|. The user interface allows you to create, edit, |
|
7 | and |svn| |repos|. The user interface allows you to create, edit, | |
8 | and commit files and |repos| while managing their security permissions. |
|
8 | and commit files and |repos| while managing their security permissions. | |
9 |
|
9 | |||
10 | |RCE| provides the following features: |
|
10 | |RCE| provides the following features: | |
11 |
|
11 | |||
12 | * Source code management. |
|
12 | * Source code management. | |
13 | * Extended permissions management. |
|
13 | * Extended permissions management. | |
14 | * Integrated code collaboration tools. |
|
14 | * Integrated code collaboration tools. | |
15 | * Integrated code review and notifications. |
|
15 | * Integrated code review and notifications. | |
16 | * Scalability provided by multi-node setup. |
|
16 | * Scalability provided by multi-node setup. | |
17 | * Fully programmable automation API. |
|
17 | * Fully programmable automation API. | |
18 | * Web-based hook management. |
|
18 | * Web-based hook management. | |
19 | * Native |svn| support. |
|
19 | * Native |svn| support. | |
20 | * Migration from existing databases. |
|
20 | * Migration from existing databases. | |
21 | * |RCE| SDK. |
|
21 | * |RCE| SDK. | |
22 | * Built-in analytics |
|
22 | * Built-in analytics | |
23 | * Built in integrations including: Slack, Webhooks (used for Jenkins/TeamCity and other CIs), Jira, Redmine, Hipchat |
|
23 | * Built in integrations including: Slack, Webhooks (used for Jenkins/TeamCity and other CIs), Jira, Redmine, Hipchat | |
24 | * Pluggable authentication system. |
|
24 | * Pluggable authentication system. | |
25 | * Support for AD, |LDAP|, Crowd, CAS, PAM. |
|
25 | * Support for AD, |LDAP|, Crowd, CAS, PAM. | |
26 | * Support for external authentication via Oauth Google, Github, Bitbucket, Twitter. |
|
26 | * Support for external authentication via Oauth Google, Github, Bitbucket, Twitter. | |
27 | * Debug modes of operation. |
|
27 | * Debug modes of operation. | |
28 | * Private and public gists. |
|
28 | * Private and public gists. | |
29 | * Gists with limited lifetimes and within instance only sharing. |
|
29 | * Gists with limited lifetimes and within instance only sharing. | |
30 | * Fully integrated code search function. |
|
30 | * Fully integrated code search function. | |
31 | * Always on SSL connectivity. |
|
31 | * Always on SSL connectivity. | |
32 |
|
32 | |||
33 | .. only:: html |
|
33 | .. only:: html | |
34 |
|
34 | |||
35 | Table of Contents |
|
35 | Table of Contents | |
36 | ----------------- |
|
36 | ----------------- | |
37 |
|
37 | |||
38 | .. toctree:: |
|
38 | .. toctree:: | |
39 | :maxdepth: 1 |
|
39 | :maxdepth: 1 | |
40 | :caption: Admin Documentation |
|
40 | :caption: Admin Documentation | |
41 |
|
41 | |||
42 | install/quick-start |
|
42 | install/quick-start | |
43 | install/install-database |
|
43 | install/install-database | |
44 | install/install-steps |
|
44 | install/install-steps | |
45 | admin/system-overview |
|
45 | admin/system-overview | |
46 | nix/default-env |
|
46 | nix/default-env | |
47 | admin/system-admin |
|
47 | admin/system-admin | |
48 | admin/user-admin |
|
48 | admin/user-admin | |
49 | admin/setting-repo-perms |
|
49 | admin/setting-repo-perms | |
50 | admin/security-tips |
|
50 | admin/security-tips | |
51 | auth/auth |
|
51 | auth/auth | |
52 | issue-trackers/issue-trackers |
|
52 | issue-trackers/issue-trackers | |
53 | admin/lab-settings |
|
53 | admin/lab-settings | |
54 |
|
54 | |||
55 | .. toctree:: |
|
55 | .. toctree:: | |
56 | :maxdepth: 1 |
|
56 | :maxdepth: 1 | |
57 | :caption: Feature Documentation |
|
57 | :caption: Feature Documentation | |
58 |
|
58 | |||
59 | collaboration/collaboration |
|
59 | collaboration/collaboration | |
60 | collaboration/review-notifications |
|
60 | collaboration/review-notifications | |
61 | collaboration/pull-requests |
|
61 | collaboration/pull-requests | |
62 | code-review/code-review |
|
62 | code-review/code-review | |
63 | integrations/integrations |
|
63 | integrations/integrations | |
64 |
|
64 | |||
65 | .. toctree:: |
|
65 | .. toctree:: | |
66 | :maxdepth: 1 |
|
66 | :maxdepth: 1 | |
|
67 | :caption: User Documentation | |||
|
68 | ||||
|
69 | usage/basic-usage | |||
|
70 | tutorials/tutorials | |||
|
71 | ||||
|
72 | .. toctree:: | |||
|
73 | :maxdepth: 1 | |||
67 | :caption: Developer Documentation |
|
74 | :caption: Developer Documentation | |
68 |
|
75 | |||
69 | api/api |
|
76 | api/api | |
70 | tools/rhodecode-tools |
|
77 | tools/rhodecode-tools | |
71 | extensions/extensions-hooks |
|
78 | extensions/extensions-hooks | |
72 | contributing/contributing |
|
79 | contributing/contributing | |
73 |
|
80 | |||
74 | .. toctree:: |
|
81 | .. toctree:: | |
75 | :maxdepth: 1 |
|
82 | :maxdepth: 1 | |
76 | :caption: User Documentation |
|
|||
77 |
|
||||
78 | usage/basic-usage |
|
|||
79 | tutorials/tutorials |
|
|||
80 |
|
||||
81 | .. toctree:: |
|
|||
82 | :maxdepth: 1 |
|
|||
83 | :caption: About |
|
83 | :caption: About | |
84 |
|
84 | |||
85 | known-issues/known-issues |
|
85 | known-issues/known-issues | |
86 | release-notes/release-notes |
|
86 | release-notes/release-notes | |
87 | admin/glossary |
|
87 | admin/glossary |
@@ -1,1266 +1,1265 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2016-2019 RhodeCode GmbH |
|
3 | # Copyright (C) 2016-2019 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | import logging |
|
21 | import logging | |
22 | import datetime |
|
22 | import datetime | |
23 | import formencode |
|
23 | import formencode | |
24 | import formencode.htmlfill |
|
24 | import formencode.htmlfill | |
25 |
|
25 | |||
26 | from pyramid.httpexceptions import HTTPFound |
|
26 | from pyramid.httpexceptions import HTTPFound | |
27 | from pyramid.view import view_config |
|
27 | from pyramid.view import view_config | |
28 | from pyramid.renderers import render |
|
28 | from pyramid.renderers import render | |
29 | from pyramid.response import Response |
|
29 | from pyramid.response import Response | |
30 |
|
30 | |||
31 | from rhodecode import events |
|
31 | from rhodecode import events | |
32 | from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView |
|
32 | from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView | |
33 | from rhodecode.apps.ssh_support import SshKeyFileChangeEvent |
|
33 | from rhodecode.apps.ssh_support import SshKeyFileChangeEvent | |
34 | from rhodecode.authentication.plugins import auth_rhodecode |
|
34 | from rhodecode.authentication.plugins import auth_rhodecode | |
35 | from rhodecode.events import trigger |
|
35 | from rhodecode.events import trigger | |
36 | from rhodecode.model.db import true |
|
36 | from rhodecode.model.db import true | |
37 |
|
37 | |||
38 | from rhodecode.lib import audit_logger, rc_cache |
|
38 | from rhodecode.lib import audit_logger, rc_cache | |
39 | from rhodecode.lib.exceptions import ( |
|
39 | from rhodecode.lib.exceptions import ( | |
40 | UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException, |
|
40 | UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException, | |
41 | UserOwnsUserGroupsException, DefaultUserException) |
|
41 | UserOwnsUserGroupsException, DefaultUserException) | |
42 | from rhodecode.lib.ext_json import json |
|
42 | from rhodecode.lib.ext_json import json | |
43 | from rhodecode.lib.auth import ( |
|
43 | from rhodecode.lib.auth import ( | |
44 | LoginRequired, HasPermissionAllDecorator, CSRFRequired) |
|
44 | LoginRequired, HasPermissionAllDecorator, CSRFRequired) | |
45 | from rhodecode.lib import helpers as h |
|
45 | from rhodecode.lib import helpers as h | |
46 | from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict |
|
46 | from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict | |
47 | from rhodecode.model.auth_token import AuthTokenModel |
|
47 | from rhodecode.model.auth_token import AuthTokenModel | |
48 | from rhodecode.model.forms import ( |
|
48 | from rhodecode.model.forms import ( | |
49 | UserForm, UserIndividualPermissionsForm, UserPermissionsForm, |
|
49 | UserForm, UserIndividualPermissionsForm, UserPermissionsForm, | |
50 | UserExtraEmailForm, UserExtraIpForm) |
|
50 | UserExtraEmailForm, UserExtraIpForm) | |
51 | from rhodecode.model.permission import PermissionModel |
|
51 | from rhodecode.model.permission import PermissionModel | |
52 | from rhodecode.model.repo_group import RepoGroupModel |
|
52 | from rhodecode.model.repo_group import RepoGroupModel | |
53 | from rhodecode.model.ssh_key import SshKeyModel |
|
53 | from rhodecode.model.ssh_key import SshKeyModel | |
54 | from rhodecode.model.user import UserModel |
|
54 | from rhodecode.model.user import UserModel | |
55 | from rhodecode.model.user_group import UserGroupModel |
|
55 | from rhodecode.model.user_group import UserGroupModel | |
56 | from rhodecode.model.db import ( |
|
56 | from rhodecode.model.db import ( | |
57 | or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap, |
|
57 | or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap, | |
58 | UserApiKeys, UserSshKeys, RepoGroup) |
|
58 | UserApiKeys, UserSshKeys, RepoGroup) | |
59 | from rhodecode.model.meta import Session |
|
59 | from rhodecode.model.meta import Session | |
60 |
|
60 | |||
61 | log = logging.getLogger(__name__) |
|
61 | log = logging.getLogger(__name__) | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | class AdminUsersView(BaseAppView, DataGridAppView): |
|
64 | class AdminUsersView(BaseAppView, DataGridAppView): | |
65 |
|
65 | |||
66 | def load_default_context(self): |
|
66 | def load_default_context(self): | |
67 | c = self._get_local_tmpl_context() |
|
67 | c = self._get_local_tmpl_context() | |
68 | return c |
|
68 | return c | |
69 |
|
69 | |||
70 | @LoginRequired() |
|
70 | @LoginRequired() | |
71 | @HasPermissionAllDecorator('hg.admin') |
|
71 | @HasPermissionAllDecorator('hg.admin') | |
72 | @view_config( |
|
72 | @view_config( | |
73 | route_name='users', request_method='GET', |
|
73 | route_name='users', request_method='GET', | |
74 | renderer='rhodecode:templates/admin/users/users.mako') |
|
74 | renderer='rhodecode:templates/admin/users/users.mako') | |
75 | def users_list(self): |
|
75 | def users_list(self): | |
76 | c = self.load_default_context() |
|
76 | c = self.load_default_context() | |
77 | return self._get_template_context(c) |
|
77 | return self._get_template_context(c) | |
78 |
|
78 | |||
79 | @LoginRequired() |
|
79 | @LoginRequired() | |
80 | @HasPermissionAllDecorator('hg.admin') |
|
80 | @HasPermissionAllDecorator('hg.admin') | |
81 | @view_config( |
|
81 | @view_config( | |
82 | # renderer defined below |
|
82 | # renderer defined below | |
83 | route_name='users_data', request_method='GET', |
|
83 | route_name='users_data', request_method='GET', | |
84 | renderer='json_ext', xhr=True) |
|
84 | renderer='json_ext', xhr=True) | |
85 | def users_list_data(self): |
|
85 | def users_list_data(self): | |
86 | self.load_default_context() |
|
86 | self.load_default_context() | |
87 | column_map = { |
|
87 | column_map = { | |
88 | 'first_name': 'name', |
|
88 | 'first_name': 'name', | |
89 | 'last_name': 'lastname', |
|
89 | 'last_name': 'lastname', | |
90 | } |
|
90 | } | |
91 | draw, start, limit = self._extract_chunk(self.request) |
|
91 | draw, start, limit = self._extract_chunk(self.request) | |
92 | search_q, order_by, order_dir = self._extract_ordering( |
|
92 | search_q, order_by, order_dir = self._extract_ordering( | |
93 | self.request, column_map=column_map) |
|
93 | self.request, column_map=column_map) | |
94 | _render = self.request.get_partial_renderer( |
|
94 | _render = self.request.get_partial_renderer( | |
95 | 'rhodecode:templates/data_table/_dt_elements.mako') |
|
95 | 'rhodecode:templates/data_table/_dt_elements.mako') | |
96 |
|
96 | |||
97 | def user_actions(user_id, username): |
|
97 | def user_actions(user_id, username): | |
98 | return _render("user_actions", user_id, username) |
|
98 | return _render("user_actions", user_id, username) | |
99 |
|
99 | |||
100 | users_data_total_count = User.query()\ |
|
100 | users_data_total_count = User.query()\ | |
101 | .filter(User.username != User.DEFAULT_USER) \ |
|
101 | .filter(User.username != User.DEFAULT_USER) \ | |
102 | .count() |
|
102 | .count() | |
103 |
|
103 | |||
104 | users_data_total_inactive_count = User.query()\ |
|
104 | users_data_total_inactive_count = User.query()\ | |
105 | .filter(User.username != User.DEFAULT_USER) \ |
|
105 | .filter(User.username != User.DEFAULT_USER) \ | |
106 | .filter(User.active != true())\ |
|
106 | .filter(User.active != true())\ | |
107 | .count() |
|
107 | .count() | |
108 |
|
108 | |||
109 | # json generate |
|
109 | # json generate | |
110 | base_q = User.query().filter(User.username != User.DEFAULT_USER) |
|
110 | base_q = User.query().filter(User.username != User.DEFAULT_USER) | |
111 | base_inactive_q = base_q.filter(User.active != true()) |
|
111 | base_inactive_q = base_q.filter(User.active != true()) | |
112 |
|
112 | |||
113 | if search_q: |
|
113 | if search_q: | |
114 | like_expression = u'%{}%'.format(safe_unicode(search_q)) |
|
114 | like_expression = u'%{}%'.format(safe_unicode(search_q)) | |
115 | base_q = base_q.filter(or_( |
|
115 | base_q = base_q.filter(or_( | |
116 | User.username.ilike(like_expression), |
|
116 | User.username.ilike(like_expression), | |
117 | User._email.ilike(like_expression), |
|
117 | User._email.ilike(like_expression), | |
118 | User.name.ilike(like_expression), |
|
118 | User.name.ilike(like_expression), | |
119 | User.lastname.ilike(like_expression), |
|
119 | User.lastname.ilike(like_expression), | |
120 | )) |
|
120 | )) | |
121 | base_inactive_q = base_q.filter(User.active != true()) |
|
121 | base_inactive_q = base_q.filter(User.active != true()) | |
122 |
|
122 | |||
123 | users_data_total_filtered_count = base_q.count() |
|
123 | users_data_total_filtered_count = base_q.count() | |
124 | users_data_total_filtered_inactive_count = base_inactive_q.count() |
|
124 | users_data_total_filtered_inactive_count = base_inactive_q.count() | |
125 |
|
125 | |||
126 | sort_col = getattr(User, order_by, None) |
|
126 | sort_col = getattr(User, order_by, None) | |
127 | if sort_col: |
|
127 | if sort_col: | |
128 | if order_dir == 'asc': |
|
128 | if order_dir == 'asc': | |
129 | # handle null values properly to order by NULL last |
|
129 | # handle null values properly to order by NULL last | |
130 | if order_by in ['last_activity']: |
|
130 | if order_by in ['last_activity']: | |
131 | sort_col = coalesce(sort_col, datetime.date.max) |
|
131 | sort_col = coalesce(sort_col, datetime.date.max) | |
132 | sort_col = sort_col.asc() |
|
132 | sort_col = sort_col.asc() | |
133 | else: |
|
133 | else: | |
134 | # handle null values properly to order by NULL last |
|
134 | # handle null values properly to order by NULL last | |
135 | if order_by in ['last_activity']: |
|
135 | if order_by in ['last_activity']: | |
136 | sort_col = coalesce(sort_col, datetime.date.min) |
|
136 | sort_col = coalesce(sort_col, datetime.date.min) | |
137 | sort_col = sort_col.desc() |
|
137 | sort_col = sort_col.desc() | |
138 |
|
138 | |||
139 | base_q = base_q.order_by(sort_col) |
|
139 | base_q = base_q.order_by(sort_col) | |
140 | base_q = base_q.offset(start).limit(limit) |
|
140 | base_q = base_q.offset(start).limit(limit) | |
141 |
|
141 | |||
142 | users_list = base_q.all() |
|
142 | users_list = base_q.all() | |
143 |
|
143 | |||
144 | users_data = [] |
|
144 | users_data = [] | |
145 | for user in users_list: |
|
145 | for user in users_list: | |
146 | users_data.append({ |
|
146 | users_data.append({ | |
147 | "username": h.gravatar_with_user(self.request, user.username), |
|
147 | "username": h.gravatar_with_user(self.request, user.username), | |
148 | "email": user.email, |
|
148 | "email": user.email, | |
149 | "first_name": user.first_name, |
|
149 | "first_name": user.first_name, | |
150 | "last_name": user.last_name, |
|
150 | "last_name": user.last_name, | |
151 | "last_login": h.format_date(user.last_login), |
|
151 | "last_login": h.format_date(user.last_login), | |
152 | "last_activity": h.format_date(user.last_activity), |
|
152 | "last_activity": h.format_date(user.last_activity), | |
153 | "active": h.bool2icon(user.active), |
|
153 | "active": h.bool2icon(user.active), | |
154 | "active_raw": user.active, |
|
154 | "active_raw": user.active, | |
155 | "admin": h.bool2icon(user.admin), |
|
155 | "admin": h.bool2icon(user.admin), | |
156 | "extern_type": user.extern_type, |
|
156 | "extern_type": user.extern_type, | |
157 | "extern_name": user.extern_name, |
|
157 | "extern_name": user.extern_name, | |
158 | "action": user_actions(user.user_id, user.username), |
|
158 | "action": user_actions(user.user_id, user.username), | |
159 | }) |
|
159 | }) | |
160 | data = ({ |
|
160 | data = ({ | |
161 | 'draw': draw, |
|
161 | 'draw': draw, | |
162 | 'data': users_data, |
|
162 | 'data': users_data, | |
163 | 'recordsTotal': users_data_total_count, |
|
163 | 'recordsTotal': users_data_total_count, | |
164 | 'recordsFiltered': users_data_total_filtered_count, |
|
164 | 'recordsFiltered': users_data_total_filtered_count, | |
165 | 'recordsTotalInactive': users_data_total_inactive_count, |
|
165 | 'recordsTotalInactive': users_data_total_inactive_count, | |
166 | 'recordsFilteredInactive': users_data_total_filtered_inactive_count |
|
166 | 'recordsFilteredInactive': users_data_total_filtered_inactive_count | |
167 | }) |
|
167 | }) | |
168 |
|
168 | |||
169 | return data |
|
169 | return data | |
170 |
|
170 | |||
171 | def _set_personal_repo_group_template_vars(self, c_obj): |
|
171 | def _set_personal_repo_group_template_vars(self, c_obj): | |
172 | DummyUser = AttributeDict({ |
|
172 | DummyUser = AttributeDict({ | |
173 | 'username': '${username}', |
|
173 | 'username': '${username}', | |
174 | 'user_id': '${user_id}', |
|
174 | 'user_id': '${user_id}', | |
175 | }) |
|
175 | }) | |
176 | c_obj.default_create_repo_group = RepoGroupModel() \ |
|
176 | c_obj.default_create_repo_group = RepoGroupModel() \ | |
177 | .get_default_create_personal_repo_group() |
|
177 | .get_default_create_personal_repo_group() | |
178 | c_obj.personal_repo_group_name = RepoGroupModel() \ |
|
178 | c_obj.personal_repo_group_name = RepoGroupModel() \ | |
179 | .get_personal_group_name(DummyUser) |
|
179 | .get_personal_group_name(DummyUser) | |
180 |
|
180 | |||
181 | @LoginRequired() |
|
181 | @LoginRequired() | |
182 | @HasPermissionAllDecorator('hg.admin') |
|
182 | @HasPermissionAllDecorator('hg.admin') | |
183 | @view_config( |
|
183 | @view_config( | |
184 | route_name='users_new', request_method='GET', |
|
184 | route_name='users_new', request_method='GET', | |
185 | renderer='rhodecode:templates/admin/users/user_add.mako') |
|
185 | renderer='rhodecode:templates/admin/users/user_add.mako') | |
186 | def users_new(self): |
|
186 | def users_new(self): | |
187 | _ = self.request.translate |
|
187 | _ = self.request.translate | |
188 | c = self.load_default_context() |
|
188 | c = self.load_default_context() | |
189 | c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid |
|
189 | c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid | |
190 | self._set_personal_repo_group_template_vars(c) |
|
190 | self._set_personal_repo_group_template_vars(c) | |
191 | return self._get_template_context(c) |
|
191 | return self._get_template_context(c) | |
192 |
|
192 | |||
193 | @LoginRequired() |
|
193 | @LoginRequired() | |
194 | @HasPermissionAllDecorator('hg.admin') |
|
194 | @HasPermissionAllDecorator('hg.admin') | |
195 | @CSRFRequired() |
|
195 | @CSRFRequired() | |
196 | @view_config( |
|
196 | @view_config( | |
197 | route_name='users_create', request_method='POST', |
|
197 | route_name='users_create', request_method='POST', | |
198 | renderer='rhodecode:templates/admin/users/user_add.mako') |
|
198 | renderer='rhodecode:templates/admin/users/user_add.mako') | |
199 | def users_create(self): |
|
199 | def users_create(self): | |
200 | _ = self.request.translate |
|
200 | _ = self.request.translate | |
201 | c = self.load_default_context() |
|
201 | c = self.load_default_context() | |
202 | c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid |
|
202 | c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.uid | |
203 | user_model = UserModel() |
|
203 | user_model = UserModel() | |
204 | user_form = UserForm(self.request.translate)() |
|
204 | user_form = UserForm(self.request.translate)() | |
205 | try: |
|
205 | try: | |
206 | form_result = user_form.to_python(dict(self.request.POST)) |
|
206 | form_result = user_form.to_python(dict(self.request.POST)) | |
207 | user = user_model.create(form_result) |
|
207 | user = user_model.create(form_result) | |
208 | Session().flush() |
|
208 | Session().flush() | |
209 | creation_data = user.get_api_data() |
|
209 | creation_data = user.get_api_data() | |
210 | username = form_result['username'] |
|
210 | username = form_result['username'] | |
211 |
|
211 | |||
212 | audit_logger.store_web( |
|
212 | audit_logger.store_web( | |
213 | 'user.create', action_data={'data': creation_data}, |
|
213 | 'user.create', action_data={'data': creation_data}, | |
214 | user=c.rhodecode_user) |
|
214 | user=c.rhodecode_user) | |
215 |
|
215 | |||
216 | user_link = h.link_to( |
|
216 | user_link = h.link_to( | |
217 | h.escape(username), |
|
217 | h.escape(username), | |
218 | h.route_path('user_edit', user_id=user.user_id)) |
|
218 | h.route_path('user_edit', user_id=user.user_id)) | |
219 | h.flash(h.literal(_('Created user %(user_link)s') |
|
219 | h.flash(h.literal(_('Created user %(user_link)s') | |
220 | % {'user_link': user_link}), category='success') |
|
220 | % {'user_link': user_link}), category='success') | |
221 | Session().commit() |
|
221 | Session().commit() | |
222 | except formencode.Invalid as errors: |
|
222 | except formencode.Invalid as errors: | |
223 | self._set_personal_repo_group_template_vars(c) |
|
223 | self._set_personal_repo_group_template_vars(c) | |
224 | data = render( |
|
224 | data = render( | |
225 | 'rhodecode:templates/admin/users/user_add.mako', |
|
225 | 'rhodecode:templates/admin/users/user_add.mako', | |
226 | self._get_template_context(c), self.request) |
|
226 | self._get_template_context(c), self.request) | |
227 | html = formencode.htmlfill.render( |
|
227 | html = formencode.htmlfill.render( | |
228 | data, |
|
228 | data, | |
229 | defaults=errors.value, |
|
229 | defaults=errors.value, | |
230 | errors=errors.error_dict or {}, |
|
230 | errors=errors.error_dict or {}, | |
231 | prefix_error=False, |
|
231 | prefix_error=False, | |
232 | encoding="UTF-8", |
|
232 | encoding="UTF-8", | |
233 | force_defaults=False |
|
233 | force_defaults=False | |
234 | ) |
|
234 | ) | |
235 | return Response(html) |
|
235 | return Response(html) | |
236 | except UserCreationError as e: |
|
236 | except UserCreationError as e: | |
237 | h.flash(e, 'error') |
|
237 | h.flash(e, 'error') | |
238 | except Exception: |
|
238 | except Exception: | |
239 | log.exception("Exception creation of user") |
|
239 | log.exception("Exception creation of user") | |
240 | h.flash(_('Error occurred during creation of user %s') |
|
240 | h.flash(_('Error occurred during creation of user %s') | |
241 | % self.request.POST.get('username'), category='error') |
|
241 | % self.request.POST.get('username'), category='error') | |
242 | raise HTTPFound(h.route_path('users')) |
|
242 | raise HTTPFound(h.route_path('users')) | |
243 |
|
243 | |||
244 |
|
244 | |||
245 | class UsersView(UserAppView): |
|
245 | class UsersView(UserAppView): | |
246 | ALLOW_SCOPED_TOKENS = False |
|
246 | ALLOW_SCOPED_TOKENS = False | |
247 | """ |
|
247 | """ | |
248 | This view has alternative version inside EE, if modified please take a look |
|
248 | This view has alternative version inside EE, if modified please take a look | |
249 | in there as well. |
|
249 | in there as well. | |
250 | """ |
|
250 | """ | |
251 |
|
251 | |||
252 | def load_default_context(self): |
|
252 | def load_default_context(self): | |
253 | c = self._get_local_tmpl_context() |
|
253 | c = self._get_local_tmpl_context() | |
254 | c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS |
|
254 | c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS | |
255 | c.allowed_languages = [ |
|
255 | c.allowed_languages = [ | |
256 | ('en', 'English (en)'), |
|
256 | ('en', 'English (en)'), | |
257 | ('de', 'German (de)'), |
|
257 | ('de', 'German (de)'), | |
258 | ('fr', 'French (fr)'), |
|
258 | ('fr', 'French (fr)'), | |
259 | ('it', 'Italian (it)'), |
|
259 | ('it', 'Italian (it)'), | |
260 | ('ja', 'Japanese (ja)'), |
|
260 | ('ja', 'Japanese (ja)'), | |
261 | ('pl', 'Polish (pl)'), |
|
261 | ('pl', 'Polish (pl)'), | |
262 | ('pt', 'Portuguese (pt)'), |
|
262 | ('pt', 'Portuguese (pt)'), | |
263 | ('ru', 'Russian (ru)'), |
|
263 | ('ru', 'Russian (ru)'), | |
264 | ('zh', 'Chinese (zh)'), |
|
264 | ('zh', 'Chinese (zh)'), | |
265 | ] |
|
265 | ] | |
266 | req = self.request |
|
266 | req = self.request | |
267 |
|
267 | |||
268 | c.available_permissions = req.registry.settings['available_permissions'] |
|
268 | c.available_permissions = req.registry.settings['available_permissions'] | |
269 | PermissionModel().set_global_permission_choices( |
|
269 | PermissionModel().set_global_permission_choices( | |
270 | c, gettext_translator=req.translate) |
|
270 | c, gettext_translator=req.translate) | |
271 |
|
271 | |||
272 | return c |
|
272 | return c | |
273 |
|
273 | |||
274 | @LoginRequired() |
|
274 | @LoginRequired() | |
275 | @HasPermissionAllDecorator('hg.admin') |
|
275 | @HasPermissionAllDecorator('hg.admin') | |
276 | @CSRFRequired() |
|
276 | @CSRFRequired() | |
277 | @view_config( |
|
277 | @view_config( | |
278 | route_name='user_update', request_method='POST', |
|
278 | route_name='user_update', request_method='POST', | |
279 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
279 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
280 | def user_update(self): |
|
280 | def user_update(self): | |
281 | _ = self.request.translate |
|
281 | _ = self.request.translate | |
282 | c = self.load_default_context() |
|
282 | c = self.load_default_context() | |
283 |
|
283 | |||
284 | user_id = self.db_user_id |
|
284 | user_id = self.db_user_id | |
285 | c.user = self.db_user |
|
285 | c.user = self.db_user | |
286 |
|
286 | |||
287 | c.active = 'profile' |
|
287 | c.active = 'profile' | |
288 | c.extern_type = c.user.extern_type |
|
288 | c.extern_type = c.user.extern_type | |
289 | c.extern_name = c.user.extern_name |
|
289 | c.extern_name = c.user.extern_name | |
290 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) |
|
290 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) | |
291 | available_languages = [x[0] for x in c.allowed_languages] |
|
291 | available_languages = [x[0] for x in c.allowed_languages] | |
292 | _form = UserForm(self.request.translate, edit=True, |
|
292 | _form = UserForm(self.request.translate, edit=True, | |
293 | available_languages=available_languages, |
|
293 | available_languages=available_languages, | |
294 | old_data={'user_id': user_id, |
|
294 | old_data={'user_id': user_id, | |
295 | 'email': c.user.email})() |
|
295 | 'email': c.user.email})() | |
296 | form_result = {} |
|
296 | form_result = {} | |
297 | old_values = c.user.get_api_data() |
|
297 | old_values = c.user.get_api_data() | |
298 | try: |
|
298 | try: | |
299 | form_result = _form.to_python(dict(self.request.POST)) |
|
299 | form_result = _form.to_python(dict(self.request.POST)) | |
300 | skip_attrs = ['extern_type', 'extern_name'] |
|
300 | skip_attrs = ['extern_type', 'extern_name'] | |
301 | # TODO: plugin should define if username can be updated |
|
301 | # TODO: plugin should define if username can be updated | |
302 | if c.extern_type != "rhodecode": |
|
302 | if c.extern_type != "rhodecode": | |
303 | # forbid updating username for external accounts |
|
303 | # forbid updating username for external accounts | |
304 | skip_attrs.append('username') |
|
304 | skip_attrs.append('username') | |
305 |
|
305 | |||
306 | UserModel().update_user( |
|
306 | UserModel().update_user( | |
307 | user_id, skip_attrs=skip_attrs, **form_result) |
|
307 | user_id, skip_attrs=skip_attrs, **form_result) | |
308 |
|
308 | |||
309 | audit_logger.store_web( |
|
309 | audit_logger.store_web( | |
310 | 'user.edit', action_data={'old_data': old_values}, |
|
310 | 'user.edit', action_data={'old_data': old_values}, | |
311 | user=c.rhodecode_user) |
|
311 | user=c.rhodecode_user) | |
312 |
|
312 | |||
313 | Session().commit() |
|
313 | Session().commit() | |
314 | h.flash(_('User updated successfully'), category='success') |
|
314 | h.flash(_('User updated successfully'), category='success') | |
315 | except formencode.Invalid as errors: |
|
315 | except formencode.Invalid as errors: | |
316 | data = render( |
|
316 | data = render( | |
317 | 'rhodecode:templates/admin/users/user_edit.mako', |
|
317 | 'rhodecode:templates/admin/users/user_edit.mako', | |
318 | self._get_template_context(c), self.request) |
|
318 | self._get_template_context(c), self.request) | |
319 | html = formencode.htmlfill.render( |
|
319 | html = formencode.htmlfill.render( | |
320 | data, |
|
320 | data, | |
321 | defaults=errors.value, |
|
321 | defaults=errors.value, | |
322 | errors=errors.error_dict or {}, |
|
322 | errors=errors.error_dict or {}, | |
323 | prefix_error=False, |
|
323 | prefix_error=False, | |
324 | encoding="UTF-8", |
|
324 | encoding="UTF-8", | |
325 | force_defaults=False |
|
325 | force_defaults=False | |
326 | ) |
|
326 | ) | |
327 | return Response(html) |
|
327 | return Response(html) | |
328 | except UserCreationError as e: |
|
328 | except UserCreationError as e: | |
329 | h.flash(e, 'error') |
|
329 | h.flash(e, 'error') | |
330 | except Exception: |
|
330 | except Exception: | |
331 | log.exception("Exception updating user") |
|
331 | log.exception("Exception updating user") | |
332 | h.flash(_('Error occurred during update of user %s') |
|
332 | h.flash(_('Error occurred during update of user %s') | |
333 | % form_result.get('username'), category='error') |
|
333 | % form_result.get('username'), category='error') | |
334 | raise HTTPFound(h.route_path('user_edit', user_id=user_id)) |
|
334 | raise HTTPFound(h.route_path('user_edit', user_id=user_id)) | |
335 |
|
335 | |||
336 | @LoginRequired() |
|
336 | @LoginRequired() | |
337 | @HasPermissionAllDecorator('hg.admin') |
|
337 | @HasPermissionAllDecorator('hg.admin') | |
338 | @CSRFRequired() |
|
338 | @CSRFRequired() | |
339 | @view_config( |
|
339 | @view_config( | |
340 | route_name='user_delete', request_method='POST', |
|
340 | route_name='user_delete', request_method='POST', | |
341 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
341 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
342 | def user_delete(self): |
|
342 | def user_delete(self): | |
343 | _ = self.request.translate |
|
343 | _ = self.request.translate | |
344 | c = self.load_default_context() |
|
344 | c = self.load_default_context() | |
345 | c.user = self.db_user |
|
345 | c.user = self.db_user | |
346 |
|
346 | |||
347 | _repos = c.user.repositories |
|
347 | _repos = c.user.repositories | |
348 | _repo_groups = c.user.repository_groups |
|
348 | _repo_groups = c.user.repository_groups | |
349 | _user_groups = c.user.user_groups |
|
349 | _user_groups = c.user.user_groups | |
350 |
|
350 | |||
351 | handle_repos = None |
|
351 | handle_repos = None | |
352 | handle_repo_groups = None |
|
352 | handle_repo_groups = None | |
353 | handle_user_groups = None |
|
353 | handle_user_groups = None | |
354 | # dummy call for flash of handle |
|
354 | # dummy call for flash of handle | |
355 | set_handle_flash_repos = lambda: None |
|
355 | set_handle_flash_repos = lambda: None | |
356 | set_handle_flash_repo_groups = lambda: None |
|
356 | set_handle_flash_repo_groups = lambda: None | |
357 | set_handle_flash_user_groups = lambda: None |
|
357 | set_handle_flash_user_groups = lambda: None | |
358 |
|
358 | |||
359 | if _repos and self.request.POST.get('user_repos'): |
|
359 | if _repos and self.request.POST.get('user_repos'): | |
360 | do = self.request.POST['user_repos'] |
|
360 | do = self.request.POST['user_repos'] | |
361 | if do == 'detach': |
|
361 | if do == 'detach': | |
362 | handle_repos = 'detach' |
|
362 | handle_repos = 'detach' | |
363 | set_handle_flash_repos = lambda: h.flash( |
|
363 | set_handle_flash_repos = lambda: h.flash( | |
364 | _('Detached %s repositories') % len(_repos), |
|
364 | _('Detached %s repositories') % len(_repos), | |
365 | category='success') |
|
365 | category='success') | |
366 | elif do == 'delete': |
|
366 | elif do == 'delete': | |
367 | handle_repos = 'delete' |
|
367 | handle_repos = 'delete' | |
368 | set_handle_flash_repos = lambda: h.flash( |
|
368 | set_handle_flash_repos = lambda: h.flash( | |
369 | _('Deleted %s repositories') % len(_repos), |
|
369 | _('Deleted %s repositories') % len(_repos), | |
370 | category='success') |
|
370 | category='success') | |
371 |
|
371 | |||
372 | if _repo_groups and self.request.POST.get('user_repo_groups'): |
|
372 | if _repo_groups and self.request.POST.get('user_repo_groups'): | |
373 | do = self.request.POST['user_repo_groups'] |
|
373 | do = self.request.POST['user_repo_groups'] | |
374 | if do == 'detach': |
|
374 | if do == 'detach': | |
375 | handle_repo_groups = 'detach' |
|
375 | handle_repo_groups = 'detach' | |
376 | set_handle_flash_repo_groups = lambda: h.flash( |
|
376 | set_handle_flash_repo_groups = lambda: h.flash( | |
377 | _('Detached %s repository groups') % len(_repo_groups), |
|
377 | _('Detached %s repository groups') % len(_repo_groups), | |
378 | category='success') |
|
378 | category='success') | |
379 | elif do == 'delete': |
|
379 | elif do == 'delete': | |
380 | handle_repo_groups = 'delete' |
|
380 | handle_repo_groups = 'delete' | |
381 | set_handle_flash_repo_groups = lambda: h.flash( |
|
381 | set_handle_flash_repo_groups = lambda: h.flash( | |
382 | _('Deleted %s repository groups') % len(_repo_groups), |
|
382 | _('Deleted %s repository groups') % len(_repo_groups), | |
383 | category='success') |
|
383 | category='success') | |
384 |
|
384 | |||
385 | if _user_groups and self.request.POST.get('user_user_groups'): |
|
385 | if _user_groups and self.request.POST.get('user_user_groups'): | |
386 | do = self.request.POST['user_user_groups'] |
|
386 | do = self.request.POST['user_user_groups'] | |
387 | if do == 'detach': |
|
387 | if do == 'detach': | |
388 | handle_user_groups = 'detach' |
|
388 | handle_user_groups = 'detach' | |
389 | set_handle_flash_user_groups = lambda: h.flash( |
|
389 | set_handle_flash_user_groups = lambda: h.flash( | |
390 | _('Detached %s user groups') % len(_user_groups), |
|
390 | _('Detached %s user groups') % len(_user_groups), | |
391 | category='success') |
|
391 | category='success') | |
392 | elif do == 'delete': |
|
392 | elif do == 'delete': | |
393 | handle_user_groups = 'delete' |
|
393 | handle_user_groups = 'delete' | |
394 | set_handle_flash_user_groups = lambda: h.flash( |
|
394 | set_handle_flash_user_groups = lambda: h.flash( | |
395 | _('Deleted %s user groups') % len(_user_groups), |
|
395 | _('Deleted %s user groups') % len(_user_groups), | |
396 | category='success') |
|
396 | category='success') | |
397 |
|
397 | |||
398 | old_values = c.user.get_api_data() |
|
398 | old_values = c.user.get_api_data() | |
399 | try: |
|
399 | try: | |
400 | UserModel().delete(c.user, handle_repos=handle_repos, |
|
400 | UserModel().delete(c.user, handle_repos=handle_repos, | |
401 | handle_repo_groups=handle_repo_groups, |
|
401 | handle_repo_groups=handle_repo_groups, | |
402 | handle_user_groups=handle_user_groups) |
|
402 | handle_user_groups=handle_user_groups) | |
403 |
|
403 | |||
404 | audit_logger.store_web( |
|
404 | audit_logger.store_web( | |
405 | 'user.delete', action_data={'old_data': old_values}, |
|
405 | 'user.delete', action_data={'old_data': old_values}, | |
406 | user=c.rhodecode_user) |
|
406 | user=c.rhodecode_user) | |
407 |
|
407 | |||
408 | Session().commit() |
|
408 | Session().commit() | |
409 | set_handle_flash_repos() |
|
409 | set_handle_flash_repos() | |
410 | set_handle_flash_repo_groups() |
|
410 | set_handle_flash_repo_groups() | |
411 | set_handle_flash_user_groups() |
|
411 | set_handle_flash_user_groups() | |
412 | h.flash(_('Successfully deleted user'), category='success') |
|
412 | h.flash(_('Successfully deleted user'), category='success') | |
413 | except (UserOwnsReposException, UserOwnsRepoGroupsException, |
|
413 | except (UserOwnsReposException, UserOwnsRepoGroupsException, | |
414 | UserOwnsUserGroupsException, DefaultUserException) as e: |
|
414 | UserOwnsUserGroupsException, DefaultUserException) as e: | |
415 | h.flash(e, category='warning') |
|
415 | h.flash(e, category='warning') | |
416 | except Exception: |
|
416 | except Exception: | |
417 | log.exception("Exception during deletion of user") |
|
417 | log.exception("Exception during deletion of user") | |
418 | h.flash(_('An error occurred during deletion of user'), |
|
418 | h.flash(_('An error occurred during deletion of user'), | |
419 | category='error') |
|
419 | category='error') | |
420 | raise HTTPFound(h.route_path('users')) |
|
420 | raise HTTPFound(h.route_path('users')) | |
421 |
|
421 | |||
422 | @LoginRequired() |
|
422 | @LoginRequired() | |
423 | @HasPermissionAllDecorator('hg.admin') |
|
423 | @HasPermissionAllDecorator('hg.admin') | |
424 | @view_config( |
|
424 | @view_config( | |
425 | route_name='user_edit', request_method='GET', |
|
425 | route_name='user_edit', request_method='GET', | |
426 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
426 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
427 | def user_edit(self): |
|
427 | def user_edit(self): | |
428 | _ = self.request.translate |
|
428 | _ = self.request.translate | |
429 | c = self.load_default_context() |
|
429 | c = self.load_default_context() | |
430 | c.user = self.db_user |
|
430 | c.user = self.db_user | |
431 |
|
431 | |||
432 | c.active = 'profile' |
|
432 | c.active = 'profile' | |
433 | c.extern_type = c.user.extern_type |
|
433 | c.extern_type = c.user.extern_type | |
434 | c.extern_name = c.user.extern_name |
|
434 | c.extern_name = c.user.extern_name | |
435 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) |
|
435 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) | |
436 |
|
436 | |||
437 | defaults = c.user.get_dict() |
|
437 | defaults = c.user.get_dict() | |
438 | defaults.update({'language': c.user.user_data.get('language')}) |
|
438 | defaults.update({'language': c.user.user_data.get('language')}) | |
439 |
|
439 | |||
440 | data = render( |
|
440 | data = render( | |
441 | 'rhodecode:templates/admin/users/user_edit.mako', |
|
441 | 'rhodecode:templates/admin/users/user_edit.mako', | |
442 | self._get_template_context(c), self.request) |
|
442 | self._get_template_context(c), self.request) | |
443 | html = formencode.htmlfill.render( |
|
443 | html = formencode.htmlfill.render( | |
444 | data, |
|
444 | data, | |
445 | defaults=defaults, |
|
445 | defaults=defaults, | |
446 | encoding="UTF-8", |
|
446 | encoding="UTF-8", | |
447 | force_defaults=False |
|
447 | force_defaults=False | |
448 | ) |
|
448 | ) | |
449 | return Response(html) |
|
449 | return Response(html) | |
450 |
|
450 | |||
451 | @LoginRequired() |
|
451 | @LoginRequired() | |
452 | @HasPermissionAllDecorator('hg.admin') |
|
452 | @HasPermissionAllDecorator('hg.admin') | |
453 | @view_config( |
|
453 | @view_config( | |
454 | route_name='user_edit_advanced', request_method='GET', |
|
454 | route_name='user_edit_advanced', request_method='GET', | |
455 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
455 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
456 | def user_edit_advanced(self): |
|
456 | def user_edit_advanced(self): | |
457 | _ = self.request.translate |
|
457 | _ = self.request.translate | |
458 | c = self.load_default_context() |
|
458 | c = self.load_default_context() | |
459 |
|
459 | |||
460 | user_id = self.db_user_id |
|
460 | user_id = self.db_user_id | |
461 | c.user = self.db_user |
|
461 | c.user = self.db_user | |
462 |
|
462 | |||
463 | c.active = 'advanced' |
|
463 | c.active = 'advanced' | |
464 | c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id) |
|
464 | c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id) | |
465 | c.personal_repo_group_name = RepoGroupModel()\ |
|
465 | c.personal_repo_group_name = RepoGroupModel()\ | |
466 | .get_personal_group_name(c.user) |
|
466 | .get_personal_group_name(c.user) | |
467 |
|
467 | |||
468 | c.user_to_review_rules = sorted( |
|
468 | c.user_to_review_rules = sorted( | |
469 | (x.user for x in c.user.user_review_rules), |
|
469 | (x.user for x in c.user.user_review_rules), | |
470 | key=lambda u: u.username.lower()) |
|
470 | key=lambda u: u.username.lower()) | |
471 |
|
471 | |||
472 | c.first_admin = User.get_first_super_admin() |
|
472 | c.first_admin = User.get_first_super_admin() | |
473 | defaults = c.user.get_dict() |
|
473 | defaults = c.user.get_dict() | |
474 |
|
474 | |||
475 | # Interim workaround if the user participated on any pull requests as a |
|
475 | # Interim workaround if the user participated on any pull requests as a | |
476 | # reviewer. |
|
476 | # reviewer. | |
477 | has_review = len(c.user.reviewer_pull_requests) |
|
477 | has_review = len(c.user.reviewer_pull_requests) | |
478 | c.can_delete_user = not has_review |
|
478 | c.can_delete_user = not has_review | |
479 | c.can_delete_user_message = '' |
|
479 | c.can_delete_user_message = '' | |
480 | inactive_link = h.link_to( |
|
480 | inactive_link = h.link_to( | |
481 | 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active')) |
|
481 | 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active')) | |
482 | if has_review == 1: |
|
482 | if has_review == 1: | |
483 | c.can_delete_user_message = h.literal(_( |
|
483 | c.can_delete_user_message = h.literal(_( | |
484 | 'The user participates as reviewer in {} pull request and ' |
|
484 | 'The user participates as reviewer in {} pull request and ' | |
485 | 'cannot be deleted. \nYou can set the user to ' |
|
485 | 'cannot be deleted. \nYou can set the user to ' | |
486 | '"{}" instead of deleting it.').format( |
|
486 | '"{}" instead of deleting it.').format( | |
487 | has_review, inactive_link)) |
|
487 | has_review, inactive_link)) | |
488 | elif has_review: |
|
488 | elif has_review: | |
489 | c.can_delete_user_message = h.literal(_( |
|
489 | c.can_delete_user_message = h.literal(_( | |
490 | 'The user participates as reviewer in {} pull requests and ' |
|
490 | 'The user participates as reviewer in {} pull requests and ' | |
491 | 'cannot be deleted. \nYou can set the user to ' |
|
491 | 'cannot be deleted. \nYou can set the user to ' | |
492 | '"{}" instead of deleting it.').format( |
|
492 | '"{}" instead of deleting it.').format( | |
493 | has_review, inactive_link)) |
|
493 | has_review, inactive_link)) | |
494 |
|
494 | |||
495 | data = render( |
|
495 | data = render( | |
496 | 'rhodecode:templates/admin/users/user_edit.mako', |
|
496 | 'rhodecode:templates/admin/users/user_edit.mako', | |
497 | self._get_template_context(c), self.request) |
|
497 | self._get_template_context(c), self.request) | |
498 | html = formencode.htmlfill.render( |
|
498 | html = formencode.htmlfill.render( | |
499 | data, |
|
499 | data, | |
500 | defaults=defaults, |
|
500 | defaults=defaults, | |
501 | encoding="UTF-8", |
|
501 | encoding="UTF-8", | |
502 | force_defaults=False |
|
502 | force_defaults=False | |
503 | ) |
|
503 | ) | |
504 | return Response(html) |
|
504 | return Response(html) | |
505 |
|
505 | |||
506 | @LoginRequired() |
|
506 | @LoginRequired() | |
507 | @HasPermissionAllDecorator('hg.admin') |
|
507 | @HasPermissionAllDecorator('hg.admin') | |
508 | @view_config( |
|
508 | @view_config( | |
509 | route_name='user_edit_global_perms', request_method='GET', |
|
509 | route_name='user_edit_global_perms', request_method='GET', | |
510 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
510 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
511 | def user_edit_global_perms(self): |
|
511 | def user_edit_global_perms(self): | |
512 | _ = self.request.translate |
|
512 | _ = self.request.translate | |
513 | c = self.load_default_context() |
|
513 | c = self.load_default_context() | |
514 | c.user = self.db_user |
|
514 | c.user = self.db_user | |
515 |
|
515 | |||
516 | c.active = 'global_perms' |
|
516 | c.active = 'global_perms' | |
517 |
|
517 | |||
518 | c.default_user = User.get_default_user() |
|
518 | c.default_user = User.get_default_user() | |
519 | defaults = c.user.get_dict() |
|
519 | defaults = c.user.get_dict() | |
520 | defaults.update(c.default_user.get_default_perms(suffix='_inherited')) |
|
520 | defaults.update(c.default_user.get_default_perms(suffix='_inherited')) | |
521 | defaults.update(c.default_user.get_default_perms()) |
|
521 | defaults.update(c.default_user.get_default_perms()) | |
522 | defaults.update(c.user.get_default_perms()) |
|
522 | defaults.update(c.user.get_default_perms()) | |
523 |
|
523 | |||
524 | data = render( |
|
524 | data = render( | |
525 | 'rhodecode:templates/admin/users/user_edit.mako', |
|
525 | 'rhodecode:templates/admin/users/user_edit.mako', | |
526 | self._get_template_context(c), self.request) |
|
526 | self._get_template_context(c), self.request) | |
527 | html = formencode.htmlfill.render( |
|
527 | html = formencode.htmlfill.render( | |
528 | data, |
|
528 | data, | |
529 | defaults=defaults, |
|
529 | defaults=defaults, | |
530 | encoding="UTF-8", |
|
530 | encoding="UTF-8", | |
531 | force_defaults=False |
|
531 | force_defaults=False | |
532 | ) |
|
532 | ) | |
533 | return Response(html) |
|
533 | return Response(html) | |
534 |
|
534 | |||
535 | @LoginRequired() |
|
535 | @LoginRequired() | |
536 | @HasPermissionAllDecorator('hg.admin') |
|
536 | @HasPermissionAllDecorator('hg.admin') | |
537 | @CSRFRequired() |
|
537 | @CSRFRequired() | |
538 | @view_config( |
|
538 | @view_config( | |
539 | route_name='user_edit_global_perms_update', request_method='POST', |
|
539 | route_name='user_edit_global_perms_update', request_method='POST', | |
540 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
540 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
541 | def user_edit_global_perms_update(self): |
|
541 | def user_edit_global_perms_update(self): | |
542 | _ = self.request.translate |
|
542 | _ = self.request.translate | |
543 | c = self.load_default_context() |
|
543 | c = self.load_default_context() | |
544 |
|
544 | |||
545 | user_id = self.db_user_id |
|
545 | user_id = self.db_user_id | |
546 | c.user = self.db_user |
|
546 | c.user = self.db_user | |
547 |
|
547 | |||
548 | c.active = 'global_perms' |
|
548 | c.active = 'global_perms' | |
549 | try: |
|
549 | try: | |
550 | # first stage that verifies the checkbox |
|
550 | # first stage that verifies the checkbox | |
551 | _form = UserIndividualPermissionsForm(self.request.translate) |
|
551 | _form = UserIndividualPermissionsForm(self.request.translate) | |
552 | form_result = _form.to_python(dict(self.request.POST)) |
|
552 | form_result = _form.to_python(dict(self.request.POST)) | |
553 | inherit_perms = form_result['inherit_default_permissions'] |
|
553 | inherit_perms = form_result['inherit_default_permissions'] | |
554 | c.user.inherit_default_permissions = inherit_perms |
|
554 | c.user.inherit_default_permissions = inherit_perms | |
555 | Session().add(c.user) |
|
555 | Session().add(c.user) | |
556 |
|
556 | |||
557 | if not inherit_perms: |
|
557 | if not inherit_perms: | |
558 | # only update the individual ones if we un check the flag |
|
558 | # only update the individual ones if we un check the flag | |
559 | _form = UserPermissionsForm( |
|
559 | _form = UserPermissionsForm( | |
560 | self.request.translate, |
|
560 | self.request.translate, | |
561 | [x[0] for x in c.repo_create_choices], |
|
561 | [x[0] for x in c.repo_create_choices], | |
562 | [x[0] for x in c.repo_create_on_write_choices], |
|
562 | [x[0] for x in c.repo_create_on_write_choices], | |
563 | [x[0] for x in c.repo_group_create_choices], |
|
563 | [x[0] for x in c.repo_group_create_choices], | |
564 | [x[0] for x in c.user_group_create_choices], |
|
564 | [x[0] for x in c.user_group_create_choices], | |
565 | [x[0] for x in c.fork_choices], |
|
565 | [x[0] for x in c.fork_choices], | |
566 | [x[0] for x in c.inherit_default_permission_choices])() |
|
566 | [x[0] for x in c.inherit_default_permission_choices])() | |
567 |
|
567 | |||
568 | form_result = _form.to_python(dict(self.request.POST)) |
|
568 | form_result = _form.to_python(dict(self.request.POST)) | |
569 | form_result.update({'perm_user_id': c.user.user_id}) |
|
569 | form_result.update({'perm_user_id': c.user.user_id}) | |
570 |
|
570 | |||
571 | PermissionModel().update_user_permissions(form_result) |
|
571 | PermissionModel().update_user_permissions(form_result) | |
572 |
|
572 | |||
573 | # TODO(marcink): implement global permissions |
|
573 | # TODO(marcink): implement global permissions | |
574 | # audit_log.store_web('user.edit.permissions') |
|
574 | # audit_log.store_web('user.edit.permissions') | |
575 |
|
575 | |||
576 | Session().commit() |
|
576 | Session().commit() | |
577 |
|
577 | |||
578 | h.flash(_('User global permissions updated successfully'), |
|
578 | h.flash(_('User global permissions updated successfully'), | |
579 | category='success') |
|
579 | category='success') | |
580 |
|
580 | |||
581 | except formencode.Invalid as errors: |
|
581 | except formencode.Invalid as errors: | |
582 | data = render( |
|
582 | data = render( | |
583 | 'rhodecode:templates/admin/users/user_edit.mako', |
|
583 | 'rhodecode:templates/admin/users/user_edit.mako', | |
584 | self._get_template_context(c), self.request) |
|
584 | self._get_template_context(c), self.request) | |
585 | html = formencode.htmlfill.render( |
|
585 | html = formencode.htmlfill.render( | |
586 | data, |
|
586 | data, | |
587 | defaults=errors.value, |
|
587 | defaults=errors.value, | |
588 | errors=errors.error_dict or {}, |
|
588 | errors=errors.error_dict or {}, | |
589 | prefix_error=False, |
|
589 | prefix_error=False, | |
590 | encoding="UTF-8", |
|
590 | encoding="UTF-8", | |
591 | force_defaults=False |
|
591 | force_defaults=False | |
592 | ) |
|
592 | ) | |
593 | return Response(html) |
|
593 | return Response(html) | |
594 | except Exception: |
|
594 | except Exception: | |
595 | log.exception("Exception during permissions saving") |
|
595 | log.exception("Exception during permissions saving") | |
596 | h.flash(_('An error occurred during permissions saving'), |
|
596 | h.flash(_('An error occurred during permissions saving'), | |
597 | category='error') |
|
597 | category='error') | |
598 |
|
598 | |||
599 | affected_user_ids = [user_id] |
|
599 | affected_user_ids = [user_id] | |
600 | events.trigger(events.UserPermissionsChange(affected_user_ids)) |
|
600 | events.trigger(events.UserPermissionsChange(affected_user_ids)) | |
601 | raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id)) |
|
601 | raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id)) | |
602 |
|
602 | |||
603 | @LoginRequired() |
|
603 | @LoginRequired() | |
604 | @HasPermissionAllDecorator('hg.admin') |
|
604 | @HasPermissionAllDecorator('hg.admin') | |
605 | @CSRFRequired() |
|
605 | @CSRFRequired() | |
606 | @view_config( |
|
606 | @view_config( | |
607 | route_name='user_enable_force_password_reset', request_method='POST', |
|
607 | route_name='user_enable_force_password_reset', request_method='POST', | |
608 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
608 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
609 | def user_enable_force_password_reset(self): |
|
609 | def user_enable_force_password_reset(self): | |
610 | _ = self.request.translate |
|
610 | _ = self.request.translate | |
611 | c = self.load_default_context() |
|
611 | c = self.load_default_context() | |
612 |
|
612 | |||
613 | user_id = self.db_user_id |
|
613 | user_id = self.db_user_id | |
614 | c.user = self.db_user |
|
614 | c.user = self.db_user | |
615 |
|
615 | |||
616 | try: |
|
616 | try: | |
617 | c.user.update_userdata(force_password_change=True) |
|
617 | c.user.update_userdata(force_password_change=True) | |
618 |
|
618 | |||
619 | msg = _('Force password change enabled for user') |
|
619 | msg = _('Force password change enabled for user') | |
620 | audit_logger.store_web('user.edit.password_reset.enabled', |
|
620 | audit_logger.store_web('user.edit.password_reset.enabled', | |
621 | user=c.rhodecode_user) |
|
621 | user=c.rhodecode_user) | |
622 |
|
622 | |||
623 | Session().commit() |
|
623 | Session().commit() | |
624 | h.flash(msg, category='success') |
|
624 | h.flash(msg, category='success') | |
625 | except Exception: |
|
625 | except Exception: | |
626 | log.exception("Exception during password reset for user") |
|
626 | log.exception("Exception during password reset for user") | |
627 | h.flash(_('An error occurred during password reset for user'), |
|
627 | h.flash(_('An error occurred during password reset for user'), | |
628 | category='error') |
|
628 | category='error') | |
629 |
|
629 | |||
630 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) |
|
630 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) | |
631 |
|
631 | |||
632 | @LoginRequired() |
|
632 | @LoginRequired() | |
633 | @HasPermissionAllDecorator('hg.admin') |
|
633 | @HasPermissionAllDecorator('hg.admin') | |
634 | @CSRFRequired() |
|
634 | @CSRFRequired() | |
635 | @view_config( |
|
635 | @view_config( | |
636 | route_name='user_disable_force_password_reset', request_method='POST', |
|
636 | route_name='user_disable_force_password_reset', request_method='POST', | |
637 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
637 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
638 | def user_disable_force_password_reset(self): |
|
638 | def user_disable_force_password_reset(self): | |
639 | _ = self.request.translate |
|
639 | _ = self.request.translate | |
640 | c = self.load_default_context() |
|
640 | c = self.load_default_context() | |
641 |
|
641 | |||
642 | user_id = self.db_user_id |
|
642 | user_id = self.db_user_id | |
643 | c.user = self.db_user |
|
643 | c.user = self.db_user | |
644 |
|
644 | |||
645 | try: |
|
645 | try: | |
646 | c.user.update_userdata(force_password_change=False) |
|
646 | c.user.update_userdata(force_password_change=False) | |
647 |
|
647 | |||
648 | msg = _('Force password change disabled for user') |
|
648 | msg = _('Force password change disabled for user') | |
649 | audit_logger.store_web( |
|
649 | audit_logger.store_web( | |
650 | 'user.edit.password_reset.disabled', |
|
650 | 'user.edit.password_reset.disabled', | |
651 | user=c.rhodecode_user) |
|
651 | user=c.rhodecode_user) | |
652 |
|
652 | |||
653 | Session().commit() |
|
653 | Session().commit() | |
654 | h.flash(msg, category='success') |
|
654 | h.flash(msg, category='success') | |
655 | except Exception: |
|
655 | except Exception: | |
656 | log.exception("Exception during password reset for user") |
|
656 | log.exception("Exception during password reset for user") | |
657 | h.flash(_('An error occurred during password reset for user'), |
|
657 | h.flash(_('An error occurred during password reset for user'), | |
658 | category='error') |
|
658 | category='error') | |
659 |
|
659 | |||
660 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) |
|
660 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) | |
661 |
|
661 | |||
662 | @LoginRequired() |
|
662 | @LoginRequired() | |
663 | @HasPermissionAllDecorator('hg.admin') |
|
663 | @HasPermissionAllDecorator('hg.admin') | |
664 | @CSRFRequired() |
|
664 | @CSRFRequired() | |
665 | @view_config( |
|
665 | @view_config( | |
666 | route_name='user_create_personal_repo_group', request_method='POST', |
|
666 | route_name='user_create_personal_repo_group', request_method='POST', | |
667 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
667 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
668 | def user_create_personal_repo_group(self): |
|
668 | def user_create_personal_repo_group(self): | |
669 | """ |
|
669 | """ | |
670 | Create personal repository group for this user |
|
670 | Create personal repository group for this user | |
671 | """ |
|
671 | """ | |
672 | from rhodecode.model.repo_group import RepoGroupModel |
|
672 | from rhodecode.model.repo_group import RepoGroupModel | |
673 |
|
673 | |||
674 | _ = self.request.translate |
|
674 | _ = self.request.translate | |
675 | c = self.load_default_context() |
|
675 | c = self.load_default_context() | |
676 |
|
676 | |||
677 | user_id = self.db_user_id |
|
677 | user_id = self.db_user_id | |
678 | c.user = self.db_user |
|
678 | c.user = self.db_user | |
679 |
|
679 | |||
680 | personal_repo_group = RepoGroup.get_user_personal_repo_group( |
|
680 | personal_repo_group = RepoGroup.get_user_personal_repo_group( | |
681 | c.user.user_id) |
|
681 | c.user.user_id) | |
682 | if personal_repo_group: |
|
682 | if personal_repo_group: | |
683 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) |
|
683 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) | |
684 |
|
684 | |||
685 | personal_repo_group_name = RepoGroupModel().get_personal_group_name( |
|
685 | personal_repo_group_name = RepoGroupModel().get_personal_group_name(c.user) | |
686 | c.user) |
|
|||
687 | named_personal_group = RepoGroup.get_by_group_name( |
|
686 | named_personal_group = RepoGroup.get_by_group_name( | |
688 | personal_repo_group_name) |
|
687 | personal_repo_group_name) | |
689 | try: |
|
688 | try: | |
690 |
|
689 | |||
691 | if named_personal_group and named_personal_group.user_id == c.user.user_id: |
|
690 | if named_personal_group and named_personal_group.user_id == c.user.user_id: | |
692 | # migrate the same named group, and mark it as personal |
|
691 | # migrate the same named group, and mark it as personal | |
693 | named_personal_group.personal = True |
|
692 | named_personal_group.personal = True | |
694 | Session().add(named_personal_group) |
|
693 | Session().add(named_personal_group) | |
695 | Session().commit() |
|
694 | Session().commit() | |
696 | msg = _('Linked repository group `%s` as personal' % ( |
|
695 | msg = _('Linked repository group `%s` as personal' % ( | |
697 | personal_repo_group_name,)) |
|
696 | personal_repo_group_name,)) | |
698 | h.flash(msg, category='success') |
|
697 | h.flash(msg, category='success') | |
699 | elif not named_personal_group: |
|
698 | elif not named_personal_group: | |
700 | RepoGroupModel().create_personal_repo_group(c.user) |
|
699 | RepoGroupModel().create_personal_repo_group(c.user) | |
701 |
|
700 | |||
702 | msg = _('Created repository group `%s`' % ( |
|
701 | msg = _('Created repository group `%s`' % ( | |
703 | personal_repo_group_name,)) |
|
702 | personal_repo_group_name,)) | |
704 | h.flash(msg, category='success') |
|
703 | h.flash(msg, category='success') | |
705 | else: |
|
704 | else: | |
706 | msg = _('Repository group `%s` is already taken' % ( |
|
705 | msg = _('Repository group `%s` is already taken' % ( | |
707 | personal_repo_group_name,)) |
|
706 | personal_repo_group_name,)) | |
708 | h.flash(msg, category='warning') |
|
707 | h.flash(msg, category='warning') | |
709 | except Exception: |
|
708 | except Exception: | |
710 | log.exception("Exception during repository group creation") |
|
709 | log.exception("Exception during repository group creation") | |
711 | msg = _( |
|
710 | msg = _( | |
712 | 'An error occurred during repository group creation for user') |
|
711 | 'An error occurred during repository group creation for user') | |
713 | h.flash(msg, category='error') |
|
712 | h.flash(msg, category='error') | |
714 | Session().rollback() |
|
713 | Session().rollback() | |
715 |
|
714 | |||
716 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) |
|
715 | raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id)) | |
717 |
|
716 | |||
718 | @LoginRequired() |
|
717 | @LoginRequired() | |
719 | @HasPermissionAllDecorator('hg.admin') |
|
718 | @HasPermissionAllDecorator('hg.admin') | |
720 | @view_config( |
|
719 | @view_config( | |
721 | route_name='edit_user_auth_tokens', request_method='GET', |
|
720 | route_name='edit_user_auth_tokens', request_method='GET', | |
722 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
721 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
723 | def auth_tokens(self): |
|
722 | def auth_tokens(self): | |
724 | _ = self.request.translate |
|
723 | _ = self.request.translate | |
725 | c = self.load_default_context() |
|
724 | c = self.load_default_context() | |
726 | c.user = self.db_user |
|
725 | c.user = self.db_user | |
727 |
|
726 | |||
728 | c.active = 'auth_tokens' |
|
727 | c.active = 'auth_tokens' | |
729 |
|
728 | |||
730 | c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_) |
|
729 | c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_) | |
731 | c.role_values = [ |
|
730 | c.role_values = [ | |
732 | (x, AuthTokenModel.cls._get_role_name(x)) |
|
731 | (x, AuthTokenModel.cls._get_role_name(x)) | |
733 | for x in AuthTokenModel.cls.ROLES] |
|
732 | for x in AuthTokenModel.cls.ROLES] | |
734 | c.role_options = [(c.role_values, _("Role"))] |
|
733 | c.role_options = [(c.role_values, _("Role"))] | |
735 | c.user_auth_tokens = AuthTokenModel().get_auth_tokens( |
|
734 | c.user_auth_tokens = AuthTokenModel().get_auth_tokens( | |
736 | c.user.user_id, show_expired=True) |
|
735 | c.user.user_id, show_expired=True) | |
737 | c.role_vcs = AuthTokenModel.cls.ROLE_VCS |
|
736 | c.role_vcs = AuthTokenModel.cls.ROLE_VCS | |
738 | return self._get_template_context(c) |
|
737 | return self._get_template_context(c) | |
739 |
|
738 | |||
740 | def maybe_attach_token_scope(self, token): |
|
739 | def maybe_attach_token_scope(self, token): | |
741 | # implemented in EE edition |
|
740 | # implemented in EE edition | |
742 | pass |
|
741 | pass | |
743 |
|
742 | |||
744 | @LoginRequired() |
|
743 | @LoginRequired() | |
745 | @HasPermissionAllDecorator('hg.admin') |
|
744 | @HasPermissionAllDecorator('hg.admin') | |
746 | @CSRFRequired() |
|
745 | @CSRFRequired() | |
747 | @view_config( |
|
746 | @view_config( | |
748 | route_name='edit_user_auth_tokens_add', request_method='POST') |
|
747 | route_name='edit_user_auth_tokens_add', request_method='POST') | |
749 | def auth_tokens_add(self): |
|
748 | def auth_tokens_add(self): | |
750 | _ = self.request.translate |
|
749 | _ = self.request.translate | |
751 | c = self.load_default_context() |
|
750 | c = self.load_default_context() | |
752 |
|
751 | |||
753 | user_id = self.db_user_id |
|
752 | user_id = self.db_user_id | |
754 | c.user = self.db_user |
|
753 | c.user = self.db_user | |
755 |
|
754 | |||
756 | user_data = c.user.get_api_data() |
|
755 | user_data = c.user.get_api_data() | |
757 | lifetime = safe_int(self.request.POST.get('lifetime'), -1) |
|
756 | lifetime = safe_int(self.request.POST.get('lifetime'), -1) | |
758 | description = self.request.POST.get('description') |
|
757 | description = self.request.POST.get('description') | |
759 | role = self.request.POST.get('role') |
|
758 | role = self.request.POST.get('role') | |
760 |
|
759 | |||
761 | token = UserModel().add_auth_token( |
|
760 | token = UserModel().add_auth_token( | |
762 | user=c.user.user_id, |
|
761 | user=c.user.user_id, | |
763 | lifetime_minutes=lifetime, role=role, description=description, |
|
762 | lifetime_minutes=lifetime, role=role, description=description, | |
764 | scope_callback=self.maybe_attach_token_scope) |
|
763 | scope_callback=self.maybe_attach_token_scope) | |
765 | token_data = token.get_api_data() |
|
764 | token_data = token.get_api_data() | |
766 |
|
765 | |||
767 | audit_logger.store_web( |
|
766 | audit_logger.store_web( | |
768 | 'user.edit.token.add', action_data={ |
|
767 | 'user.edit.token.add', action_data={ | |
769 | 'data': {'token': token_data, 'user': user_data}}, |
|
768 | 'data': {'token': token_data, 'user': user_data}}, | |
770 | user=self._rhodecode_user, ) |
|
769 | user=self._rhodecode_user, ) | |
771 | Session().commit() |
|
770 | Session().commit() | |
772 |
|
771 | |||
773 | h.flash(_("Auth token successfully created"), category='success') |
|
772 | h.flash(_("Auth token successfully created"), category='success') | |
774 | return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id)) |
|
773 | return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id)) | |
775 |
|
774 | |||
776 | @LoginRequired() |
|
775 | @LoginRequired() | |
777 | @HasPermissionAllDecorator('hg.admin') |
|
776 | @HasPermissionAllDecorator('hg.admin') | |
778 | @CSRFRequired() |
|
777 | @CSRFRequired() | |
779 | @view_config( |
|
778 | @view_config( | |
780 | route_name='edit_user_auth_tokens_delete', request_method='POST') |
|
779 | route_name='edit_user_auth_tokens_delete', request_method='POST') | |
781 | def auth_tokens_delete(self): |
|
780 | def auth_tokens_delete(self): | |
782 | _ = self.request.translate |
|
781 | _ = self.request.translate | |
783 | c = self.load_default_context() |
|
782 | c = self.load_default_context() | |
784 |
|
783 | |||
785 | user_id = self.db_user_id |
|
784 | user_id = self.db_user_id | |
786 | c.user = self.db_user |
|
785 | c.user = self.db_user | |
787 |
|
786 | |||
788 | user_data = c.user.get_api_data() |
|
787 | user_data = c.user.get_api_data() | |
789 |
|
788 | |||
790 | del_auth_token = self.request.POST.get('del_auth_token') |
|
789 | del_auth_token = self.request.POST.get('del_auth_token') | |
791 |
|
790 | |||
792 | if del_auth_token: |
|
791 | if del_auth_token: | |
793 | token = UserApiKeys.get_or_404(del_auth_token) |
|
792 | token = UserApiKeys.get_or_404(del_auth_token) | |
794 | token_data = token.get_api_data() |
|
793 | token_data = token.get_api_data() | |
795 |
|
794 | |||
796 | AuthTokenModel().delete(del_auth_token, c.user.user_id) |
|
795 | AuthTokenModel().delete(del_auth_token, c.user.user_id) | |
797 | audit_logger.store_web( |
|
796 | audit_logger.store_web( | |
798 | 'user.edit.token.delete', action_data={ |
|
797 | 'user.edit.token.delete', action_data={ | |
799 | 'data': {'token': token_data, 'user': user_data}}, |
|
798 | 'data': {'token': token_data, 'user': user_data}}, | |
800 | user=self._rhodecode_user,) |
|
799 | user=self._rhodecode_user,) | |
801 | Session().commit() |
|
800 | Session().commit() | |
802 | h.flash(_("Auth token successfully deleted"), category='success') |
|
801 | h.flash(_("Auth token successfully deleted"), category='success') | |
803 |
|
802 | |||
804 | return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id)) |
|
803 | return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id)) | |
805 |
|
804 | |||
806 | @LoginRequired() |
|
805 | @LoginRequired() | |
807 | @HasPermissionAllDecorator('hg.admin') |
|
806 | @HasPermissionAllDecorator('hg.admin') | |
808 | @view_config( |
|
807 | @view_config( | |
809 | route_name='edit_user_ssh_keys', request_method='GET', |
|
808 | route_name='edit_user_ssh_keys', request_method='GET', | |
810 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
809 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
811 | def ssh_keys(self): |
|
810 | def ssh_keys(self): | |
812 | _ = self.request.translate |
|
811 | _ = self.request.translate | |
813 | c = self.load_default_context() |
|
812 | c = self.load_default_context() | |
814 | c.user = self.db_user |
|
813 | c.user = self.db_user | |
815 |
|
814 | |||
816 | c.active = 'ssh_keys' |
|
815 | c.active = 'ssh_keys' | |
817 | c.default_key = self.request.GET.get('default_key') |
|
816 | c.default_key = self.request.GET.get('default_key') | |
818 | c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id) |
|
817 | c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id) | |
819 | return self._get_template_context(c) |
|
818 | return self._get_template_context(c) | |
820 |
|
819 | |||
821 | @LoginRequired() |
|
820 | @LoginRequired() | |
822 | @HasPermissionAllDecorator('hg.admin') |
|
821 | @HasPermissionAllDecorator('hg.admin') | |
823 | @view_config( |
|
822 | @view_config( | |
824 | route_name='edit_user_ssh_keys_generate_keypair', request_method='GET', |
|
823 | route_name='edit_user_ssh_keys_generate_keypair', request_method='GET', | |
825 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
824 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
826 | def ssh_keys_generate_keypair(self): |
|
825 | def ssh_keys_generate_keypair(self): | |
827 | _ = self.request.translate |
|
826 | _ = self.request.translate | |
828 | c = self.load_default_context() |
|
827 | c = self.load_default_context() | |
829 |
|
828 | |||
830 | c.user = self.db_user |
|
829 | c.user = self.db_user | |
831 |
|
830 | |||
832 | c.active = 'ssh_keys_generate' |
|
831 | c.active = 'ssh_keys_generate' | |
833 | comment = 'RhodeCode-SSH {}'.format(c.user.email or '') |
|
832 | comment = 'RhodeCode-SSH {}'.format(c.user.email or '') | |
834 | c.private, c.public = SshKeyModel().generate_keypair(comment=comment) |
|
833 | c.private, c.public = SshKeyModel().generate_keypair(comment=comment) | |
835 |
|
834 | |||
836 | return self._get_template_context(c) |
|
835 | return self._get_template_context(c) | |
837 |
|
836 | |||
838 | @LoginRequired() |
|
837 | @LoginRequired() | |
839 | @HasPermissionAllDecorator('hg.admin') |
|
838 | @HasPermissionAllDecorator('hg.admin') | |
840 | @CSRFRequired() |
|
839 | @CSRFRequired() | |
841 | @view_config( |
|
840 | @view_config( | |
842 | route_name='edit_user_ssh_keys_add', request_method='POST') |
|
841 | route_name='edit_user_ssh_keys_add', request_method='POST') | |
843 | def ssh_keys_add(self): |
|
842 | def ssh_keys_add(self): | |
844 | _ = self.request.translate |
|
843 | _ = self.request.translate | |
845 | c = self.load_default_context() |
|
844 | c = self.load_default_context() | |
846 |
|
845 | |||
847 | user_id = self.db_user_id |
|
846 | user_id = self.db_user_id | |
848 | c.user = self.db_user |
|
847 | c.user = self.db_user | |
849 |
|
848 | |||
850 | user_data = c.user.get_api_data() |
|
849 | user_data = c.user.get_api_data() | |
851 | key_data = self.request.POST.get('key_data') |
|
850 | key_data = self.request.POST.get('key_data') | |
852 | description = self.request.POST.get('description') |
|
851 | description = self.request.POST.get('description') | |
853 |
|
852 | |||
854 | fingerprint = 'unknown' |
|
853 | fingerprint = 'unknown' | |
855 | try: |
|
854 | try: | |
856 | if not key_data: |
|
855 | if not key_data: | |
857 | raise ValueError('Please add a valid public key') |
|
856 | raise ValueError('Please add a valid public key') | |
858 |
|
857 | |||
859 | key = SshKeyModel().parse_key(key_data.strip()) |
|
858 | key = SshKeyModel().parse_key(key_data.strip()) | |
860 | fingerprint = key.hash_md5() |
|
859 | fingerprint = key.hash_md5() | |
861 |
|
860 | |||
862 | ssh_key = SshKeyModel().create( |
|
861 | ssh_key = SshKeyModel().create( | |
863 | c.user.user_id, fingerprint, key.keydata, description) |
|
862 | c.user.user_id, fingerprint, key.keydata, description) | |
864 | ssh_key_data = ssh_key.get_api_data() |
|
863 | ssh_key_data = ssh_key.get_api_data() | |
865 |
|
864 | |||
866 | audit_logger.store_web( |
|
865 | audit_logger.store_web( | |
867 | 'user.edit.ssh_key.add', action_data={ |
|
866 | 'user.edit.ssh_key.add', action_data={ | |
868 | 'data': {'ssh_key': ssh_key_data, 'user': user_data}}, |
|
867 | 'data': {'ssh_key': ssh_key_data, 'user': user_data}}, | |
869 | user=self._rhodecode_user, ) |
|
868 | user=self._rhodecode_user, ) | |
870 | Session().commit() |
|
869 | Session().commit() | |
871 |
|
870 | |||
872 | # Trigger an event on change of keys. |
|
871 | # Trigger an event on change of keys. | |
873 | trigger(SshKeyFileChangeEvent(), self.request.registry) |
|
872 | trigger(SshKeyFileChangeEvent(), self.request.registry) | |
874 |
|
873 | |||
875 | h.flash(_("Ssh Key successfully created"), category='success') |
|
874 | h.flash(_("Ssh Key successfully created"), category='success') | |
876 |
|
875 | |||
877 | except IntegrityError: |
|
876 | except IntegrityError: | |
878 | log.exception("Exception during ssh key saving") |
|
877 | log.exception("Exception during ssh key saving") | |
879 | err = 'Such key with fingerprint `{}` already exists, ' \ |
|
878 | err = 'Such key with fingerprint `{}` already exists, ' \ | |
880 | 'please use a different one'.format(fingerprint) |
|
879 | 'please use a different one'.format(fingerprint) | |
881 | h.flash(_('An error occurred during ssh key saving: {}').format(err), |
|
880 | h.flash(_('An error occurred during ssh key saving: {}').format(err), | |
882 | category='error') |
|
881 | category='error') | |
883 | except Exception as e: |
|
882 | except Exception as e: | |
884 | log.exception("Exception during ssh key saving") |
|
883 | log.exception("Exception during ssh key saving") | |
885 | h.flash(_('An error occurred during ssh key saving: {}').format(e), |
|
884 | h.flash(_('An error occurred during ssh key saving: {}').format(e), | |
886 | category='error') |
|
885 | category='error') | |
887 |
|
886 | |||
888 | return HTTPFound( |
|
887 | return HTTPFound( | |
889 | h.route_path('edit_user_ssh_keys', user_id=user_id)) |
|
888 | h.route_path('edit_user_ssh_keys', user_id=user_id)) | |
890 |
|
889 | |||
891 | @LoginRequired() |
|
890 | @LoginRequired() | |
892 | @HasPermissionAllDecorator('hg.admin') |
|
891 | @HasPermissionAllDecorator('hg.admin') | |
893 | @CSRFRequired() |
|
892 | @CSRFRequired() | |
894 | @view_config( |
|
893 | @view_config( | |
895 | route_name='edit_user_ssh_keys_delete', request_method='POST') |
|
894 | route_name='edit_user_ssh_keys_delete', request_method='POST') | |
896 | def ssh_keys_delete(self): |
|
895 | def ssh_keys_delete(self): | |
897 | _ = self.request.translate |
|
896 | _ = self.request.translate | |
898 | c = self.load_default_context() |
|
897 | c = self.load_default_context() | |
899 |
|
898 | |||
900 | user_id = self.db_user_id |
|
899 | user_id = self.db_user_id | |
901 | c.user = self.db_user |
|
900 | c.user = self.db_user | |
902 |
|
901 | |||
903 | user_data = c.user.get_api_data() |
|
902 | user_data = c.user.get_api_data() | |
904 |
|
903 | |||
905 | del_ssh_key = self.request.POST.get('del_ssh_key') |
|
904 | del_ssh_key = self.request.POST.get('del_ssh_key') | |
906 |
|
905 | |||
907 | if del_ssh_key: |
|
906 | if del_ssh_key: | |
908 | ssh_key = UserSshKeys.get_or_404(del_ssh_key) |
|
907 | ssh_key = UserSshKeys.get_or_404(del_ssh_key) | |
909 | ssh_key_data = ssh_key.get_api_data() |
|
908 | ssh_key_data = ssh_key.get_api_data() | |
910 |
|
909 | |||
911 | SshKeyModel().delete(del_ssh_key, c.user.user_id) |
|
910 | SshKeyModel().delete(del_ssh_key, c.user.user_id) | |
912 | audit_logger.store_web( |
|
911 | audit_logger.store_web( | |
913 | 'user.edit.ssh_key.delete', action_data={ |
|
912 | 'user.edit.ssh_key.delete', action_data={ | |
914 | 'data': {'ssh_key': ssh_key_data, 'user': user_data}}, |
|
913 | 'data': {'ssh_key': ssh_key_data, 'user': user_data}}, | |
915 | user=self._rhodecode_user,) |
|
914 | user=self._rhodecode_user,) | |
916 | Session().commit() |
|
915 | Session().commit() | |
917 | # Trigger an event on change of keys. |
|
916 | # Trigger an event on change of keys. | |
918 | trigger(SshKeyFileChangeEvent(), self.request.registry) |
|
917 | trigger(SshKeyFileChangeEvent(), self.request.registry) | |
919 | h.flash(_("Ssh key successfully deleted"), category='success') |
|
918 | h.flash(_("Ssh key successfully deleted"), category='success') | |
920 |
|
919 | |||
921 | return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id)) |
|
920 | return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id)) | |
922 |
|
921 | |||
923 | @LoginRequired() |
|
922 | @LoginRequired() | |
924 | @HasPermissionAllDecorator('hg.admin') |
|
923 | @HasPermissionAllDecorator('hg.admin') | |
925 | @view_config( |
|
924 | @view_config( | |
926 | route_name='edit_user_emails', request_method='GET', |
|
925 | route_name='edit_user_emails', request_method='GET', | |
927 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
926 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
928 | def emails(self): |
|
927 | def emails(self): | |
929 | _ = self.request.translate |
|
928 | _ = self.request.translate | |
930 | c = self.load_default_context() |
|
929 | c = self.load_default_context() | |
931 | c.user = self.db_user |
|
930 | c.user = self.db_user | |
932 |
|
931 | |||
933 | c.active = 'emails' |
|
932 | c.active = 'emails' | |
934 | c.user_email_map = UserEmailMap.query() \ |
|
933 | c.user_email_map = UserEmailMap.query() \ | |
935 | .filter(UserEmailMap.user == c.user).all() |
|
934 | .filter(UserEmailMap.user == c.user).all() | |
936 |
|
935 | |||
937 | return self._get_template_context(c) |
|
936 | return self._get_template_context(c) | |
938 |
|
937 | |||
939 | @LoginRequired() |
|
938 | @LoginRequired() | |
940 | @HasPermissionAllDecorator('hg.admin') |
|
939 | @HasPermissionAllDecorator('hg.admin') | |
941 | @CSRFRequired() |
|
940 | @CSRFRequired() | |
942 | @view_config( |
|
941 | @view_config( | |
943 | route_name='edit_user_emails_add', request_method='POST') |
|
942 | route_name='edit_user_emails_add', request_method='POST') | |
944 | def emails_add(self): |
|
943 | def emails_add(self): | |
945 | _ = self.request.translate |
|
944 | _ = self.request.translate | |
946 | c = self.load_default_context() |
|
945 | c = self.load_default_context() | |
947 |
|
946 | |||
948 | user_id = self.db_user_id |
|
947 | user_id = self.db_user_id | |
949 | c.user = self.db_user |
|
948 | c.user = self.db_user | |
950 |
|
949 | |||
951 | email = self.request.POST.get('new_email') |
|
950 | email = self.request.POST.get('new_email') | |
952 | user_data = c.user.get_api_data() |
|
951 | user_data = c.user.get_api_data() | |
953 | try: |
|
952 | try: | |
954 |
|
953 | |||
955 | form = UserExtraEmailForm(self.request.translate)() |
|
954 | form = UserExtraEmailForm(self.request.translate)() | |
956 | data = form.to_python({'email': email}) |
|
955 | data = form.to_python({'email': email}) | |
957 | email = data['email'] |
|
956 | email = data['email'] | |
958 |
|
957 | |||
959 | UserModel().add_extra_email(c.user.user_id, email) |
|
958 | UserModel().add_extra_email(c.user.user_id, email) | |
960 | audit_logger.store_web( |
|
959 | audit_logger.store_web( | |
961 | 'user.edit.email.add', |
|
960 | 'user.edit.email.add', | |
962 | action_data={'email': email, 'user': user_data}, |
|
961 | action_data={'email': email, 'user': user_data}, | |
963 | user=self._rhodecode_user) |
|
962 | user=self._rhodecode_user) | |
964 | Session().commit() |
|
963 | Session().commit() | |
965 | h.flash(_("Added new email address `%s` for user account") % email, |
|
964 | h.flash(_("Added new email address `%s` for user account") % email, | |
966 | category='success') |
|
965 | category='success') | |
967 | except formencode.Invalid as error: |
|
966 | except formencode.Invalid as error: | |
968 | h.flash(h.escape(error.error_dict['email']), category='error') |
|
967 | h.flash(h.escape(error.error_dict['email']), category='error') | |
969 | except IntegrityError: |
|
968 | except IntegrityError: | |
970 | log.warning("Email %s already exists", email) |
|
969 | log.warning("Email %s already exists", email) | |
971 | h.flash(_('Email `{}` is already registered for another user.').format(email), |
|
970 | h.flash(_('Email `{}` is already registered for another user.').format(email), | |
972 | category='error') |
|
971 | category='error') | |
973 | except Exception: |
|
972 | except Exception: | |
974 | log.exception("Exception during email saving") |
|
973 | log.exception("Exception during email saving") | |
975 | h.flash(_('An error occurred during email saving'), |
|
974 | h.flash(_('An error occurred during email saving'), | |
976 | category='error') |
|
975 | category='error') | |
977 | raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id)) |
|
976 | raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id)) | |
978 |
|
977 | |||
979 | @LoginRequired() |
|
978 | @LoginRequired() | |
980 | @HasPermissionAllDecorator('hg.admin') |
|
979 | @HasPermissionAllDecorator('hg.admin') | |
981 | @CSRFRequired() |
|
980 | @CSRFRequired() | |
982 | @view_config( |
|
981 | @view_config( | |
983 | route_name='edit_user_emails_delete', request_method='POST') |
|
982 | route_name='edit_user_emails_delete', request_method='POST') | |
984 | def emails_delete(self): |
|
983 | def emails_delete(self): | |
985 | _ = self.request.translate |
|
984 | _ = self.request.translate | |
986 | c = self.load_default_context() |
|
985 | c = self.load_default_context() | |
987 |
|
986 | |||
988 | user_id = self.db_user_id |
|
987 | user_id = self.db_user_id | |
989 | c.user = self.db_user |
|
988 | c.user = self.db_user | |
990 |
|
989 | |||
991 | email_id = self.request.POST.get('del_email_id') |
|
990 | email_id = self.request.POST.get('del_email_id') | |
992 | user_model = UserModel() |
|
991 | user_model = UserModel() | |
993 |
|
992 | |||
994 | email = UserEmailMap.query().get(email_id).email |
|
993 | email = UserEmailMap.query().get(email_id).email | |
995 | user_data = c.user.get_api_data() |
|
994 | user_data = c.user.get_api_data() | |
996 | user_model.delete_extra_email(c.user.user_id, email_id) |
|
995 | user_model.delete_extra_email(c.user.user_id, email_id) | |
997 | audit_logger.store_web( |
|
996 | audit_logger.store_web( | |
998 | 'user.edit.email.delete', |
|
997 | 'user.edit.email.delete', | |
999 | action_data={'email': email, 'user': user_data}, |
|
998 | action_data={'email': email, 'user': user_data}, | |
1000 | user=self._rhodecode_user) |
|
999 | user=self._rhodecode_user) | |
1001 | Session().commit() |
|
1000 | Session().commit() | |
1002 | h.flash(_("Removed email address from user account"), |
|
1001 | h.flash(_("Removed email address from user account"), | |
1003 | category='success') |
|
1002 | category='success') | |
1004 | raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id)) |
|
1003 | raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id)) | |
1005 |
|
1004 | |||
1006 | @LoginRequired() |
|
1005 | @LoginRequired() | |
1007 | @HasPermissionAllDecorator('hg.admin') |
|
1006 | @HasPermissionAllDecorator('hg.admin') | |
1008 | @view_config( |
|
1007 | @view_config( | |
1009 | route_name='edit_user_ips', request_method='GET', |
|
1008 | route_name='edit_user_ips', request_method='GET', | |
1010 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
1009 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
1011 | def ips(self): |
|
1010 | def ips(self): | |
1012 | _ = self.request.translate |
|
1011 | _ = self.request.translate | |
1013 | c = self.load_default_context() |
|
1012 | c = self.load_default_context() | |
1014 | c.user = self.db_user |
|
1013 | c.user = self.db_user | |
1015 |
|
1014 | |||
1016 | c.active = 'ips' |
|
1015 | c.active = 'ips' | |
1017 | c.user_ip_map = UserIpMap.query() \ |
|
1016 | c.user_ip_map = UserIpMap.query() \ | |
1018 | .filter(UserIpMap.user == c.user).all() |
|
1017 | .filter(UserIpMap.user == c.user).all() | |
1019 |
|
1018 | |||
1020 | c.inherit_default_ips = c.user.inherit_default_permissions |
|
1019 | c.inherit_default_ips = c.user.inherit_default_permissions | |
1021 | c.default_user_ip_map = UserIpMap.query() \ |
|
1020 | c.default_user_ip_map = UserIpMap.query() \ | |
1022 | .filter(UserIpMap.user == User.get_default_user()).all() |
|
1021 | .filter(UserIpMap.user == User.get_default_user()).all() | |
1023 |
|
1022 | |||
1024 | return self._get_template_context(c) |
|
1023 | return self._get_template_context(c) | |
1025 |
|
1024 | |||
1026 | @LoginRequired() |
|
1025 | @LoginRequired() | |
1027 | @HasPermissionAllDecorator('hg.admin') |
|
1026 | @HasPermissionAllDecorator('hg.admin') | |
1028 | @CSRFRequired() |
|
1027 | @CSRFRequired() | |
1029 | @view_config( |
|
1028 | @view_config( | |
1030 | route_name='edit_user_ips_add', request_method='POST') |
|
1029 | route_name='edit_user_ips_add', request_method='POST') | |
1031 | # NOTE(marcink): this view is allowed for default users, as we can |
|
1030 | # NOTE(marcink): this view is allowed for default users, as we can | |
1032 | # edit their IP white list |
|
1031 | # edit their IP white list | |
1033 | def ips_add(self): |
|
1032 | def ips_add(self): | |
1034 | _ = self.request.translate |
|
1033 | _ = self.request.translate | |
1035 | c = self.load_default_context() |
|
1034 | c = self.load_default_context() | |
1036 |
|
1035 | |||
1037 | user_id = self.db_user_id |
|
1036 | user_id = self.db_user_id | |
1038 | c.user = self.db_user |
|
1037 | c.user = self.db_user | |
1039 |
|
1038 | |||
1040 | user_model = UserModel() |
|
1039 | user_model = UserModel() | |
1041 | desc = self.request.POST.get('description') |
|
1040 | desc = self.request.POST.get('description') | |
1042 | try: |
|
1041 | try: | |
1043 | ip_list = user_model.parse_ip_range( |
|
1042 | ip_list = user_model.parse_ip_range( | |
1044 | self.request.POST.get('new_ip')) |
|
1043 | self.request.POST.get('new_ip')) | |
1045 | except Exception as e: |
|
1044 | except Exception as e: | |
1046 | ip_list = [] |
|
1045 | ip_list = [] | |
1047 | log.exception("Exception during ip saving") |
|
1046 | log.exception("Exception during ip saving") | |
1048 | h.flash(_('An error occurred during ip saving:%s' % (e,)), |
|
1047 | h.flash(_('An error occurred during ip saving:%s' % (e,)), | |
1049 | category='error') |
|
1048 | category='error') | |
1050 | added = [] |
|
1049 | added = [] | |
1051 | user_data = c.user.get_api_data() |
|
1050 | user_data = c.user.get_api_data() | |
1052 | for ip in ip_list: |
|
1051 | for ip in ip_list: | |
1053 | try: |
|
1052 | try: | |
1054 | form = UserExtraIpForm(self.request.translate)() |
|
1053 | form = UserExtraIpForm(self.request.translate)() | |
1055 | data = form.to_python({'ip': ip}) |
|
1054 | data = form.to_python({'ip': ip}) | |
1056 | ip = data['ip'] |
|
1055 | ip = data['ip'] | |
1057 |
|
1056 | |||
1058 | user_model.add_extra_ip(c.user.user_id, ip, desc) |
|
1057 | user_model.add_extra_ip(c.user.user_id, ip, desc) | |
1059 | audit_logger.store_web( |
|
1058 | audit_logger.store_web( | |
1060 | 'user.edit.ip.add', |
|
1059 | 'user.edit.ip.add', | |
1061 | action_data={'ip': ip, 'user': user_data}, |
|
1060 | action_data={'ip': ip, 'user': user_data}, | |
1062 | user=self._rhodecode_user) |
|
1061 | user=self._rhodecode_user) | |
1063 | Session().commit() |
|
1062 | Session().commit() | |
1064 | added.append(ip) |
|
1063 | added.append(ip) | |
1065 | except formencode.Invalid as error: |
|
1064 | except formencode.Invalid as error: | |
1066 | msg = error.error_dict['ip'] |
|
1065 | msg = error.error_dict['ip'] | |
1067 | h.flash(msg, category='error') |
|
1066 | h.flash(msg, category='error') | |
1068 | except Exception: |
|
1067 | except Exception: | |
1069 | log.exception("Exception during ip saving") |
|
1068 | log.exception("Exception during ip saving") | |
1070 | h.flash(_('An error occurred during ip saving'), |
|
1069 | h.flash(_('An error occurred during ip saving'), | |
1071 | category='error') |
|
1070 | category='error') | |
1072 | if added: |
|
1071 | if added: | |
1073 | h.flash( |
|
1072 | h.flash( | |
1074 | _("Added ips %s to user whitelist") % (', '.join(ip_list), ), |
|
1073 | _("Added ips %s to user whitelist") % (', '.join(ip_list), ), | |
1075 | category='success') |
|
1074 | category='success') | |
1076 | if 'default_user' in self.request.POST: |
|
1075 | if 'default_user' in self.request.POST: | |
1077 | # case for editing global IP list we do it for 'DEFAULT' user |
|
1076 | # case for editing global IP list we do it for 'DEFAULT' user | |
1078 | raise HTTPFound(h.route_path('admin_permissions_ips')) |
|
1077 | raise HTTPFound(h.route_path('admin_permissions_ips')) | |
1079 | raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id)) |
|
1078 | raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id)) | |
1080 |
|
1079 | |||
1081 | @LoginRequired() |
|
1080 | @LoginRequired() | |
1082 | @HasPermissionAllDecorator('hg.admin') |
|
1081 | @HasPermissionAllDecorator('hg.admin') | |
1083 | @CSRFRequired() |
|
1082 | @CSRFRequired() | |
1084 | @view_config( |
|
1083 | @view_config( | |
1085 | route_name='edit_user_ips_delete', request_method='POST') |
|
1084 | route_name='edit_user_ips_delete', request_method='POST') | |
1086 | # NOTE(marcink): this view is allowed for default users, as we can |
|
1085 | # NOTE(marcink): this view is allowed for default users, as we can | |
1087 | # edit their IP white list |
|
1086 | # edit their IP white list | |
1088 | def ips_delete(self): |
|
1087 | def ips_delete(self): | |
1089 | _ = self.request.translate |
|
1088 | _ = self.request.translate | |
1090 | c = self.load_default_context() |
|
1089 | c = self.load_default_context() | |
1091 |
|
1090 | |||
1092 | user_id = self.db_user_id |
|
1091 | user_id = self.db_user_id | |
1093 | c.user = self.db_user |
|
1092 | c.user = self.db_user | |
1094 |
|
1093 | |||
1095 | ip_id = self.request.POST.get('del_ip_id') |
|
1094 | ip_id = self.request.POST.get('del_ip_id') | |
1096 | user_model = UserModel() |
|
1095 | user_model = UserModel() | |
1097 | user_data = c.user.get_api_data() |
|
1096 | user_data = c.user.get_api_data() | |
1098 | ip = UserIpMap.query().get(ip_id).ip_addr |
|
1097 | ip = UserIpMap.query().get(ip_id).ip_addr | |
1099 | user_model.delete_extra_ip(c.user.user_id, ip_id) |
|
1098 | user_model.delete_extra_ip(c.user.user_id, ip_id) | |
1100 | audit_logger.store_web( |
|
1099 | audit_logger.store_web( | |
1101 | 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data}, |
|
1100 | 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data}, | |
1102 | user=self._rhodecode_user) |
|
1101 | user=self._rhodecode_user) | |
1103 | Session().commit() |
|
1102 | Session().commit() | |
1104 | h.flash(_("Removed ip address from user whitelist"), category='success') |
|
1103 | h.flash(_("Removed ip address from user whitelist"), category='success') | |
1105 |
|
1104 | |||
1106 | if 'default_user' in self.request.POST: |
|
1105 | if 'default_user' in self.request.POST: | |
1107 | # case for editing global IP list we do it for 'DEFAULT' user |
|
1106 | # case for editing global IP list we do it for 'DEFAULT' user | |
1108 | raise HTTPFound(h.route_path('admin_permissions_ips')) |
|
1107 | raise HTTPFound(h.route_path('admin_permissions_ips')) | |
1109 | raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id)) |
|
1108 | raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id)) | |
1110 |
|
1109 | |||
1111 | @LoginRequired() |
|
1110 | @LoginRequired() | |
1112 | @HasPermissionAllDecorator('hg.admin') |
|
1111 | @HasPermissionAllDecorator('hg.admin') | |
1113 | @view_config( |
|
1112 | @view_config( | |
1114 | route_name='edit_user_groups_management', request_method='GET', |
|
1113 | route_name='edit_user_groups_management', request_method='GET', | |
1115 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
1114 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
1116 | def groups_management(self): |
|
1115 | def groups_management(self): | |
1117 | c = self.load_default_context() |
|
1116 | c = self.load_default_context() | |
1118 | c.user = self.db_user |
|
1117 | c.user = self.db_user | |
1119 | c.data = c.user.group_member |
|
1118 | c.data = c.user.group_member | |
1120 |
|
1119 | |||
1121 | groups = [UserGroupModel.get_user_groups_as_dict(group.users_group) |
|
1120 | groups = [UserGroupModel.get_user_groups_as_dict(group.users_group) | |
1122 | for group in c.user.group_member] |
|
1121 | for group in c.user.group_member] | |
1123 | c.groups = json.dumps(groups) |
|
1122 | c.groups = json.dumps(groups) | |
1124 | c.active = 'groups' |
|
1123 | c.active = 'groups' | |
1125 |
|
1124 | |||
1126 | return self._get_template_context(c) |
|
1125 | return self._get_template_context(c) | |
1127 |
|
1126 | |||
1128 | @LoginRequired() |
|
1127 | @LoginRequired() | |
1129 | @HasPermissionAllDecorator('hg.admin') |
|
1128 | @HasPermissionAllDecorator('hg.admin') | |
1130 | @CSRFRequired() |
|
1129 | @CSRFRequired() | |
1131 | @view_config( |
|
1130 | @view_config( | |
1132 | route_name='edit_user_groups_management_updates', request_method='POST') |
|
1131 | route_name='edit_user_groups_management_updates', request_method='POST') | |
1133 | def groups_management_updates(self): |
|
1132 | def groups_management_updates(self): | |
1134 | _ = self.request.translate |
|
1133 | _ = self.request.translate | |
1135 | c = self.load_default_context() |
|
1134 | c = self.load_default_context() | |
1136 |
|
1135 | |||
1137 | user_id = self.db_user_id |
|
1136 | user_id = self.db_user_id | |
1138 | c.user = self.db_user |
|
1137 | c.user = self.db_user | |
1139 |
|
1138 | |||
1140 | user_groups = set(self.request.POST.getall('users_group_id')) |
|
1139 | user_groups = set(self.request.POST.getall('users_group_id')) | |
1141 | user_groups_objects = [] |
|
1140 | user_groups_objects = [] | |
1142 |
|
1141 | |||
1143 | for ugid in user_groups: |
|
1142 | for ugid in user_groups: | |
1144 | user_groups_objects.append( |
|
1143 | user_groups_objects.append( | |
1145 | UserGroupModel().get_group(safe_int(ugid))) |
|
1144 | UserGroupModel().get_group(safe_int(ugid))) | |
1146 | user_group_model = UserGroupModel() |
|
1145 | user_group_model = UserGroupModel() | |
1147 | added_to_groups, removed_from_groups = \ |
|
1146 | added_to_groups, removed_from_groups = \ | |
1148 | user_group_model.change_groups(c.user, user_groups_objects) |
|
1147 | user_group_model.change_groups(c.user, user_groups_objects) | |
1149 |
|
1148 | |||
1150 | user_data = c.user.get_api_data() |
|
1149 | user_data = c.user.get_api_data() | |
1151 | for user_group_id in added_to_groups: |
|
1150 | for user_group_id in added_to_groups: | |
1152 | user_group = UserGroup.get(user_group_id) |
|
1151 | user_group = UserGroup.get(user_group_id) | |
1153 | old_values = user_group.get_api_data() |
|
1152 | old_values = user_group.get_api_data() | |
1154 | audit_logger.store_web( |
|
1153 | audit_logger.store_web( | |
1155 | 'user_group.edit.member.add', |
|
1154 | 'user_group.edit.member.add', | |
1156 | action_data={'user': user_data, 'old_data': old_values}, |
|
1155 | action_data={'user': user_data, 'old_data': old_values}, | |
1157 | user=self._rhodecode_user) |
|
1156 | user=self._rhodecode_user) | |
1158 |
|
1157 | |||
1159 | for user_group_id in removed_from_groups: |
|
1158 | for user_group_id in removed_from_groups: | |
1160 | user_group = UserGroup.get(user_group_id) |
|
1159 | user_group = UserGroup.get(user_group_id) | |
1161 | old_values = user_group.get_api_data() |
|
1160 | old_values = user_group.get_api_data() | |
1162 | audit_logger.store_web( |
|
1161 | audit_logger.store_web( | |
1163 | 'user_group.edit.member.delete', |
|
1162 | 'user_group.edit.member.delete', | |
1164 | action_data={'user': user_data, 'old_data': old_values}, |
|
1163 | action_data={'user': user_data, 'old_data': old_values}, | |
1165 | user=self._rhodecode_user) |
|
1164 | user=self._rhodecode_user) | |
1166 |
|
1165 | |||
1167 | Session().commit() |
|
1166 | Session().commit() | |
1168 | c.active = 'user_groups_management' |
|
1167 | c.active = 'user_groups_management' | |
1169 | h.flash(_("Groups successfully changed"), category='success') |
|
1168 | h.flash(_("Groups successfully changed"), category='success') | |
1170 |
|
1169 | |||
1171 | return HTTPFound(h.route_path( |
|
1170 | return HTTPFound(h.route_path( | |
1172 | 'edit_user_groups_management', user_id=user_id)) |
|
1171 | 'edit_user_groups_management', user_id=user_id)) | |
1173 |
|
1172 | |||
1174 | @LoginRequired() |
|
1173 | @LoginRequired() | |
1175 | @HasPermissionAllDecorator('hg.admin') |
|
1174 | @HasPermissionAllDecorator('hg.admin') | |
1176 | @view_config( |
|
1175 | @view_config( | |
1177 | route_name='edit_user_audit_logs', request_method='GET', |
|
1176 | route_name='edit_user_audit_logs', request_method='GET', | |
1178 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
1177 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
1179 | def user_audit_logs(self): |
|
1178 | def user_audit_logs(self): | |
1180 | _ = self.request.translate |
|
1179 | _ = self.request.translate | |
1181 | c = self.load_default_context() |
|
1180 | c = self.load_default_context() | |
1182 | c.user = self.db_user |
|
1181 | c.user = self.db_user | |
1183 |
|
1182 | |||
1184 | c.active = 'audit' |
|
1183 | c.active = 'audit' | |
1185 |
|
1184 | |||
1186 | p = safe_int(self.request.GET.get('page', 1), 1) |
|
1185 | p = safe_int(self.request.GET.get('page', 1), 1) | |
1187 |
|
1186 | |||
1188 | filter_term = self.request.GET.get('filter') |
|
1187 | filter_term = self.request.GET.get('filter') | |
1189 | user_log = UserModel().get_user_log(c.user, filter_term) |
|
1188 | user_log = UserModel().get_user_log(c.user, filter_term) | |
1190 |
|
1189 | |||
1191 | def url_generator(**kw): |
|
1190 | def url_generator(**kw): | |
1192 | if filter_term: |
|
1191 | if filter_term: | |
1193 | kw['filter'] = filter_term |
|
1192 | kw['filter'] = filter_term | |
1194 | return self.request.current_route_path(_query=kw) |
|
1193 | return self.request.current_route_path(_query=kw) | |
1195 |
|
1194 | |||
1196 | c.audit_logs = h.Page( |
|
1195 | c.audit_logs = h.Page( | |
1197 | user_log, page=p, items_per_page=10, url=url_generator) |
|
1196 | user_log, page=p, items_per_page=10, url=url_generator) | |
1198 | c.filter_term = filter_term |
|
1197 | c.filter_term = filter_term | |
1199 | return self._get_template_context(c) |
|
1198 | return self._get_template_context(c) | |
1200 |
|
1199 | |||
1201 | @LoginRequired() |
|
1200 | @LoginRequired() | |
1202 | @HasPermissionAllDecorator('hg.admin') |
|
1201 | @HasPermissionAllDecorator('hg.admin') | |
1203 | @view_config( |
|
1202 | @view_config( | |
1204 | route_name='edit_user_perms_summary', request_method='GET', |
|
1203 | route_name='edit_user_perms_summary', request_method='GET', | |
1205 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
1204 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
1206 | def user_perms_summary(self): |
|
1205 | def user_perms_summary(self): | |
1207 | _ = self.request.translate |
|
1206 | _ = self.request.translate | |
1208 | c = self.load_default_context() |
|
1207 | c = self.load_default_context() | |
1209 | c.user = self.db_user |
|
1208 | c.user = self.db_user | |
1210 |
|
1209 | |||
1211 | c.active = 'perms_summary' |
|
1210 | c.active = 'perms_summary' | |
1212 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) |
|
1211 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) | |
1213 |
|
1212 | |||
1214 | return self._get_template_context(c) |
|
1213 | return self._get_template_context(c) | |
1215 |
|
1214 | |||
1216 | @LoginRequired() |
|
1215 | @LoginRequired() | |
1217 | @HasPermissionAllDecorator('hg.admin') |
|
1216 | @HasPermissionAllDecorator('hg.admin') | |
1218 | @view_config( |
|
1217 | @view_config( | |
1219 | route_name='edit_user_perms_summary_json', request_method='GET', |
|
1218 | route_name='edit_user_perms_summary_json', request_method='GET', | |
1220 | renderer='json_ext') |
|
1219 | renderer='json_ext') | |
1221 | def user_perms_summary_json(self): |
|
1220 | def user_perms_summary_json(self): | |
1222 | self.load_default_context() |
|
1221 | self.load_default_context() | |
1223 | perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr) |
|
1222 | perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr) | |
1224 |
|
1223 | |||
1225 | return perm_user.permissions |
|
1224 | return perm_user.permissions | |
1226 |
|
1225 | |||
1227 | @LoginRequired() |
|
1226 | @LoginRequired() | |
1228 | @HasPermissionAllDecorator('hg.admin') |
|
1227 | @HasPermissionAllDecorator('hg.admin') | |
1229 | @view_config( |
|
1228 | @view_config( | |
1230 | route_name='edit_user_caches', request_method='GET', |
|
1229 | route_name='edit_user_caches', request_method='GET', | |
1231 | renderer='rhodecode:templates/admin/users/user_edit.mako') |
|
1230 | renderer='rhodecode:templates/admin/users/user_edit.mako') | |
1232 | def user_caches(self): |
|
1231 | def user_caches(self): | |
1233 | _ = self.request.translate |
|
1232 | _ = self.request.translate | |
1234 | c = self.load_default_context() |
|
1233 | c = self.load_default_context() | |
1235 | c.user = self.db_user |
|
1234 | c.user = self.db_user | |
1236 |
|
1235 | |||
1237 | c.active = 'caches' |
|
1236 | c.active = 'caches' | |
1238 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) |
|
1237 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) | |
1239 |
|
1238 | |||
1240 | cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id) |
|
1239 | cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id) | |
1241 | c.region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid) |
|
1240 | c.region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid) | |
1242 | c.backend = c.region.backend |
|
1241 | c.backend = c.region.backend | |
1243 | c.user_keys = sorted(c.region.backend.list_keys(prefix=cache_namespace_uid)) |
|
1242 | c.user_keys = sorted(c.region.backend.list_keys(prefix=cache_namespace_uid)) | |
1244 |
|
1243 | |||
1245 | return self._get_template_context(c) |
|
1244 | return self._get_template_context(c) | |
1246 |
|
1245 | |||
1247 | @LoginRequired() |
|
1246 | @LoginRequired() | |
1248 | @HasPermissionAllDecorator('hg.admin') |
|
1247 | @HasPermissionAllDecorator('hg.admin') | |
1249 | @CSRFRequired() |
|
1248 | @CSRFRequired() | |
1250 | @view_config( |
|
1249 | @view_config( | |
1251 | route_name='edit_user_caches_update', request_method='POST') |
|
1250 | route_name='edit_user_caches_update', request_method='POST') | |
1252 | def user_caches_update(self): |
|
1251 | def user_caches_update(self): | |
1253 | _ = self.request.translate |
|
1252 | _ = self.request.translate | |
1254 | c = self.load_default_context() |
|
1253 | c = self.load_default_context() | |
1255 | c.user = self.db_user |
|
1254 | c.user = self.db_user | |
1256 |
|
1255 | |||
1257 | c.active = 'caches' |
|
1256 | c.active = 'caches' | |
1258 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) |
|
1257 | c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr) | |
1259 |
|
1258 | |||
1260 | cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id) |
|
1259 | cache_namespace_uid = 'cache_user_auth.{}'.format(self.db_user.user_id) | |
1261 | del_keys = rc_cache.clear_cache_namespace('cache_perms', cache_namespace_uid) |
|
1260 | del_keys = rc_cache.clear_cache_namespace('cache_perms', cache_namespace_uid) | |
1262 |
|
1261 | |||
1263 | h.flash(_("Deleted {} cache keys").format(del_keys), category='success') |
|
1262 | h.flash(_("Deleted {} cache keys").format(del_keys), category='success') | |
1264 |
|
1263 | |||
1265 | return HTTPFound(h.route_path( |
|
1264 | return HTTPFound(h.route_path( | |
1266 | 'edit_user_caches', user_id=c.user.user_id)) |
|
1265 | 'edit_user_caches', user_id=c.user.user_id)) |
@@ -1,147 +1,147 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2016-2019 RhodeCode GmbH |
|
3 | # Copyright (C) 2016-2019 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | import os |
|
21 | import os | |
22 | import sys |
|
22 | import sys | |
23 | import logging |
|
23 | import logging | |
24 | import tempfile |
|
24 | import tempfile | |
25 | import textwrap |
|
25 | import textwrap | |
26 | import collections |
|
26 | import collections | |
27 | from .base import VcsServer |
|
27 | from .base import VcsServer | |
28 | from rhodecode.model.db import RhodeCodeUi |
|
28 | from rhodecode.model.db import RhodeCodeUi | |
29 | from rhodecode.model.settings import VcsSettingsModel |
|
29 | from rhodecode.model.settings import VcsSettingsModel | |
30 |
|
30 | |||
31 | log = logging.getLogger(__name__) |
|
31 | log = logging.getLogger(__name__) | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | class MercurialTunnelWrapper(object): |
|
34 | class MercurialTunnelWrapper(object): | |
35 | process = None |
|
35 | process = None | |
36 |
|
36 | |||
37 | def __init__(self, server): |
|
37 | def __init__(self, server): | |
38 | self.server = server |
|
38 | self.server = server | |
39 | self.stdin = sys.stdin |
|
39 | self.stdin = sys.stdin | |
40 | self.stdout = sys.stdout |
|
40 | self.stdout = sys.stdout | |
41 | self.hooks_env_fd, self.hooks_env_path = tempfile.mkstemp(prefix='hgrc_rhodecode_') |
|
41 | self.hooks_env_fd, self.hooks_env_path = tempfile.mkstemp(prefix='hgrc_rhodecode_') | |
42 |
|
42 | |||
43 | def create_hooks_env(self): |
|
43 | def create_hooks_env(self): | |
44 | repo_name = self.server.repo_name |
|
44 | repo_name = self.server.repo_name | |
45 | hg_flags = self.config_to_hgrc(repo_name) |
|
45 | hg_flags = self.server.config_to_hgrc(repo_name) | |
46 |
|
46 | |||
47 | content = textwrap.dedent( |
|
47 | content = textwrap.dedent( | |
48 | ''' |
|
48 | ''' | |
49 | # RhodeCode SSH hooks version=2.0.0 |
|
49 | # RhodeCode SSH hooks version=2.0.0 | |
50 | {custom} |
|
50 | {custom} | |
51 | ''' |
|
51 | ''' | |
52 | ).format(custom='\n'.join(hg_flags)) |
|
52 | ).format(custom='\n'.join(hg_flags)) | |
53 |
|
53 | |||
54 | root = self.server.get_root_store() |
|
54 | root = self.server.get_root_store() | |
55 | hgrc_custom = os.path.join(root, repo_name, '.hg', 'hgrc_rhodecode') |
|
55 | hgrc_custom = os.path.join(root, repo_name, '.hg', 'hgrc_rhodecode') | |
56 | hgrc_main = os.path.join(root, repo_name, '.hg', 'hgrc') |
|
56 | hgrc_main = os.path.join(root, repo_name, '.hg', 'hgrc') | |
57 |
|
57 | |||
58 | # cleanup custom hgrc file |
|
58 | # cleanup custom hgrc file | |
59 | if os.path.isfile(hgrc_custom): |
|
59 | if os.path.isfile(hgrc_custom): | |
60 | with open(hgrc_custom, 'wb') as f: |
|
60 | with open(hgrc_custom, 'wb') as f: | |
61 | f.write('') |
|
61 | f.write('') | |
62 | log.debug('Cleanup custom hgrc file under %s', hgrc_custom) |
|
62 | log.debug('Cleanup custom hgrc file under %s', hgrc_custom) | |
63 |
|
63 | |||
64 | # write temp |
|
64 | # write temp | |
65 | with os.fdopen(self.hooks_env_fd, 'w') as hooks_env_file: |
|
65 | with os.fdopen(self.hooks_env_fd, 'w') as hooks_env_file: | |
66 | hooks_env_file.write(content) |
|
66 | hooks_env_file.write(content) | |
67 |
|
67 | |||
68 | return self.hooks_env_path |
|
68 | return self.hooks_env_path | |
69 |
|
69 | |||
70 | def remove_configs(self): |
|
70 | def remove_configs(self): | |
71 | os.remove(self.hooks_env_path) |
|
71 | os.remove(self.hooks_env_path) | |
72 |
|
72 | |||
73 | def command(self, hgrc_path): |
|
73 | def command(self, hgrc_path): | |
74 | root = self.server.get_root_store() |
|
74 | root = self.server.get_root_store() | |
75 |
|
75 | |||
76 | command = ( |
|
76 | command = ( | |
77 | "cd {root}; HGRCPATH={hgrc} {hg_path} -R {root}{repo_name} " |
|
77 | "cd {root}; HGRCPATH={hgrc} {hg_path} -R {root}{repo_name} " | |
78 | "serve --stdio".format( |
|
78 | "serve --stdio".format( | |
79 | root=root, hg_path=self.server.hg_path, |
|
79 | root=root, hg_path=self.server.hg_path, | |
80 | repo_name=self.server.repo_name, hgrc=hgrc_path)) |
|
80 | repo_name=self.server.repo_name, hgrc=hgrc_path)) | |
81 | log.debug("Final CMD: %s", command) |
|
81 | log.debug("Final CMD: %s", command) | |
82 | return command |
|
82 | return command | |
83 |
|
83 | |||
84 | def run(self, extras): |
|
84 | def run(self, extras): | |
85 | # at this point we cannot tell, we do further ACL checks |
|
85 | # at this point we cannot tell, we do further ACL checks | |
86 | # inside the hooks |
|
86 | # inside the hooks | |
87 | action = '?' |
|
87 | action = '?' | |
88 | # permissions are check via `pre_push_ssh_auth` hook |
|
88 | # permissions are check via `pre_push_ssh_auth` hook | |
89 | self.server.update_environment(action=action, extras=extras) |
|
89 | self.server.update_environment(action=action, extras=extras) | |
90 | custom_hgrc_file = self.create_hooks_env() |
|
90 | custom_hgrc_file = self.create_hooks_env() | |
91 |
|
91 | |||
92 | try: |
|
92 | try: | |
93 | return os.system(self.command(custom_hgrc_file)) |
|
93 | return os.system(self.command(custom_hgrc_file)) | |
94 | finally: |
|
94 | finally: | |
95 | self.remove_configs() |
|
95 | self.remove_configs() | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | class MercurialServer(VcsServer): |
|
98 | class MercurialServer(VcsServer): | |
99 | backend = 'hg' |
|
99 | backend = 'hg' | |
100 | cli_flags = ['phases', 'largefiles', 'extensions', 'experimental', 'hooks'] |
|
100 | cli_flags = ['phases', 'largefiles', 'extensions', 'experimental', 'hooks'] | |
101 |
|
101 | |||
102 | def __init__(self, store, ini_path, repo_name, user, user_permissions, config, env): |
|
102 | def __init__(self, store, ini_path, repo_name, user, user_permissions, config, env): | |
103 | super(MercurialServer, self).__init__(user, user_permissions, config, env) |
|
103 | super(MercurialServer, self).__init__(user, user_permissions, config, env) | |
104 |
|
104 | |||
105 | self.store = store |
|
105 | self.store = store | |
106 | self.ini_path = ini_path |
|
106 | self.ini_path = ini_path | |
107 | self.repo_name = repo_name |
|
107 | self.repo_name = repo_name | |
108 | self._path = self.hg_path = config.get('app:main', 'ssh.executable.hg') |
|
108 | self._path = self.hg_path = config.get('app:main', 'ssh.executable.hg') | |
109 | self.tunnel = MercurialTunnelWrapper(server=self) |
|
109 | self.tunnel = MercurialTunnelWrapper(server=self) | |
110 |
|
110 | |||
111 | def config_to_hgrc(self, repo_name): |
|
111 | def config_to_hgrc(self, repo_name): | |
112 | ui_sections = collections.defaultdict(list) |
|
112 | ui_sections = collections.defaultdict(list) | |
113 | ui = VcsSettingsModel(repo=repo_name).get_ui_settings(section=None, key=None) |
|
113 | ui = VcsSettingsModel(repo=repo_name).get_ui_settings(section=None, key=None) | |
114 |
|
114 | |||
115 | # write default hooks |
|
115 | # write default hooks | |
116 | default_hooks = [ |
|
116 | default_hooks = [ | |
117 | ('pretxnchangegroup.ssh_auth', 'python:vcsserver.hooks.pre_push_ssh_auth'), |
|
117 | ('pretxnchangegroup.ssh_auth', 'python:vcsserver.hooks.pre_push_ssh_auth'), | |
118 | ('pretxnchangegroup.ssh', 'python:vcsserver.hooks.pre_push_ssh'), |
|
118 | ('pretxnchangegroup.ssh', 'python:vcsserver.hooks.pre_push_ssh'), | |
119 | ('changegroup.ssh', 'python:vcsserver.hooks.post_push_ssh'), |
|
119 | ('changegroup.ssh', 'python:vcsserver.hooks.post_push_ssh'), | |
120 |
|
120 | |||
121 | ('preoutgoing.ssh', 'python:vcsserver.hooks.pre_pull_ssh'), |
|
121 | ('preoutgoing.ssh', 'python:vcsserver.hooks.pre_pull_ssh'), | |
122 | ('outgoing.ssh', 'python:vcsserver.hooks.post_pull_ssh'), |
|
122 | ('outgoing.ssh', 'python:vcsserver.hooks.post_pull_ssh'), | |
123 | ] |
|
123 | ] | |
124 |
|
124 | |||
125 | for k, v in default_hooks: |
|
125 | for k, v in default_hooks: | |
126 | ui_sections['hooks'].append((k, v)) |
|
126 | ui_sections['hooks'].append((k, v)) | |
127 |
|
127 | |||
128 | for entry in ui: |
|
128 | for entry in ui: | |
129 | if not entry.active: |
|
129 | if not entry.active: | |
130 | continue |
|
130 | continue | |
131 | sec = entry.section |
|
131 | sec = entry.section | |
132 | key = entry.key |
|
132 | key = entry.key | |
133 |
|
133 | |||
134 | if sec in self.cli_flags: |
|
134 | if sec in self.cli_flags: | |
135 | # we want only custom hooks, so we skip builtins |
|
135 | # we want only custom hooks, so we skip builtins | |
136 | if sec == 'hooks' and key in RhodeCodeUi.HOOKS_BUILTIN: |
|
136 | if sec == 'hooks' and key in RhodeCodeUi.HOOKS_BUILTIN: | |
137 | continue |
|
137 | continue | |
138 |
|
138 | |||
139 | ui_sections[sec].append([key, entry.value]) |
|
139 | ui_sections[sec].append([key, entry.value]) | |
140 |
|
140 | |||
141 | flags = [] |
|
141 | flags = [] | |
142 | for _sec, key_val in ui_sections.items(): |
|
142 | for _sec, key_val in ui_sections.items(): | |
143 | flags.append(' ') |
|
143 | flags.append(' ') | |
144 | flags.append('[{}]'.format(_sec)) |
|
144 | flags.append('[{}]'.format(_sec)) | |
145 | for key, val in key_val: |
|
145 | for key, val in key_val: | |
146 | flags.append('{}= {}'.format(key, val)) |
|
146 | flags.append('{}= {}'.format(key, val)) | |
147 | return flags |
|
147 | return flags |
@@ -1,937 +1,941 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2014-2019 RhodeCode GmbH |
|
3 | # Copyright (C) 2014-2019 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | """ |
|
21 | """ | |
22 | HG repository module |
|
22 | HG repository module | |
23 | """ |
|
23 | """ | |
24 | import os |
|
24 | import os | |
25 | import logging |
|
25 | import logging | |
26 | import binascii |
|
26 | import binascii | |
27 | import urllib |
|
27 | import urllib | |
28 |
|
28 | |||
29 | from zope.cachedescriptors.property import Lazy as LazyProperty |
|
29 | from zope.cachedescriptors.property import Lazy as LazyProperty | |
30 |
|
30 | |||
31 | from rhodecode.lib.compat import OrderedDict |
|
31 | from rhodecode.lib.compat import OrderedDict | |
32 | from rhodecode.lib.datelib import ( |
|
32 | from rhodecode.lib.datelib import ( | |
33 | date_to_timestamp_plus_offset, utcdate_fromtimestamp, makedate) |
|
33 | date_to_timestamp_plus_offset, utcdate_fromtimestamp, makedate) | |
34 | from rhodecode.lib.utils import safe_unicode, safe_str |
|
34 | from rhodecode.lib.utils import safe_unicode, safe_str | |
35 | from rhodecode.lib.vcs import connection, exceptions |
|
35 | from rhodecode.lib.vcs import connection, exceptions | |
36 | from rhodecode.lib.vcs.backends.base import ( |
|
36 | from rhodecode.lib.vcs.backends.base import ( | |
37 | BaseRepository, CollectionGenerator, Config, MergeResponse, |
|
37 | BaseRepository, CollectionGenerator, Config, MergeResponse, | |
38 | MergeFailureReason, Reference, BasePathPermissionChecker) |
|
38 | MergeFailureReason, Reference, BasePathPermissionChecker) | |
39 | from rhodecode.lib.vcs.backends.hg.commit import MercurialCommit |
|
39 | from rhodecode.lib.vcs.backends.hg.commit import MercurialCommit | |
40 | from rhodecode.lib.vcs.backends.hg.diff import MercurialDiff |
|
40 | from rhodecode.lib.vcs.backends.hg.diff import MercurialDiff | |
41 | from rhodecode.lib.vcs.backends.hg.inmemory import MercurialInMemoryCommit |
|
41 | from rhodecode.lib.vcs.backends.hg.inmemory import MercurialInMemoryCommit | |
42 | from rhodecode.lib.vcs.exceptions import ( |
|
42 | from rhodecode.lib.vcs.exceptions import ( | |
43 | EmptyRepositoryError, RepositoryError, TagAlreadyExistError, |
|
43 | EmptyRepositoryError, RepositoryError, TagAlreadyExistError, | |
44 | TagDoesNotExistError, CommitDoesNotExistError, SubrepoMergeError) |
|
44 | TagDoesNotExistError, CommitDoesNotExistError, SubrepoMergeError) | |
45 | from rhodecode.lib.vcs.compat import configparser |
|
45 | from rhodecode.lib.vcs.compat import configparser | |
46 |
|
46 | |||
47 | hexlify = binascii.hexlify |
|
47 | hexlify = binascii.hexlify | |
48 | nullid = "\0" * 20 |
|
48 | nullid = "\0" * 20 | |
49 |
|
49 | |||
50 | log = logging.getLogger(__name__) |
|
50 | log = logging.getLogger(__name__) | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | class MercurialRepository(BaseRepository): |
|
53 | class MercurialRepository(BaseRepository): | |
54 | """ |
|
54 | """ | |
55 | Mercurial repository backend |
|
55 | Mercurial repository backend | |
56 | """ |
|
56 | """ | |
57 | DEFAULT_BRANCH_NAME = 'default' |
|
57 | DEFAULT_BRANCH_NAME = 'default' | |
58 |
|
58 | |||
59 | def __init__(self, repo_path, config=None, create=False, src_url=None, |
|
59 | def __init__(self, repo_path, config=None, create=False, src_url=None, | |
60 | do_workspace_checkout=False, with_wire=None, bare=False): |
|
60 | do_workspace_checkout=False, with_wire=None, bare=False): | |
61 | """ |
|
61 | """ | |
62 | Raises RepositoryError if repository could not be find at the given |
|
62 | Raises RepositoryError if repository could not be find at the given | |
63 | ``repo_path``. |
|
63 | ``repo_path``. | |
64 |
|
64 | |||
65 | :param repo_path: local path of the repository |
|
65 | :param repo_path: local path of the repository | |
66 | :param config: config object containing the repo configuration |
|
66 | :param config: config object containing the repo configuration | |
67 | :param create=False: if set to True, would try to create repository if |
|
67 | :param create=False: if set to True, would try to create repository if | |
68 | it does not exist rather than raising exception |
|
68 | it does not exist rather than raising exception | |
69 | :param src_url=None: would try to clone repository from given location |
|
69 | :param src_url=None: would try to clone repository from given location | |
70 | :param do_workspace_checkout=False: sets update of working copy after |
|
70 | :param do_workspace_checkout=False: sets update of working copy after | |
71 | making a clone |
|
71 | making a clone | |
72 | :param bare: not used, compatible with other VCS |
|
72 | :param bare: not used, compatible with other VCS | |
73 | """ |
|
73 | """ | |
74 |
|
74 | |||
75 | self.path = safe_str(os.path.abspath(repo_path)) |
|
75 | self.path = safe_str(os.path.abspath(repo_path)) | |
76 | # mercurial since 4.4.X requires certain configuration to be present |
|
76 | # mercurial since 4.4.X requires certain configuration to be present | |
77 | # because sometimes we init the repos with config we need to meet |
|
77 | # because sometimes we init the repos with config we need to meet | |
78 | # special requirements |
|
78 | # special requirements | |
79 | self.config = config if config else self.get_default_config( |
|
79 | self.config = config if config else self.get_default_config( | |
80 | default=[('extensions', 'largefiles', '1')]) |
|
80 | default=[('extensions', 'largefiles', '1')]) | |
81 | self.with_wire = with_wire |
|
81 | self.with_wire = with_wire | |
82 |
|
82 | |||
83 | self._init_repo(create, src_url, do_workspace_checkout) |
|
83 | self._init_repo(create, src_url, do_workspace_checkout) | |
84 |
|
84 | |||
85 | # caches |
|
85 | # caches | |
86 | self._commit_ids = {} |
|
86 | self._commit_ids = {} | |
87 |
|
87 | |||
88 | @LazyProperty |
|
88 | @LazyProperty | |
89 | def _remote(self): |
|
89 | def _remote(self): | |
90 | return connection.Hg(self.path, self.config, with_wire=self.with_wire) |
|
90 | return connection.Hg(self.path, self.config, with_wire=self.with_wire) | |
91 |
|
91 | |||
92 | @LazyProperty |
|
92 | @LazyProperty | |
93 | def commit_ids(self): |
|
93 | def commit_ids(self): | |
94 | """ |
|
94 | """ | |
95 | Returns list of commit ids, in ascending order. Being lazy |
|
95 | Returns list of commit ids, in ascending order. Being lazy | |
96 | attribute allows external tools to inject shas from cache. |
|
96 | attribute allows external tools to inject shas from cache. | |
97 | """ |
|
97 | """ | |
98 | commit_ids = self._get_all_commit_ids() |
|
98 | commit_ids = self._get_all_commit_ids() | |
99 | self._rebuild_cache(commit_ids) |
|
99 | self._rebuild_cache(commit_ids) | |
100 | return commit_ids |
|
100 | return commit_ids | |
101 |
|
101 | |||
102 | def _rebuild_cache(self, commit_ids): |
|
102 | def _rebuild_cache(self, commit_ids): | |
103 | self._commit_ids = dict((commit_id, index) |
|
103 | self._commit_ids = dict((commit_id, index) | |
104 | for index, commit_id in enumerate(commit_ids)) |
|
104 | for index, commit_id in enumerate(commit_ids)) | |
105 |
|
105 | |||
106 | @LazyProperty |
|
106 | @LazyProperty | |
107 | def branches(self): |
|
107 | def branches(self): | |
108 | return self._get_branches() |
|
108 | return self._get_branches() | |
109 |
|
109 | |||
110 | @LazyProperty |
|
110 | @LazyProperty | |
111 | def branches_closed(self): |
|
111 | def branches_closed(self): | |
112 | return self._get_branches(active=False, closed=True) |
|
112 | return self._get_branches(active=False, closed=True) | |
113 |
|
113 | |||
114 | @LazyProperty |
|
114 | @LazyProperty | |
115 | def branches_all(self): |
|
115 | def branches_all(self): | |
116 | all_branches = {} |
|
116 | all_branches = {} | |
117 | all_branches.update(self.branches) |
|
117 | all_branches.update(self.branches) | |
118 | all_branches.update(self.branches_closed) |
|
118 | all_branches.update(self.branches_closed) | |
119 | return all_branches |
|
119 | return all_branches | |
120 |
|
120 | |||
121 | def _get_branches(self, active=True, closed=False): |
|
121 | def _get_branches(self, active=True, closed=False): | |
122 | """ |
|
122 | """ | |
123 | Gets branches for this repository |
|
123 | Gets branches for this repository | |
124 | Returns only not closed active branches by default |
|
124 | Returns only not closed active branches by default | |
125 |
|
125 | |||
126 | :param active: return also active branches |
|
126 | :param active: return also active branches | |
127 | :param closed: return also closed branches |
|
127 | :param closed: return also closed branches | |
128 |
|
128 | |||
129 | """ |
|
129 | """ | |
130 | if self.is_empty(): |
|
130 | if self.is_empty(): | |
131 | return {} |
|
131 | return {} | |
132 |
|
132 | |||
133 | def get_name(ctx): |
|
133 | def get_name(ctx): | |
134 | return ctx[0] |
|
134 | return ctx[0] | |
135 |
|
135 | |||
136 | _branches = [(safe_unicode(n), hexlify(h),) for n, h in |
|
136 | _branches = [(safe_unicode(n), hexlify(h),) for n, h in | |
137 | self._remote.branches(active, closed).items()] |
|
137 | self._remote.branches(active, closed).items()] | |
138 |
|
138 | |||
139 | return OrderedDict(sorted(_branches, key=get_name, reverse=False)) |
|
139 | return OrderedDict(sorted(_branches, key=get_name, reverse=False)) | |
140 |
|
140 | |||
141 | @LazyProperty |
|
141 | @LazyProperty | |
142 | def tags(self): |
|
142 | def tags(self): | |
143 | """ |
|
143 | """ | |
144 | Gets tags for this repository |
|
144 | Gets tags for this repository | |
145 | """ |
|
145 | """ | |
146 | return self._get_tags() |
|
146 | return self._get_tags() | |
147 |
|
147 | |||
148 | def _get_tags(self): |
|
148 | def _get_tags(self): | |
149 | if self.is_empty(): |
|
149 | if self.is_empty(): | |
150 | return {} |
|
150 | return {} | |
151 |
|
151 | |||
152 | def get_name(ctx): |
|
152 | def get_name(ctx): | |
153 | return ctx[0] |
|
153 | return ctx[0] | |
154 |
|
154 | |||
155 | _tags = [(safe_unicode(n), hexlify(h),) for n, h in |
|
155 | _tags = [(safe_unicode(n), hexlify(h),) for n, h in | |
156 | self._remote.tags().items()] |
|
156 | self._remote.tags().items()] | |
157 |
|
157 | |||
158 | return OrderedDict(sorted(_tags, key=get_name, reverse=True)) |
|
158 | return OrderedDict(sorted(_tags, key=get_name, reverse=True)) | |
159 |
|
159 | |||
160 | def tag(self, name, user, commit_id=None, message=None, date=None, |
|
160 | def tag(self, name, user, commit_id=None, message=None, date=None, | |
161 | **kwargs): |
|
161 | **kwargs): | |
162 | """ |
|
162 | """ | |
163 | Creates and returns a tag for the given ``commit_id``. |
|
163 | Creates and returns a tag for the given ``commit_id``. | |
164 |
|
164 | |||
165 | :param name: name for new tag |
|
165 | :param name: name for new tag | |
166 | :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" |
|
166 | :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" | |
167 | :param commit_id: commit id for which new tag would be created |
|
167 | :param commit_id: commit id for which new tag would be created | |
168 | :param message: message of the tag's commit |
|
168 | :param message: message of the tag's commit | |
169 | :param date: date of tag's commit |
|
169 | :param date: date of tag's commit | |
170 |
|
170 | |||
171 | :raises TagAlreadyExistError: if tag with same name already exists |
|
171 | :raises TagAlreadyExistError: if tag with same name already exists | |
172 | """ |
|
172 | """ | |
173 | if name in self.tags: |
|
173 | if name in self.tags: | |
174 | raise TagAlreadyExistError("Tag %s already exists" % name) |
|
174 | raise TagAlreadyExistError("Tag %s already exists" % name) | |
175 | commit = self.get_commit(commit_id=commit_id) |
|
175 | commit = self.get_commit(commit_id=commit_id) | |
176 | local = kwargs.setdefault('local', False) |
|
176 | local = kwargs.setdefault('local', False) | |
177 |
|
177 | |||
178 | if message is None: |
|
178 | if message is None: | |
179 | message = "Added tag %s for commit %s" % (name, commit.short_id) |
|
179 | message = "Added tag %s for commit %s" % (name, commit.short_id) | |
180 |
|
180 | |||
181 | date, tz = date_to_timestamp_plus_offset(date) |
|
181 | date, tz = date_to_timestamp_plus_offset(date) | |
182 |
|
182 | |||
183 | self._remote.tag( |
|
183 | self._remote.tag( | |
184 | name, commit.raw_id, message, local, user, date, tz) |
|
184 | name, commit.raw_id, message, local, user, date, tz) | |
185 | self._remote.invalidate_vcs_cache() |
|
185 | self._remote.invalidate_vcs_cache() | |
186 |
|
186 | |||
187 | # Reinitialize tags |
|
187 | # Reinitialize tags | |
188 | self.tags = self._get_tags() |
|
188 | self.tags = self._get_tags() | |
189 | tag_id = self.tags[name] |
|
189 | tag_id = self.tags[name] | |
190 |
|
190 | |||
191 | return self.get_commit(commit_id=tag_id) |
|
191 | return self.get_commit(commit_id=tag_id) | |
192 |
|
192 | |||
193 | def remove_tag(self, name, user, message=None, date=None): |
|
193 | def remove_tag(self, name, user, message=None, date=None): | |
194 | """ |
|
194 | """ | |
195 | Removes tag with the given `name`. |
|
195 | Removes tag with the given `name`. | |
196 |
|
196 | |||
197 | :param name: name of the tag to be removed |
|
197 | :param name: name of the tag to be removed | |
198 | :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" |
|
198 | :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" | |
199 | :param message: message of the tag's removal commit |
|
199 | :param message: message of the tag's removal commit | |
200 | :param date: date of tag's removal commit |
|
200 | :param date: date of tag's removal commit | |
201 |
|
201 | |||
202 | :raises TagDoesNotExistError: if tag with given name does not exists |
|
202 | :raises TagDoesNotExistError: if tag with given name does not exists | |
203 | """ |
|
203 | """ | |
204 | if name not in self.tags: |
|
204 | if name not in self.tags: | |
205 | raise TagDoesNotExistError("Tag %s does not exist" % name) |
|
205 | raise TagDoesNotExistError("Tag %s does not exist" % name) | |
206 | if message is None: |
|
206 | if message is None: | |
207 | message = "Removed tag %s" % name |
|
207 | message = "Removed tag %s" % name | |
208 | local = False |
|
208 | local = False | |
209 |
|
209 | |||
210 | date, tz = date_to_timestamp_plus_offset(date) |
|
210 | date, tz = date_to_timestamp_plus_offset(date) | |
211 |
|
211 | |||
212 | self._remote.tag(name, nullid, message, local, user, date, tz) |
|
212 | self._remote.tag(name, nullid, message, local, user, date, tz) | |
213 | self._remote.invalidate_vcs_cache() |
|
213 | self._remote.invalidate_vcs_cache() | |
214 | self.tags = self._get_tags() |
|
214 | self.tags = self._get_tags() | |
215 |
|
215 | |||
216 | @LazyProperty |
|
216 | @LazyProperty | |
217 | def bookmarks(self): |
|
217 | def bookmarks(self): | |
218 | """ |
|
218 | """ | |
219 | Gets bookmarks for this repository |
|
219 | Gets bookmarks for this repository | |
220 | """ |
|
220 | """ | |
221 | return self._get_bookmarks() |
|
221 | return self._get_bookmarks() | |
222 |
|
222 | |||
223 | def _get_bookmarks(self): |
|
223 | def _get_bookmarks(self): | |
224 | if self.is_empty(): |
|
224 | if self.is_empty(): | |
225 | return {} |
|
225 | return {} | |
226 |
|
226 | |||
227 | def get_name(ctx): |
|
227 | def get_name(ctx): | |
228 | return ctx[0] |
|
228 | return ctx[0] | |
229 |
|
229 | |||
230 | _bookmarks = [ |
|
230 | _bookmarks = [ | |
231 | (safe_unicode(n), hexlify(h)) for n, h in |
|
231 | (safe_unicode(n), hexlify(h)) for n, h in | |
232 | self._remote.bookmarks().items()] |
|
232 | self._remote.bookmarks().items()] | |
233 |
|
233 | |||
234 | return OrderedDict(sorted(_bookmarks, key=get_name)) |
|
234 | return OrderedDict(sorted(_bookmarks, key=get_name)) | |
235 |
|
235 | |||
236 | def _get_all_commit_ids(self): |
|
236 | def _get_all_commit_ids(self): | |
237 | return self._remote.get_all_commit_ids('visible') |
|
237 | return self._remote.get_all_commit_ids('visible') | |
238 |
|
238 | |||
239 | def get_diff( |
|
239 | def get_diff( | |
240 | self, commit1, commit2, path='', ignore_whitespace=False, |
|
240 | self, commit1, commit2, path='', ignore_whitespace=False, | |
241 | context=3, path1=None): |
|
241 | context=3, path1=None): | |
242 | """ |
|
242 | """ | |
243 | Returns (git like) *diff*, as plain text. Shows changes introduced by |
|
243 | Returns (git like) *diff*, as plain text. Shows changes introduced by | |
244 | `commit2` since `commit1`. |
|
244 | `commit2` since `commit1`. | |
245 |
|
245 | |||
246 | :param commit1: Entry point from which diff is shown. Can be |
|
246 | :param commit1: Entry point from which diff is shown. Can be | |
247 | ``self.EMPTY_COMMIT`` - in this case, patch showing all |
|
247 | ``self.EMPTY_COMMIT`` - in this case, patch showing all | |
248 | the changes since empty state of the repository until `commit2` |
|
248 | the changes since empty state of the repository until `commit2` | |
249 | :param commit2: Until which commit changes should be shown. |
|
249 | :param commit2: Until which commit changes should be shown. | |
250 | :param ignore_whitespace: If set to ``True``, would not show whitespace |
|
250 | :param ignore_whitespace: If set to ``True``, would not show whitespace | |
251 | changes. Defaults to ``False``. |
|
251 | changes. Defaults to ``False``. | |
252 | :param context: How many lines before/after changed lines should be |
|
252 | :param context: How many lines before/after changed lines should be | |
253 | shown. Defaults to ``3``. |
|
253 | shown. Defaults to ``3``. | |
254 | """ |
|
254 | """ | |
255 | self._validate_diff_commits(commit1, commit2) |
|
255 | self._validate_diff_commits(commit1, commit2) | |
256 | if path1 is not None and path1 != path: |
|
256 | if path1 is not None and path1 != path: | |
257 | raise ValueError("Diff of two different paths not supported.") |
|
257 | raise ValueError("Diff of two different paths not supported.") | |
258 |
|
258 | |||
259 | if path: |
|
259 | if path: | |
260 | file_filter = [self.path, path] |
|
260 | file_filter = [self.path, path] | |
261 | else: |
|
261 | else: | |
262 | file_filter = None |
|
262 | file_filter = None | |
263 |
|
263 | |||
264 | diff = self._remote.diff( |
|
264 | diff = self._remote.diff( | |
265 | commit1.raw_id, commit2.raw_id, file_filter=file_filter, |
|
265 | commit1.raw_id, commit2.raw_id, file_filter=file_filter, | |
266 | opt_git=True, opt_ignorews=ignore_whitespace, |
|
266 | opt_git=True, opt_ignorews=ignore_whitespace, | |
267 | context=context) |
|
267 | context=context) | |
268 | return MercurialDiff(diff) |
|
268 | return MercurialDiff(diff) | |
269 |
|
269 | |||
270 | def strip(self, commit_id, branch=None): |
|
270 | def strip(self, commit_id, branch=None): | |
271 | self._remote.strip(commit_id, update=False, backup="none") |
|
271 | self._remote.strip(commit_id, update=False, backup="none") | |
272 |
|
272 | |||
273 | self._remote.invalidate_vcs_cache() |
|
273 | self._remote.invalidate_vcs_cache() | |
274 | self.commit_ids = self._get_all_commit_ids() |
|
274 | self.commit_ids = self._get_all_commit_ids() | |
275 | self._rebuild_cache(self.commit_ids) |
|
275 | self._rebuild_cache(self.commit_ids) | |
276 |
|
276 | |||
277 | def verify(self): |
|
277 | def verify(self): | |
278 | verify = self._remote.verify() |
|
278 | verify = self._remote.verify() | |
279 |
|
279 | |||
280 | self._remote.invalidate_vcs_cache() |
|
280 | self._remote.invalidate_vcs_cache() | |
281 | return verify |
|
281 | return verify | |
282 |
|
282 | |||
283 | def get_common_ancestor(self, commit_id1, commit_id2, repo2): |
|
283 | def get_common_ancestor(self, commit_id1, commit_id2, repo2): | |
284 | if commit_id1 == commit_id2: |
|
284 | if commit_id1 == commit_id2: | |
285 | return commit_id1 |
|
285 | return commit_id1 | |
286 |
|
286 | |||
287 | ancestors = self._remote.revs_from_revspec( |
|
287 | ancestors = self._remote.revs_from_revspec( | |
288 | "ancestor(id(%s), id(%s))", commit_id1, commit_id2, |
|
288 | "ancestor(id(%s), id(%s))", commit_id1, commit_id2, | |
289 | other_path=repo2.path) |
|
289 | other_path=repo2.path) | |
290 | return repo2[ancestors[0]].raw_id if ancestors else None |
|
290 | return repo2[ancestors[0]].raw_id if ancestors else None | |
291 |
|
291 | |||
292 | def compare(self, commit_id1, commit_id2, repo2, merge, pre_load=None): |
|
292 | def compare(self, commit_id1, commit_id2, repo2, merge, pre_load=None): | |
293 | if commit_id1 == commit_id2: |
|
293 | if commit_id1 == commit_id2: | |
294 | commits = [] |
|
294 | commits = [] | |
295 | else: |
|
295 | else: | |
296 | if merge: |
|
296 | if merge: | |
297 | indexes = self._remote.revs_from_revspec( |
|
297 | indexes = self._remote.revs_from_revspec( | |
298 | "ancestors(id(%s)) - ancestors(id(%s)) - id(%s)", |
|
298 | "ancestors(id(%s)) - ancestors(id(%s)) - id(%s)", | |
299 | commit_id2, commit_id1, commit_id1, other_path=repo2.path) |
|
299 | commit_id2, commit_id1, commit_id1, other_path=repo2.path) | |
300 | else: |
|
300 | else: | |
301 | indexes = self._remote.revs_from_revspec( |
|
301 | indexes = self._remote.revs_from_revspec( | |
302 | "id(%s)..id(%s) - id(%s)", commit_id1, commit_id2, |
|
302 | "id(%s)..id(%s) - id(%s)", commit_id1, commit_id2, | |
303 | commit_id1, other_path=repo2.path) |
|
303 | commit_id1, other_path=repo2.path) | |
304 |
|
304 | |||
305 | commits = [repo2.get_commit(commit_idx=idx, pre_load=pre_load) |
|
305 | commits = [repo2.get_commit(commit_idx=idx, pre_load=pre_load) | |
306 | for idx in indexes] |
|
306 | for idx in indexes] | |
307 |
|
307 | |||
308 | return commits |
|
308 | return commits | |
309 |
|
309 | |||
310 | @staticmethod |
|
310 | @staticmethod | |
311 | def check_url(url, config): |
|
311 | def check_url(url, config): | |
312 | """ |
|
312 | """ | |
313 | Function will check given url and try to verify if it's a valid |
|
313 | Function will check given url and try to verify if it's a valid | |
314 | link. Sometimes it may happened that mercurial will issue basic |
|
314 | link. Sometimes it may happened that mercurial will issue basic | |
315 | auth request that can cause whole API to hang when used from python |
|
315 | auth request that can cause whole API to hang when used from python | |
316 | or other external calls. |
|
316 | or other external calls. | |
317 |
|
317 | |||
318 | On failures it'll raise urllib2.HTTPError, exception is also thrown |
|
318 | On failures it'll raise urllib2.HTTPError, exception is also thrown | |
319 | when the return code is non 200 |
|
319 | when the return code is non 200 | |
320 | """ |
|
320 | """ | |
321 | # check first if it's not an local url |
|
321 | # check first if it's not an local url | |
322 | if os.path.isdir(url) or url.startswith('file:'): |
|
322 | if os.path.isdir(url) or url.startswith('file:'): | |
323 | return True |
|
323 | return True | |
324 |
|
324 | |||
325 | # Request the _remote to verify the url |
|
325 | # Request the _remote to verify the url | |
326 | return connection.Hg.check_url(url, config.serialize()) |
|
326 | return connection.Hg.check_url(url, config.serialize()) | |
327 |
|
327 | |||
328 | @staticmethod |
|
328 | @staticmethod | |
329 | def is_valid_repository(path): |
|
329 | def is_valid_repository(path): | |
330 | return os.path.isdir(os.path.join(path, '.hg')) |
|
330 | return os.path.isdir(os.path.join(path, '.hg')) | |
331 |
|
331 | |||
332 | def _init_repo(self, create, src_url=None, do_workspace_checkout=False): |
|
332 | def _init_repo(self, create, src_url=None, do_workspace_checkout=False): | |
333 | """ |
|
333 | """ | |
334 | Function will check for mercurial repository in given path. If there |
|
334 | Function will check for mercurial repository in given path. If there | |
335 | is no repository in that path it will raise an exception unless |
|
335 | is no repository in that path it will raise an exception unless | |
336 | `create` parameter is set to True - in that case repository would |
|
336 | `create` parameter is set to True - in that case repository would | |
337 | be created. |
|
337 | be created. | |
338 |
|
338 | |||
339 | If `src_url` is given, would try to clone repository from the |
|
339 | If `src_url` is given, would try to clone repository from the | |
340 | location at given clone_point. Additionally it'll make update to |
|
340 | location at given clone_point. Additionally it'll make update to | |
341 | working copy accordingly to `do_workspace_checkout` flag. |
|
341 | working copy accordingly to `do_workspace_checkout` flag. | |
342 | """ |
|
342 | """ | |
343 | if create and os.path.exists(self.path): |
|
343 | if create and os.path.exists(self.path): | |
344 | raise RepositoryError( |
|
344 | raise RepositoryError( | |
345 | "Cannot create repository at %s, location already exist" |
|
345 | "Cannot create repository at %s, location already exist" | |
346 | % self.path) |
|
346 | % self.path) | |
347 |
|
347 | |||
348 | if src_url: |
|
348 | if src_url: | |
349 | url = str(self._get_url(src_url)) |
|
349 | url = str(self._get_url(src_url)) | |
350 | MercurialRepository.check_url(url, self.config) |
|
350 | MercurialRepository.check_url(url, self.config) | |
351 |
|
351 | |||
352 | self._remote.clone(url, self.path, do_workspace_checkout) |
|
352 | self._remote.clone(url, self.path, do_workspace_checkout) | |
353 |
|
353 | |||
354 | # Don't try to create if we've already cloned repo |
|
354 | # Don't try to create if we've already cloned repo | |
355 | create = False |
|
355 | create = False | |
356 |
|
356 | |||
357 | if create: |
|
357 | if create: | |
358 | os.makedirs(self.path, mode=0o755) |
|
358 | os.makedirs(self.path, mode=0o755) | |
359 |
|
359 | |||
360 | self._remote.localrepository(create) |
|
360 | self._remote.localrepository(create) | |
361 |
|
361 | |||
362 | @LazyProperty |
|
362 | @LazyProperty | |
363 | def in_memory_commit(self): |
|
363 | def in_memory_commit(self): | |
364 | return MercurialInMemoryCommit(self) |
|
364 | return MercurialInMemoryCommit(self) | |
365 |
|
365 | |||
366 | @LazyProperty |
|
366 | @LazyProperty | |
367 | def description(self): |
|
367 | def description(self): | |
368 | description = self._remote.get_config_value( |
|
368 | description = self._remote.get_config_value( | |
369 | 'web', 'description', untrusted=True) |
|
369 | 'web', 'description', untrusted=True) | |
370 | return safe_unicode(description or self.DEFAULT_DESCRIPTION) |
|
370 | return safe_unicode(description or self.DEFAULT_DESCRIPTION) | |
371 |
|
371 | |||
372 | @LazyProperty |
|
372 | @LazyProperty | |
373 | def contact(self): |
|
373 | def contact(self): | |
374 | contact = ( |
|
374 | contact = ( | |
375 | self._remote.get_config_value("web", "contact") or |
|
375 | self._remote.get_config_value("web", "contact") or | |
376 | self._remote.get_config_value("ui", "username")) |
|
376 | self._remote.get_config_value("ui", "username")) | |
377 | return safe_unicode(contact or self.DEFAULT_CONTACT) |
|
377 | return safe_unicode(contact or self.DEFAULT_CONTACT) | |
378 |
|
378 | |||
379 | @LazyProperty |
|
379 | @LazyProperty | |
380 | def last_change(self): |
|
380 | def last_change(self): | |
381 | """ |
|
381 | """ | |
382 | Returns last change made on this repository as |
|
382 | Returns last change made on this repository as | |
383 | `datetime.datetime` object. |
|
383 | `datetime.datetime` object. | |
384 | """ |
|
384 | """ | |
385 | try: |
|
385 | try: | |
386 | return self.get_commit().date |
|
386 | return self.get_commit().date | |
387 | except RepositoryError: |
|
387 | except RepositoryError: | |
388 | tzoffset = makedate()[1] |
|
388 | tzoffset = makedate()[1] | |
389 | return utcdate_fromtimestamp(self._get_fs_mtime(), tzoffset) |
|
389 | return utcdate_fromtimestamp(self._get_fs_mtime(), tzoffset) | |
390 |
|
390 | |||
391 | def _get_fs_mtime(self): |
|
391 | def _get_fs_mtime(self): | |
392 | # fallback to filesystem |
|
392 | # fallback to filesystem | |
393 | cl_path = os.path.join(self.path, '.hg', "00changelog.i") |
|
393 | cl_path = os.path.join(self.path, '.hg', "00changelog.i") | |
394 | st_path = os.path.join(self.path, '.hg', "store") |
|
394 | st_path = os.path.join(self.path, '.hg', "store") | |
395 | if os.path.exists(cl_path): |
|
395 | if os.path.exists(cl_path): | |
396 | return os.stat(cl_path).st_mtime |
|
396 | return os.stat(cl_path).st_mtime | |
397 | else: |
|
397 | else: | |
398 | return os.stat(st_path).st_mtime |
|
398 | return os.stat(st_path).st_mtime | |
399 |
|
399 | |||
400 | def _get_url(self, url): |
|
400 | def _get_url(self, url): | |
401 | """ |
|
401 | """ | |
402 | Returns normalized url. If schema is not given, would fall |
|
402 | Returns normalized url. If schema is not given, would fall | |
403 | to filesystem |
|
403 | to filesystem | |
404 | (``file:///``) schema. |
|
404 | (``file:///``) schema. | |
405 | """ |
|
405 | """ | |
406 | url = url.encode('utf8') |
|
406 | url = url.encode('utf8') | |
407 | if url != 'default' and '://' not in url: |
|
407 | if url != 'default' and '://' not in url: | |
408 | url = "file:" + urllib.pathname2url(url) |
|
408 | url = "file:" + urllib.pathname2url(url) | |
409 | return url |
|
409 | return url | |
410 |
|
410 | |||
411 | def get_hook_location(self): |
|
411 | def get_hook_location(self): | |
412 | """ |
|
412 | """ | |
413 | returns absolute path to location where hooks are stored |
|
413 | returns absolute path to location where hooks are stored | |
414 | """ |
|
414 | """ | |
415 | return os.path.join(self.path, '.hg', '.hgrc') |
|
415 | return os.path.join(self.path, '.hg', '.hgrc') | |
416 |
|
416 | |||
417 | def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, translate_tag=None): |
|
417 | def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, translate_tag=None): | |
418 | """ |
|
418 | """ | |
419 | Returns ``MercurialCommit`` object representing repository's |
|
419 | Returns ``MercurialCommit`` object representing repository's | |
420 | commit at the given `commit_id` or `commit_idx`. |
|
420 | commit at the given `commit_id` or `commit_idx`. | |
421 | """ |
|
421 | """ | |
422 | if self.is_empty(): |
|
422 | if self.is_empty(): | |
423 | raise EmptyRepositoryError("There are no commits yet") |
|
423 | raise EmptyRepositoryError("There are no commits yet") | |
424 |
|
424 | |||
425 | if commit_id is not None: |
|
425 | if commit_id is not None: | |
426 | self._validate_commit_id(commit_id) |
|
426 | self._validate_commit_id(commit_id) | |
427 | try: |
|
427 | try: | |
428 | idx = self._commit_ids[commit_id] |
|
428 | idx = self._commit_ids[commit_id] | |
429 | return MercurialCommit(self, commit_id, idx, pre_load=pre_load) |
|
429 | return MercurialCommit(self, commit_id, idx, pre_load=pre_load) | |
430 | except KeyError: |
|
430 | except KeyError: | |
431 | pass |
|
431 | pass | |
432 | elif commit_idx is not None: |
|
432 | elif commit_idx is not None: | |
433 | self._validate_commit_idx(commit_idx) |
|
433 | self._validate_commit_idx(commit_idx) | |
434 | try: |
|
434 | try: | |
435 | id_ = self.commit_ids[commit_idx] |
|
435 | id_ = self.commit_ids[commit_idx] | |
436 | if commit_idx < 0: |
|
436 | if commit_idx < 0: | |
437 | commit_idx += len(self.commit_ids) |
|
437 | commit_idx += len(self.commit_ids) | |
438 | return MercurialCommit( |
|
438 | return MercurialCommit( | |
439 | self, id_, commit_idx, pre_load=pre_load) |
|
439 | self, id_, commit_idx, pre_load=pre_load) | |
440 | except IndexError: |
|
440 | except IndexError: | |
441 | commit_id = commit_idx |
|
441 | commit_id = commit_idx | |
442 | else: |
|
442 | else: | |
443 | commit_id = "tip" |
|
443 | commit_id = "tip" | |
444 |
|
444 | |||
445 | if isinstance(commit_id, unicode): |
|
445 | if isinstance(commit_id, unicode): | |
446 | commit_id = safe_str(commit_id) |
|
446 | commit_id = safe_str(commit_id) | |
447 |
|
447 | |||
448 | try: |
|
448 | try: | |
449 | raw_id, idx = self._remote.lookup(commit_id, both=True) |
|
449 | raw_id, idx = self._remote.lookup(commit_id, both=True) | |
450 | except CommitDoesNotExistError: |
|
450 | except CommitDoesNotExistError: | |
451 | msg = "Commit %s does not exist for %s" % ( |
|
451 | msg = "Commit %s does not exist for %s" % ( | |
452 | commit_id, self) |
|
452 | commit_id, self) | |
453 | raise CommitDoesNotExistError(msg) |
|
453 | raise CommitDoesNotExistError(msg) | |
454 |
|
454 | |||
455 | return MercurialCommit(self, raw_id, idx, pre_load=pre_load) |
|
455 | return MercurialCommit(self, raw_id, idx, pre_load=pre_load) | |
456 |
|
456 | |||
457 | def get_commits( |
|
457 | def get_commits( | |
458 | self, start_id=None, end_id=None, start_date=None, end_date=None, |
|
458 | self, start_id=None, end_id=None, start_date=None, end_date=None, | |
459 | branch_name=None, show_hidden=False, pre_load=None, translate_tags=None): |
|
459 | branch_name=None, show_hidden=False, pre_load=None, translate_tags=None): | |
460 | """ |
|
460 | """ | |
461 | Returns generator of ``MercurialCommit`` objects from start to end |
|
461 | Returns generator of ``MercurialCommit`` objects from start to end | |
462 | (both are inclusive) |
|
462 | (both are inclusive) | |
463 |
|
463 | |||
464 | :param start_id: None, str(commit_id) |
|
464 | :param start_id: None, str(commit_id) | |
465 | :param end_id: None, str(commit_id) |
|
465 | :param end_id: None, str(commit_id) | |
466 | :param start_date: if specified, commits with commit date less than |
|
466 | :param start_date: if specified, commits with commit date less than | |
467 | ``start_date`` would be filtered out from returned set |
|
467 | ``start_date`` would be filtered out from returned set | |
468 | :param end_date: if specified, commits with commit date greater than |
|
468 | :param end_date: if specified, commits with commit date greater than | |
469 | ``end_date`` would be filtered out from returned set |
|
469 | ``end_date`` would be filtered out from returned set | |
470 | :param branch_name: if specified, commits not reachable from given |
|
470 | :param branch_name: if specified, commits not reachable from given | |
471 | branch would be filtered out from returned set |
|
471 | branch would be filtered out from returned set | |
472 | :param show_hidden: Show hidden commits such as obsolete or hidden from |
|
472 | :param show_hidden: Show hidden commits such as obsolete or hidden from | |
473 | Mercurial evolve |
|
473 | Mercurial evolve | |
474 | :raise BranchDoesNotExistError: If given ``branch_name`` does not |
|
474 | :raise BranchDoesNotExistError: If given ``branch_name`` does not | |
475 | exist. |
|
475 | exist. | |
476 | :raise CommitDoesNotExistError: If commit for given ``start`` or |
|
476 | :raise CommitDoesNotExistError: If commit for given ``start`` or | |
477 | ``end`` could not be found. |
|
477 | ``end`` could not be found. | |
478 | """ |
|
478 | """ | |
479 | # actually we should check now if it's not an empty repo |
|
479 | # actually we should check now if it's not an empty repo | |
480 | branch_ancestors = False |
|
480 | branch_ancestors = False | |
481 | if self.is_empty(): |
|
481 | if self.is_empty(): | |
482 | raise EmptyRepositoryError("There are no commits yet") |
|
482 | raise EmptyRepositoryError("There are no commits yet") | |
483 | self._validate_branch_name(branch_name) |
|
483 | self._validate_branch_name(branch_name) | |
484 |
|
484 | |||
485 | if start_id is not None: |
|
485 | if start_id is not None: | |
486 | self._validate_commit_id(start_id) |
|
486 | self._validate_commit_id(start_id) | |
487 | c_start = self.get_commit(commit_id=start_id) |
|
487 | c_start = self.get_commit(commit_id=start_id) | |
488 | start_pos = self._commit_ids[c_start.raw_id] |
|
488 | start_pos = self._commit_ids[c_start.raw_id] | |
489 | else: |
|
489 | else: | |
490 | start_pos = None |
|
490 | start_pos = None | |
491 |
|
491 | |||
492 | if end_id is not None: |
|
492 | if end_id is not None: | |
493 | self._validate_commit_id(end_id) |
|
493 | self._validate_commit_id(end_id) | |
494 | c_end = self.get_commit(commit_id=end_id) |
|
494 | c_end = self.get_commit(commit_id=end_id) | |
495 | end_pos = max(0, self._commit_ids[c_end.raw_id]) |
|
495 | end_pos = max(0, self._commit_ids[c_end.raw_id]) | |
496 | else: |
|
496 | else: | |
497 | end_pos = None |
|
497 | end_pos = None | |
498 |
|
498 | |||
499 | if None not in [start_id, end_id] and start_pos > end_pos: |
|
499 | if None not in [start_id, end_id] and start_pos > end_pos: | |
500 | raise RepositoryError( |
|
500 | raise RepositoryError( | |
501 | "Start commit '%s' cannot be after end commit '%s'" % |
|
501 | "Start commit '%s' cannot be after end commit '%s'" % | |
502 | (start_id, end_id)) |
|
502 | (start_id, end_id)) | |
503 |
|
503 | |||
504 | if end_pos is not None: |
|
504 | if end_pos is not None: | |
505 | end_pos += 1 |
|
505 | end_pos += 1 | |
506 |
|
506 | |||
507 | commit_filter = [] |
|
507 | commit_filter = [] | |
508 |
|
508 | |||
509 | if branch_name and not branch_ancestors: |
|
509 | if branch_name and not branch_ancestors: | |
510 | commit_filter.append('branch("%s")' % (branch_name,)) |
|
510 | commit_filter.append('branch("%s")' % (branch_name,)) | |
511 | elif branch_name and branch_ancestors: |
|
511 | elif branch_name and branch_ancestors: | |
512 | commit_filter.append('ancestors(branch("%s"))' % (branch_name,)) |
|
512 | commit_filter.append('ancestors(branch("%s"))' % (branch_name,)) | |
513 |
|
513 | |||
514 | if start_date and not end_date: |
|
514 | if start_date and not end_date: | |
515 | commit_filter.append('date(">%s")' % (start_date,)) |
|
515 | commit_filter.append('date(">%s")' % (start_date,)) | |
516 | if end_date and not start_date: |
|
516 | if end_date and not start_date: | |
517 | commit_filter.append('date("<%s")' % (end_date,)) |
|
517 | commit_filter.append('date("<%s")' % (end_date,)) | |
518 | if start_date and end_date: |
|
518 | if start_date and end_date: | |
519 | commit_filter.append( |
|
519 | commit_filter.append( | |
520 | 'date(">%s") and date("<%s")' % (start_date, end_date)) |
|
520 | 'date(">%s") and date("<%s")' % (start_date, end_date)) | |
521 |
|
521 | |||
522 | if not show_hidden: |
|
522 | if not show_hidden: | |
523 | commit_filter.append('not obsolete()') |
|
523 | commit_filter.append('not obsolete()') | |
524 | commit_filter.append('not hidden()') |
|
524 | commit_filter.append('not hidden()') | |
525 |
|
525 | |||
526 | # TODO: johbo: Figure out a simpler way for this solution |
|
526 | # TODO: johbo: Figure out a simpler way for this solution | |
527 | collection_generator = CollectionGenerator |
|
527 | collection_generator = CollectionGenerator | |
528 | if commit_filter: |
|
528 | if commit_filter: | |
529 | commit_filter = ' and '.join(map(safe_str, commit_filter)) |
|
529 | commit_filter = ' and '.join(map(safe_str, commit_filter)) | |
530 | revisions = self._remote.rev_range([commit_filter]) |
|
530 | revisions = self._remote.rev_range([commit_filter]) | |
531 | collection_generator = MercurialIndexBasedCollectionGenerator |
|
531 | collection_generator = MercurialIndexBasedCollectionGenerator | |
532 | else: |
|
532 | else: | |
533 | revisions = self.commit_ids |
|
533 | revisions = self.commit_ids | |
534 |
|
534 | |||
535 | if start_pos or end_pos: |
|
535 | if start_pos or end_pos: | |
536 | revisions = revisions[start_pos:end_pos] |
|
536 | revisions = revisions[start_pos:end_pos] | |
537 |
|
537 | |||
538 | return collection_generator(self, revisions, pre_load=pre_load) |
|
538 | return collection_generator(self, revisions, pre_load=pre_load) | |
539 |
|
539 | |||
540 | def pull(self, url, commit_ids=None): |
|
540 | def pull(self, url, commit_ids=None): | |
541 | """ |
|
541 | """ | |
542 | Pull changes from external location. |
|
542 | Pull changes from external location. | |
543 |
|
543 | |||
544 | :param commit_ids: Optional. Can be set to a list of commit ids |
|
544 | :param commit_ids: Optional. Can be set to a list of commit ids | |
545 | which shall be pulled from the other repository. |
|
545 | which shall be pulled from the other repository. | |
546 | """ |
|
546 | """ | |
547 | url = self._get_url(url) |
|
547 | url = self._get_url(url) | |
548 | self._remote.pull(url, commit_ids=commit_ids) |
|
548 | self._remote.pull(url, commit_ids=commit_ids) | |
549 | self._remote.invalidate_vcs_cache() |
|
549 | self._remote.invalidate_vcs_cache() | |
550 |
|
550 | |||
551 | def fetch(self, url, commit_ids=None): |
|
551 | def fetch(self, url, commit_ids=None): | |
552 | """ |
|
552 | """ | |
553 | Backward compatibility with GIT fetch==pull |
|
553 | Backward compatibility with GIT fetch==pull | |
554 | """ |
|
554 | """ | |
555 | return self.pull(url, commit_ids=commit_ids) |
|
555 | return self.pull(url, commit_ids=commit_ids) | |
556 |
|
556 | |||
557 | def push(self, url): |
|
557 | def push(self, url): | |
558 | url = self._get_url(url) |
|
558 | url = self._get_url(url) | |
559 | self._remote.sync_push(url) |
|
559 | self._remote.sync_push(url) | |
560 |
|
560 | |||
561 | def _local_clone(self, clone_path): |
|
561 | def _local_clone(self, clone_path): | |
562 | """ |
|
562 | """ | |
563 | Create a local clone of the current repo. |
|
563 | Create a local clone of the current repo. | |
564 | """ |
|
564 | """ | |
565 | self._remote.clone(self.path, clone_path, update_after_clone=True, |
|
565 | self._remote.clone(self.path, clone_path, update_after_clone=True, | |
566 | hooks=False) |
|
566 | hooks=False) | |
567 |
|
567 | |||
568 | def _update(self, revision, clean=False): |
|
568 | def _update(self, revision, clean=False): | |
569 | """ |
|
569 | """ | |
570 | Update the working copy to the specified revision. |
|
570 | Update the working copy to the specified revision. | |
571 | """ |
|
571 | """ | |
572 | log.debug('Doing checkout to commit: `%s` for %s', revision, self) |
|
572 | log.debug('Doing checkout to commit: `%s` for %s', revision, self) | |
573 | self._remote.update(revision, clean=clean) |
|
573 | self._remote.update(revision, clean=clean) | |
574 |
|
574 | |||
575 | def _identify(self): |
|
575 | def _identify(self): | |
576 | """ |
|
576 | """ | |
577 | Return the current state of the working directory. |
|
577 | Return the current state of the working directory. | |
578 | """ |
|
578 | """ | |
579 | return self._remote.identify().strip().rstrip('+') |
|
579 | return self._remote.identify().strip().rstrip('+') | |
580 |
|
580 | |||
581 | def _heads(self, branch=None): |
|
581 | def _heads(self, branch=None): | |
582 | """ |
|
582 | """ | |
583 | Return the commit ids of the repository heads. |
|
583 | Return the commit ids of the repository heads. | |
584 | """ |
|
584 | """ | |
585 | return self._remote.heads(branch=branch).strip().split(' ') |
|
585 | return self._remote.heads(branch=branch).strip().split(' ') | |
586 |
|
586 | |||
587 | def _ancestor(self, revision1, revision2): |
|
587 | def _ancestor(self, revision1, revision2): | |
588 | """ |
|
588 | """ | |
589 | Return the common ancestor of the two revisions. |
|
589 | Return the common ancestor of the two revisions. | |
590 | """ |
|
590 | """ | |
591 | return self._remote.ancestor(revision1, revision2) |
|
591 | return self._remote.ancestor(revision1, revision2) | |
592 |
|
592 | |||
593 | def _local_push( |
|
593 | def _local_push( | |
594 | self, revision, repository_path, push_branches=False, |
|
594 | self, revision, repository_path, push_branches=False, | |
595 | enable_hooks=False): |
|
595 | enable_hooks=False): | |
596 | """ |
|
596 | """ | |
597 | Push the given revision to the specified repository. |
|
597 | Push the given revision to the specified repository. | |
598 |
|
598 | |||
599 | :param push_branches: allow to create branches in the target repo. |
|
599 | :param push_branches: allow to create branches in the target repo. | |
600 | """ |
|
600 | """ | |
601 | self._remote.push( |
|
601 | self._remote.push( | |
602 | [revision], repository_path, hooks=enable_hooks, |
|
602 | [revision], repository_path, hooks=enable_hooks, | |
603 | push_branches=push_branches) |
|
603 | push_branches=push_branches) | |
604 |
|
604 | |||
605 | def _local_merge(self, target_ref, merge_message, user_name, user_email, |
|
605 | def _local_merge(self, target_ref, merge_message, user_name, user_email, | |
606 | source_ref, use_rebase=False, dry_run=False): |
|
606 | source_ref, use_rebase=False, dry_run=False): | |
607 | """ |
|
607 | """ | |
608 | Merge the given source_revision into the checked out revision. |
|
608 | Merge the given source_revision into the checked out revision. | |
609 |
|
609 | |||
610 | Returns the commit id of the merge and a boolean indicating if the |
|
610 | Returns the commit id of the merge and a boolean indicating if the | |
611 | commit needs to be pushed. |
|
611 | commit needs to be pushed. | |
612 | """ |
|
612 | """ | |
613 | self._update(target_ref.commit_id, clean=True) |
|
613 | self._update(target_ref.commit_id, clean=True) | |
614 |
|
614 | |||
615 | ancestor = self._ancestor(target_ref.commit_id, source_ref.commit_id) |
|
615 | ancestor = self._ancestor(target_ref.commit_id, source_ref.commit_id) | |
616 | is_the_same_branch = self._is_the_same_branch(target_ref, source_ref) |
|
616 | is_the_same_branch = self._is_the_same_branch(target_ref, source_ref) | |
617 |
|
617 | |||
618 | if ancestor == source_ref.commit_id: |
|
618 | if ancestor == source_ref.commit_id: | |
619 | # Nothing to do, the changes were already integrated |
|
619 | # Nothing to do, the changes were already integrated | |
620 | return target_ref.commit_id, False |
|
620 | return target_ref.commit_id, False | |
621 |
|
621 | |||
622 | elif ancestor == target_ref.commit_id and is_the_same_branch: |
|
622 | elif ancestor == target_ref.commit_id and is_the_same_branch: | |
623 | # In this case we should force a commit message |
|
623 | # In this case we should force a commit message | |
624 | return source_ref.commit_id, True |
|
624 | return source_ref.commit_id, True | |
625 |
|
625 | |||
626 | if use_rebase: |
|
626 | if use_rebase: | |
627 | try: |
|
627 | try: | |
628 | bookmark_name = 'rcbook%s%s' % (source_ref.commit_id, |
|
628 | bookmark_name = 'rcbook%s%s' % (source_ref.commit_id, | |
629 | target_ref.commit_id) |
|
629 | target_ref.commit_id) | |
630 | self.bookmark(bookmark_name, revision=source_ref.commit_id) |
|
630 | self.bookmark(bookmark_name, revision=source_ref.commit_id) | |
631 | self._remote.rebase( |
|
631 | self._remote.rebase( | |
632 | source=source_ref.commit_id, dest=target_ref.commit_id) |
|
632 | source=source_ref.commit_id, dest=target_ref.commit_id) | |
633 | self._remote.invalidate_vcs_cache() |
|
633 | self._remote.invalidate_vcs_cache() | |
634 | self._update(bookmark_name, clean=True) |
|
634 | self._update(bookmark_name, clean=True) | |
635 | return self._identify(), True |
|
635 | return self._identify(), True | |
636 | except RepositoryError: |
|
636 | except RepositoryError: | |
637 | # The rebase-abort may raise another exception which 'hides' |
|
637 | # The rebase-abort may raise another exception which 'hides' | |
638 | # the original one, therefore we log it here. |
|
638 | # the original one, therefore we log it here. | |
639 | log.exception('Error while rebasing shadow repo during merge.') |
|
639 | log.exception('Error while rebasing shadow repo during merge.') | |
640 |
|
640 | |||
641 | # Cleanup any rebase leftovers |
|
641 | # Cleanup any rebase leftovers | |
642 | self._remote.invalidate_vcs_cache() |
|
642 | self._remote.invalidate_vcs_cache() | |
643 | self._remote.rebase(abort=True) |
|
643 | self._remote.rebase(abort=True) | |
644 | self._remote.invalidate_vcs_cache() |
|
644 | self._remote.invalidate_vcs_cache() | |
645 | self._remote.update(clean=True) |
|
645 | self._remote.update(clean=True) | |
646 | raise |
|
646 | raise | |
647 | else: |
|
647 | else: | |
648 | try: |
|
648 | try: | |
649 | self._remote.merge(source_ref.commit_id) |
|
649 | self._remote.merge(source_ref.commit_id) | |
650 | self._remote.invalidate_vcs_cache() |
|
650 | self._remote.invalidate_vcs_cache() | |
651 | self._remote.commit( |
|
651 | self._remote.commit( | |
652 | message=safe_str(merge_message), |
|
652 | message=safe_str(merge_message), | |
653 | username=safe_str('%s <%s>' % (user_name, user_email))) |
|
653 | username=safe_str('%s <%s>' % (user_name, user_email))) | |
654 | self._remote.invalidate_vcs_cache() |
|
654 | self._remote.invalidate_vcs_cache() | |
655 | return self._identify(), True |
|
655 | return self._identify(), True | |
656 | except RepositoryError: |
|
656 | except RepositoryError: | |
657 | # Cleanup any merge leftovers |
|
657 | # Cleanup any merge leftovers | |
658 | self._remote.update(clean=True) |
|
658 | self._remote.update(clean=True) | |
659 | raise |
|
659 | raise | |
660 |
|
660 | |||
661 | def _local_close(self, target_ref, user_name, user_email, |
|
661 | def _local_close(self, target_ref, user_name, user_email, | |
662 | source_ref, close_message=''): |
|
662 | source_ref, close_message=''): | |
663 | """ |
|
663 | """ | |
664 | Close the branch of the given source_revision |
|
664 | Close the branch of the given source_revision | |
665 |
|
665 | |||
666 | Returns the commit id of the close and a boolean indicating if the |
|
666 | Returns the commit id of the close and a boolean indicating if the | |
667 | commit needs to be pushed. |
|
667 | commit needs to be pushed. | |
668 | """ |
|
668 | """ | |
669 | self._update(source_ref.commit_id) |
|
669 | self._update(source_ref.commit_id) | |
670 | message = close_message or "Closing branch: `{}`".format(source_ref.name) |
|
670 | message = close_message or "Closing branch: `{}`".format(source_ref.name) | |
671 | try: |
|
671 | try: | |
672 | self._remote.commit( |
|
672 | self._remote.commit( | |
673 | message=safe_str(message), |
|
673 | message=safe_str(message), | |
674 | username=safe_str('%s <%s>' % (user_name, user_email)), |
|
674 | username=safe_str('%s <%s>' % (user_name, user_email)), | |
675 | close_branch=True) |
|
675 | close_branch=True) | |
676 | self._remote.invalidate_vcs_cache() |
|
676 | self._remote.invalidate_vcs_cache() | |
677 | return self._identify(), True |
|
677 | return self._identify(), True | |
678 | except RepositoryError: |
|
678 | except RepositoryError: | |
679 | # Cleanup any commit leftovers |
|
679 | # Cleanup any commit leftovers | |
680 | self._remote.update(clean=True) |
|
680 | self._remote.update(clean=True) | |
681 | raise |
|
681 | raise | |
682 |
|
682 | |||
683 | def _is_the_same_branch(self, target_ref, source_ref): |
|
683 | def _is_the_same_branch(self, target_ref, source_ref): | |
684 | return ( |
|
684 | return ( | |
685 | self._get_branch_name(target_ref) == |
|
685 | self._get_branch_name(target_ref) == | |
686 | self._get_branch_name(source_ref)) |
|
686 | self._get_branch_name(source_ref)) | |
687 |
|
687 | |||
688 | def _get_branch_name(self, ref): |
|
688 | def _get_branch_name(self, ref): | |
689 | if ref.type == 'branch': |
|
689 | if ref.type == 'branch': | |
690 | return ref.name |
|
690 | return ref.name | |
691 | return self._remote.ctx_branch(ref.commit_id) |
|
691 | return self._remote.ctx_branch(ref.commit_id) | |
692 |
|
692 | |||
693 | def _maybe_prepare_merge_workspace( |
|
693 | def _maybe_prepare_merge_workspace( | |
694 | self, repo_id, workspace_id, unused_target_ref, unused_source_ref): |
|
694 | self, repo_id, workspace_id, unused_target_ref, unused_source_ref): | |
695 | shadow_repository_path = self._get_shadow_repository_path( |
|
695 | shadow_repository_path = self._get_shadow_repository_path( | |
696 | repo_id, workspace_id) |
|
696 | repo_id, workspace_id) | |
697 | if not os.path.exists(shadow_repository_path): |
|
697 | if not os.path.exists(shadow_repository_path): | |
698 | self._local_clone(shadow_repository_path) |
|
698 | self._local_clone(shadow_repository_path) | |
699 | log.debug( |
|
699 | log.debug( | |
700 | 'Prepared shadow repository in %s', shadow_repository_path) |
|
700 | 'Prepared shadow repository in %s', shadow_repository_path) | |
701 |
|
701 | |||
702 | return shadow_repository_path |
|
702 | return shadow_repository_path | |
703 |
|
703 | |||
704 | def _merge_repo(self, repo_id, workspace_id, target_ref, |
|
704 | def _merge_repo(self, repo_id, workspace_id, target_ref, | |
705 | source_repo, source_ref, merge_message, |
|
705 | source_repo, source_ref, merge_message, | |
706 | merger_name, merger_email, dry_run=False, |
|
706 | merger_name, merger_email, dry_run=False, | |
707 | use_rebase=False, close_branch=False): |
|
707 | use_rebase=False, close_branch=False): | |
708 |
|
708 | |||
709 | log.debug('Executing merge_repo with %s strategy, dry_run mode:%s', |
|
709 | log.debug('Executing merge_repo with %s strategy, dry_run mode:%s', | |
710 | 'rebase' if use_rebase else 'merge', dry_run) |
|
710 | 'rebase' if use_rebase else 'merge', dry_run) | |
711 | if target_ref.commit_id not in self._heads(): |
|
711 | if target_ref.commit_id not in self._heads(): | |
712 | return MergeResponse( |
|
712 | return MergeResponse( | |
713 | False, False, None, MergeFailureReason.TARGET_IS_NOT_HEAD, |
|
713 | False, False, None, MergeFailureReason.TARGET_IS_NOT_HEAD, | |
714 | metadata={'target_ref': target_ref}) |
|
714 | metadata={'target_ref': target_ref}) | |
715 |
|
715 | |||
716 | try: |
|
716 | try: | |
717 | if target_ref.type == 'branch' and len(self._heads(target_ref.name)) != 1: |
|
717 | if target_ref.type == 'branch' and len(self._heads(target_ref.name)) != 1: | |
718 | heads = '\n,'.join(self._heads(target_ref.name)) |
|
718 | heads = '\n,'.join(self._heads(target_ref.name)) | |
719 | metadata = { |
|
719 | metadata = { | |
720 | 'target_ref': target_ref, |
|
720 | 'target_ref': target_ref, | |
721 | 'source_ref': source_ref, |
|
721 | 'source_ref': source_ref, | |
722 | 'heads': heads |
|
722 | 'heads': heads | |
723 | } |
|
723 | } | |
724 | return MergeResponse( |
|
724 | return MergeResponse( | |
725 | False, False, None, |
|
725 | False, False, None, | |
726 | MergeFailureReason.HG_TARGET_HAS_MULTIPLE_HEADS, |
|
726 | MergeFailureReason.HG_TARGET_HAS_MULTIPLE_HEADS, | |
727 | metadata=metadata) |
|
727 | metadata=metadata) | |
728 | except CommitDoesNotExistError: |
|
728 | except CommitDoesNotExistError: | |
729 | log.exception('Failure when looking up branch heads on hg target') |
|
729 | log.exception('Failure when looking up branch heads on hg target') | |
730 | return MergeResponse( |
|
730 | return MergeResponse( | |
731 | False, False, None, MergeFailureReason.MISSING_TARGET_REF, |
|
731 | False, False, None, MergeFailureReason.MISSING_TARGET_REF, | |
732 | metadata={'target_ref': target_ref}) |
|
732 | metadata={'target_ref': target_ref}) | |
733 |
|
733 | |||
734 | shadow_repository_path = self._maybe_prepare_merge_workspace( |
|
734 | shadow_repository_path = self._maybe_prepare_merge_workspace( | |
735 | repo_id, workspace_id, target_ref, source_ref) |
|
735 | repo_id, workspace_id, target_ref, source_ref) | |
736 | shadow_repo = self._get_shadow_instance(shadow_repository_path) |
|
736 | shadow_repo = self._get_shadow_instance(shadow_repository_path) | |
737 |
|
737 | |||
738 | log.debug('Pulling in target reference %s', target_ref) |
|
738 | log.debug('Pulling in target reference %s', target_ref) | |
739 | self._validate_pull_reference(target_ref) |
|
739 | self._validate_pull_reference(target_ref) | |
740 | shadow_repo._local_pull(self.path, target_ref) |
|
740 | shadow_repo._local_pull(self.path, target_ref) | |
741 |
|
741 | |||
742 | try: |
|
742 | try: | |
743 | log.debug('Pulling in source reference %s', source_ref) |
|
743 | log.debug('Pulling in source reference %s', source_ref) | |
744 | source_repo._validate_pull_reference(source_ref) |
|
744 | source_repo._validate_pull_reference(source_ref) | |
745 | shadow_repo._local_pull(source_repo.path, source_ref) |
|
745 | shadow_repo._local_pull(source_repo.path, source_ref) | |
746 | except CommitDoesNotExistError: |
|
746 | except CommitDoesNotExistError: | |
747 | log.exception('Failure when doing local pull on hg shadow repo') |
|
747 | log.exception('Failure when doing local pull on hg shadow repo') | |
748 | return MergeResponse( |
|
748 | return MergeResponse( | |
749 | False, False, None, MergeFailureReason.MISSING_SOURCE_REF, |
|
749 | False, False, None, MergeFailureReason.MISSING_SOURCE_REF, | |
750 | metadata={'source_ref': source_ref}) |
|
750 | metadata={'source_ref': source_ref}) | |
751 |
|
751 | |||
752 | merge_ref = None |
|
752 | merge_ref = None | |
753 | merge_commit_id = None |
|
753 | merge_commit_id = None | |
754 | close_commit_id = None |
|
754 | close_commit_id = None | |
755 | merge_failure_reason = MergeFailureReason.NONE |
|
755 | merge_failure_reason = MergeFailureReason.NONE | |
756 | metadata = {} |
|
756 | metadata = {} | |
757 |
|
757 | |||
758 | # enforce that close branch should be used only in case we source from |
|
758 | # enforce that close branch should be used only in case we source from | |
759 | # an actual Branch |
|
759 | # an actual Branch | |
760 | close_branch = close_branch and source_ref.type == 'branch' |
|
760 | close_branch = close_branch and source_ref.type == 'branch' | |
761 |
|
761 | |||
762 | # don't allow to close branch if source and target are the same |
|
762 | # don't allow to close branch if source and target are the same | |
763 | close_branch = close_branch and source_ref.name != target_ref.name |
|
763 | close_branch = close_branch and source_ref.name != target_ref.name | |
764 |
|
764 | |||
765 | needs_push_on_close = False |
|
765 | needs_push_on_close = False | |
766 | if close_branch and not use_rebase and not dry_run: |
|
766 | if close_branch and not use_rebase and not dry_run: | |
767 | try: |
|
767 | try: | |
768 | close_commit_id, needs_push_on_close = shadow_repo._local_close( |
|
768 | close_commit_id, needs_push_on_close = shadow_repo._local_close( | |
769 | target_ref, merger_name, merger_email, source_ref) |
|
769 | target_ref, merger_name, merger_email, source_ref) | |
770 | merge_possible = True |
|
770 | merge_possible = True | |
771 | except RepositoryError: |
|
771 | except RepositoryError: | |
772 | log.exception('Failure when doing close branch on ' |
|
772 | log.exception('Failure when doing close branch on ' | |
773 | 'shadow repo: %s', shadow_repo) |
|
773 | 'shadow repo: %s', shadow_repo) | |
774 | merge_possible = False |
|
774 | merge_possible = False | |
775 | merge_failure_reason = MergeFailureReason.MERGE_FAILED |
|
775 | merge_failure_reason = MergeFailureReason.MERGE_FAILED | |
776 | else: |
|
776 | else: | |
777 | merge_possible = True |
|
777 | merge_possible = True | |
778 |
|
778 | |||
779 | needs_push = False |
|
779 | needs_push = False | |
780 | if merge_possible: |
|
780 | if merge_possible: | |
781 | try: |
|
781 | try: | |
782 | merge_commit_id, needs_push = shadow_repo._local_merge( |
|
782 | merge_commit_id, needs_push = shadow_repo._local_merge( | |
783 | target_ref, merge_message, merger_name, merger_email, |
|
783 | target_ref, merge_message, merger_name, merger_email, | |
784 | source_ref, use_rebase=use_rebase, dry_run=dry_run) |
|
784 | source_ref, use_rebase=use_rebase, dry_run=dry_run) | |
785 | merge_possible = True |
|
785 | merge_possible = True | |
786 |
|
786 | |||
787 | # read the state of the close action, if it |
|
787 | # read the state of the close action, if it | |
788 | # maybe required a push |
|
788 | # maybe required a push | |
789 | needs_push = needs_push or needs_push_on_close |
|
789 | needs_push = needs_push or needs_push_on_close | |
790 |
|
790 | |||
791 | # Set a bookmark pointing to the merge commit. This bookmark |
|
791 | # Set a bookmark pointing to the merge commit. This bookmark | |
792 | # may be used to easily identify the last successful merge |
|
792 | # may be used to easily identify the last successful merge | |
793 | # commit in the shadow repository. |
|
793 | # commit in the shadow repository. | |
794 | shadow_repo.bookmark('pr-merge', revision=merge_commit_id) |
|
794 | shadow_repo.bookmark('pr-merge', revision=merge_commit_id) | |
795 | merge_ref = Reference('book', 'pr-merge', merge_commit_id) |
|
795 | merge_ref = Reference('book', 'pr-merge', merge_commit_id) | |
796 | except SubrepoMergeError: |
|
796 | except SubrepoMergeError: | |
797 | log.exception( |
|
797 | log.exception( | |
798 | 'Subrepo merge error during local merge on hg shadow repo.') |
|
798 | 'Subrepo merge error during local merge on hg shadow repo.') | |
799 | merge_possible = False |
|
799 | merge_possible = False | |
800 | merge_failure_reason = MergeFailureReason.SUBREPO_MERGE_FAILED |
|
800 | merge_failure_reason = MergeFailureReason.SUBREPO_MERGE_FAILED | |
801 | needs_push = False |
|
801 | needs_push = False | |
802 | except RepositoryError: |
|
802 | except RepositoryError: | |
803 | log.exception('Failure when doing local merge on hg shadow repo') |
|
803 | log.exception('Failure when doing local merge on hg shadow repo') | |
804 | merge_possible = False |
|
804 | merge_possible = False | |
805 | merge_failure_reason = MergeFailureReason.MERGE_FAILED |
|
805 | merge_failure_reason = MergeFailureReason.MERGE_FAILED | |
806 | needs_push = False |
|
806 | needs_push = False | |
807 |
|
807 | |||
808 | if merge_possible and not dry_run: |
|
808 | if merge_possible and not dry_run: | |
809 | if needs_push: |
|
809 | if needs_push: | |
810 | # In case the target is a bookmark, update it, so after pushing |
|
810 | # In case the target is a bookmark, update it, so after pushing | |
811 | # the bookmarks is also updated in the target. |
|
811 | # the bookmarks is also updated in the target. | |
812 | if target_ref.type == 'book': |
|
812 | if target_ref.type == 'book': | |
813 | shadow_repo.bookmark( |
|
813 | shadow_repo.bookmark( | |
814 | target_ref.name, revision=merge_commit_id) |
|
814 | target_ref.name, revision=merge_commit_id) | |
815 | try: |
|
815 | try: | |
816 | shadow_repo_with_hooks = self._get_shadow_instance( |
|
816 | shadow_repo_with_hooks = self._get_shadow_instance( | |
817 | shadow_repository_path, |
|
817 | shadow_repository_path, | |
818 | enable_hooks=True) |
|
818 | enable_hooks=True) | |
819 | # This is the actual merge action, we push from shadow |
|
819 | # This is the actual merge action, we push from shadow | |
820 | # into origin. |
|
820 | # into origin. | |
821 | # Note: the push_branches option will push any new branch |
|
821 | # Note: the push_branches option will push any new branch | |
822 | # defined in the source repository to the target. This may |
|
822 | # defined in the source repository to the target. This may | |
823 | # be dangerous as branches are permanent in Mercurial. |
|
823 | # be dangerous as branches are permanent in Mercurial. | |
824 | # This feature was requested in issue #441. |
|
824 | # This feature was requested in issue #441. | |
825 | shadow_repo_with_hooks._local_push( |
|
825 | shadow_repo_with_hooks._local_push( | |
826 | merge_commit_id, self.path, push_branches=True, |
|
826 | merge_commit_id, self.path, push_branches=True, | |
827 | enable_hooks=True) |
|
827 | enable_hooks=True) | |
828 |
|
828 | |||
829 | # maybe we also need to push the close_commit_id |
|
829 | # maybe we also need to push the close_commit_id | |
830 | if close_commit_id: |
|
830 | if close_commit_id: | |
831 | shadow_repo_with_hooks._local_push( |
|
831 | shadow_repo_with_hooks._local_push( | |
832 | close_commit_id, self.path, push_branches=True, |
|
832 | close_commit_id, self.path, push_branches=True, | |
833 | enable_hooks=True) |
|
833 | enable_hooks=True) | |
834 | merge_succeeded = True |
|
834 | merge_succeeded = True | |
835 | except RepositoryError: |
|
835 | except RepositoryError: | |
836 | log.exception( |
|
836 | log.exception( | |
837 | 'Failure when doing local push from the shadow ' |
|
837 | 'Failure when doing local push from the shadow ' | |
838 | 'repository to the target repository at %s.', self.path) |
|
838 | 'repository to the target repository at %s.', self.path) | |
839 | merge_succeeded = False |
|
839 | merge_succeeded = False | |
840 | merge_failure_reason = MergeFailureReason.PUSH_FAILED |
|
840 | merge_failure_reason = MergeFailureReason.PUSH_FAILED | |
841 | metadata['target'] = 'hg shadow repo' |
|
841 | metadata['target'] = 'hg shadow repo' | |
842 | metadata['merge_commit'] = merge_commit_id |
|
842 | metadata['merge_commit'] = merge_commit_id | |
843 | else: |
|
843 | else: | |
844 | merge_succeeded = True |
|
844 | merge_succeeded = True | |
845 | else: |
|
845 | else: | |
846 | merge_succeeded = False |
|
846 | merge_succeeded = False | |
847 |
|
847 | |||
848 | return MergeResponse( |
|
848 | return MergeResponse( | |
849 | merge_possible, merge_succeeded, merge_ref, merge_failure_reason, |
|
849 | merge_possible, merge_succeeded, merge_ref, merge_failure_reason, | |
850 | metadata=metadata) |
|
850 | metadata=metadata) | |
851 |
|
851 | |||
852 | def _get_shadow_instance(self, shadow_repository_path, enable_hooks=False): |
|
852 | def _get_shadow_instance(self, shadow_repository_path, enable_hooks=False): | |
853 | config = self.config.copy() |
|
853 | config = self.config.copy() | |
854 | if not enable_hooks: |
|
854 | if not enable_hooks: | |
855 | config.clear_section('hooks') |
|
855 | config.clear_section('hooks') | |
856 | return MercurialRepository(shadow_repository_path, config) |
|
856 | return MercurialRepository(shadow_repository_path, config) | |
857 |
|
857 | |||
858 | def _validate_pull_reference(self, reference): |
|
858 | def _validate_pull_reference(self, reference): | |
859 | if not (reference.name in self.bookmarks or |
|
859 | if not (reference.name in self.bookmarks or | |
860 | reference.name in self.branches or |
|
860 | reference.name in self.branches or | |
861 | self.get_commit(reference.commit_id)): |
|
861 | self.get_commit(reference.commit_id)): | |
862 | raise CommitDoesNotExistError( |
|
862 | raise CommitDoesNotExistError( | |
863 | 'Unknown branch, bookmark or commit id') |
|
863 | 'Unknown branch, bookmark or commit id') | |
864 |
|
864 | |||
865 | def _local_pull(self, repository_path, reference): |
|
865 | def _local_pull(self, repository_path, reference): | |
866 | """ |
|
866 | """ | |
867 | Fetch a branch, bookmark or commit from a local repository. |
|
867 | Fetch a branch, bookmark or commit from a local repository. | |
868 | """ |
|
868 | """ | |
869 | repository_path = os.path.abspath(repository_path) |
|
869 | repository_path = os.path.abspath(repository_path) | |
870 | if repository_path == self.path: |
|
870 | if repository_path == self.path: | |
871 | raise ValueError('Cannot pull from the same repository') |
|
871 | raise ValueError('Cannot pull from the same repository') | |
872 |
|
872 | |||
873 | reference_type_to_option_name = { |
|
873 | reference_type_to_option_name = { | |
874 | 'book': 'bookmark', |
|
874 | 'book': 'bookmark', | |
875 | 'branch': 'branch', |
|
875 | 'branch': 'branch', | |
876 | } |
|
876 | } | |
877 | option_name = reference_type_to_option_name.get( |
|
877 | option_name = reference_type_to_option_name.get( | |
878 | reference.type, 'revision') |
|
878 | reference.type, 'revision') | |
879 |
|
879 | |||
880 | if option_name == 'revision': |
|
880 | if option_name == 'revision': | |
881 | ref = reference.commit_id |
|
881 | ref = reference.commit_id | |
882 | else: |
|
882 | else: | |
883 | ref = reference.name |
|
883 | ref = reference.name | |
884 |
|
884 | |||
885 | options = {option_name: [ref]} |
|
885 | options = {option_name: [ref]} | |
886 | self._remote.pull_cmd(repository_path, hooks=False, **options) |
|
886 | self._remote.pull_cmd(repository_path, hooks=False, **options) | |
887 | self._remote.invalidate_vcs_cache() |
|
887 | self._remote.invalidate_vcs_cache() | |
888 |
|
888 | |||
889 | def bookmark(self, bookmark, revision=None): |
|
889 | def bookmark(self, bookmark, revision=None): | |
890 | if isinstance(bookmark, unicode): |
|
890 | if isinstance(bookmark, unicode): | |
891 | bookmark = safe_str(bookmark) |
|
891 | bookmark = safe_str(bookmark) | |
892 | self._remote.bookmark(bookmark, revision=revision) |
|
892 | self._remote.bookmark(bookmark, revision=revision) | |
893 | self._remote.invalidate_vcs_cache() |
|
893 | self._remote.invalidate_vcs_cache() | |
894 |
|
894 | |||
895 | def get_path_permissions(self, username): |
|
895 | def get_path_permissions(self, username): | |
896 | hgacl_file = os.path.join(self.path, '.hg/hgacl') |
|
896 | hgacl_file = os.path.join(self.path, '.hg/hgacl') | |
897 |
|
897 | |||
898 | def read_patterns(suffix): |
|
898 | def read_patterns(suffix): | |
899 | svalue = None |
|
899 | svalue = None | |
900 | try: |
|
900 | for section, option in [ | |
901 |
|
|
901 | ('narrowacl', username + suffix), | |
902 | except configparser.NoOptionError: |
|
902 | ('narrowacl', 'default' + suffix), | |
|
903 | ('narrowhgacl', username + suffix), | |||
|
904 | ('narrowhgacl', 'default' + suffix) | |||
|
905 | ]: | |||
903 | try: |
|
906 | try: | |
904 |
svalue = hgacl.get( |
|
907 | svalue = hgacl.get(section, option) | |
|
908 | break # stop at the first value we find | |||
905 | except configparser.NoOptionError: |
|
909 | except configparser.NoOptionError: | |
906 | pass |
|
910 | pass | |
907 | if not svalue: |
|
911 | if not svalue: | |
908 | return None |
|
912 | return None | |
909 | result = ['/'] |
|
913 | result = ['/'] | |
910 | for pattern in svalue.split(): |
|
914 | for pattern in svalue.split(): | |
911 | result.append(pattern) |
|
915 | result.append(pattern) | |
912 | if '*' not in pattern and '?' not in pattern: |
|
916 | if '*' not in pattern and '?' not in pattern: | |
913 | result.append(pattern + '/*') |
|
917 | result.append(pattern + '/*') | |
914 | return result |
|
918 | return result | |
915 |
|
919 | |||
916 | if os.path.exists(hgacl_file): |
|
920 | if os.path.exists(hgacl_file): | |
917 | try: |
|
921 | try: | |
918 | hgacl = configparser.RawConfigParser() |
|
922 | hgacl = configparser.RawConfigParser() | |
919 | hgacl.read(hgacl_file) |
|
923 | hgacl.read(hgacl_file) | |
920 |
|
924 | |||
921 | includes = read_patterns('.includes') |
|
925 | includes = read_patterns('.includes') | |
922 | excludes = read_patterns('.excludes') |
|
926 | excludes = read_patterns('.excludes') | |
923 | return BasePathPermissionChecker.create_from_patterns( |
|
927 | return BasePathPermissionChecker.create_from_patterns( | |
924 | includes, excludes) |
|
928 | includes, excludes) | |
925 | except BaseException as e: |
|
929 | except BaseException as e: | |
926 | msg = 'Cannot read ACL settings from {} on {}: {}'.format( |
|
930 | msg = 'Cannot read ACL settings from {} on {}: {}'.format( | |
927 | hgacl_file, self.name, e) |
|
931 | hgacl_file, self.name, e) | |
928 | raise exceptions.RepositoryRequirementError(msg) |
|
932 | raise exceptions.RepositoryRequirementError(msg) | |
929 | else: |
|
933 | else: | |
930 | return None |
|
934 | return None | |
931 |
|
935 | |||
932 |
|
936 | |||
933 | class MercurialIndexBasedCollectionGenerator(CollectionGenerator): |
|
937 | class MercurialIndexBasedCollectionGenerator(CollectionGenerator): | |
934 |
|
938 | |||
935 | def _commit_factory(self, commit_id): |
|
939 | def _commit_factory(self, commit_id): | |
936 | return self.repo.get_commit( |
|
940 | return self.repo.get_commit( | |
937 | commit_idx=commit_id, pre_load=self.pre_load) |
|
941 | commit_idx=commit_id, pre_load=self.pre_load) |
@@ -1,635 +1,635 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2010-2019 RhodeCode GmbH |
|
3 | # Copyright (C) 2010-2019 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | """ |
|
21 | """ | |
22 | this is forms validation classes |
|
22 | this is forms validation classes | |
23 | http://formencode.org/module-formencode.validators.html |
|
23 | http://formencode.org/module-formencode.validators.html | |
24 | for list off all availible validators |
|
24 | for list off all availible validators | |
25 |
|
25 | |||
26 | we can create our own validators |
|
26 | we can create our own validators | |
27 |
|
27 | |||
28 | The table below outlines the options which can be used in a schema in addition to the validators themselves |
|
28 | The table below outlines the options which can be used in a schema in addition to the validators themselves | |
29 | pre_validators [] These validators will be applied before the schema |
|
29 | pre_validators [] These validators will be applied before the schema | |
30 | chained_validators [] These validators will be applied after the schema |
|
30 | chained_validators [] These validators will be applied after the schema | |
31 | allow_extra_fields False If True, then it is not an error when keys that aren't associated with a validator are present |
|
31 | allow_extra_fields False If True, then it is not an error when keys that aren't associated with a validator are present | |
32 | filter_extra_fields False If True, then keys that aren't associated with a validator are removed |
|
32 | filter_extra_fields False If True, then keys that aren't associated with a validator are removed | |
33 | if_key_missing NoDefault If this is given, then any keys that aren't available but are expected will be replaced with this value (and then validated). This does not override a present .if_missing attribute on validators. NoDefault is a special FormEncode class to mean that no default values has been specified and therefore missing keys shouldn't take a default value. |
|
33 | if_key_missing NoDefault If this is given, then any keys that aren't available but are expected will be replaced with this value (and then validated). This does not override a present .if_missing attribute on validators. NoDefault is a special FormEncode class to mean that no default values has been specified and therefore missing keys shouldn't take a default value. | |
34 | ignore_key_missing False If True, then missing keys will be missing in the result, if the validator doesn't have .if_missing on it already |
|
34 | ignore_key_missing False If True, then missing keys will be missing in the result, if the validator doesn't have .if_missing on it already | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | <name> = formencode.validators.<name of validator> |
|
37 | <name> = formencode.validators.<name of validator> | |
38 | <name> must equal form name |
|
38 | <name> must equal form name | |
39 | list=[1,2,3,4,5] |
|
39 | list=[1,2,3,4,5] | |
40 | for SELECT use formencode.All(OneOf(list), Int()) |
|
40 | for SELECT use formencode.All(OneOf(list), Int()) | |
41 |
|
41 | |||
42 | """ |
|
42 | """ | |
43 |
|
43 | |||
44 | import deform |
|
44 | import deform | |
45 | import logging |
|
45 | import logging | |
46 | import formencode |
|
46 | import formencode | |
47 |
|
47 | |||
48 | from pkg_resources import resource_filename |
|
48 | from pkg_resources import resource_filename | |
49 | from formencode import All, Pipe |
|
49 | from formencode import All, Pipe | |
50 |
|
50 | |||
51 | from pyramid.threadlocal import get_current_request |
|
51 | from pyramid.threadlocal import get_current_request | |
52 |
|
52 | |||
53 | from rhodecode import BACKENDS |
|
53 | from rhodecode import BACKENDS | |
54 | from rhodecode.lib import helpers |
|
54 | from rhodecode.lib import helpers | |
55 | from rhodecode.model import validators as v |
|
55 | from rhodecode.model import validators as v | |
56 |
|
56 | |||
57 | log = logging.getLogger(__name__) |
|
57 | log = logging.getLogger(__name__) | |
58 |
|
58 | |||
59 |
|
59 | |||
60 | deform_templates = resource_filename('deform', 'templates') |
|
60 | deform_templates = resource_filename('deform', 'templates') | |
61 | rhodecode_templates = resource_filename('rhodecode', 'templates/forms') |
|
61 | rhodecode_templates = resource_filename('rhodecode', 'templates/forms') | |
62 | search_path = (rhodecode_templates, deform_templates) |
|
62 | search_path = (rhodecode_templates, deform_templates) | |
63 |
|
63 | |||
64 |
|
64 | |||
65 | class RhodecodeFormZPTRendererFactory(deform.ZPTRendererFactory): |
|
65 | class RhodecodeFormZPTRendererFactory(deform.ZPTRendererFactory): | |
66 | """ Subclass of ZPTRendererFactory to add rhodecode context variables """ |
|
66 | """ Subclass of ZPTRendererFactory to add rhodecode context variables """ | |
67 | def __call__(self, template_name, **kw): |
|
67 | def __call__(self, template_name, **kw): | |
68 | kw['h'] = helpers |
|
68 | kw['h'] = helpers | |
69 | kw['request'] = get_current_request() |
|
69 | kw['request'] = get_current_request() | |
70 | return self.load(template_name)(**kw) |
|
70 | return self.load(template_name)(**kw) | |
71 |
|
71 | |||
72 |
|
72 | |||
73 | form_renderer = RhodecodeFormZPTRendererFactory(search_path) |
|
73 | form_renderer = RhodecodeFormZPTRendererFactory(search_path) | |
74 | deform.Form.set_default_renderer(form_renderer) |
|
74 | deform.Form.set_default_renderer(form_renderer) | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | def LoginForm(localizer): |
|
77 | def LoginForm(localizer): | |
78 | _ = localizer |
|
78 | _ = localizer | |
79 |
|
79 | |||
80 | class _LoginForm(formencode.Schema): |
|
80 | class _LoginForm(formencode.Schema): | |
81 | allow_extra_fields = True |
|
81 | allow_extra_fields = True | |
82 | filter_extra_fields = True |
|
82 | filter_extra_fields = True | |
83 | username = v.UnicodeString( |
|
83 | username = v.UnicodeString( | |
84 | strip=True, |
|
84 | strip=True, | |
85 | min=1, |
|
85 | min=1, | |
86 | not_empty=True, |
|
86 | not_empty=True, | |
87 | messages={ |
|
87 | messages={ | |
88 | 'empty': _(u'Please enter a login'), |
|
88 | 'empty': _(u'Please enter a login'), | |
89 | 'tooShort': _(u'Enter a value %(min)i characters long or more') |
|
89 | 'tooShort': _(u'Enter a value %(min)i characters long or more') | |
90 | } |
|
90 | } | |
91 | ) |
|
91 | ) | |
92 |
|
92 | |||
93 | password = v.UnicodeString( |
|
93 | password = v.UnicodeString( | |
94 | strip=False, |
|
94 | strip=False, | |
95 | min=3, |
|
95 | min=3, | |
96 | max=72, |
|
96 | max=72, | |
97 | not_empty=True, |
|
97 | not_empty=True, | |
98 | messages={ |
|
98 | messages={ | |
99 | 'empty': _(u'Please enter a password'), |
|
99 | 'empty': _(u'Please enter a password'), | |
100 | 'tooShort': _(u'Enter %(min)i characters or more')} |
|
100 | 'tooShort': _(u'Enter %(min)i characters or more')} | |
101 | ) |
|
101 | ) | |
102 |
|
102 | |||
103 | remember = v.StringBoolean(if_missing=False) |
|
103 | remember = v.StringBoolean(if_missing=False) | |
104 |
|
104 | |||
105 | chained_validators = [v.ValidAuth(localizer)] |
|
105 | chained_validators = [v.ValidAuth(localizer)] | |
106 | return _LoginForm |
|
106 | return _LoginForm | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | def UserForm(localizer, edit=False, available_languages=None, old_data=None): |
|
109 | def UserForm(localizer, edit=False, available_languages=None, old_data=None): | |
110 | old_data = old_data or {} |
|
110 | old_data = old_data or {} | |
111 | available_languages = available_languages or [] |
|
111 | available_languages = available_languages or [] | |
112 | _ = localizer |
|
112 | _ = localizer | |
113 |
|
113 | |||
114 | class _UserForm(formencode.Schema): |
|
114 | class _UserForm(formencode.Schema): | |
115 | allow_extra_fields = True |
|
115 | allow_extra_fields = True | |
116 | filter_extra_fields = True |
|
116 | filter_extra_fields = True | |
117 | username = All(v.UnicodeString(strip=True, min=1, not_empty=True), |
|
117 | username = All(v.UnicodeString(strip=True, min=1, not_empty=True), | |
118 | v.ValidUsername(localizer, edit, old_data)) |
|
118 | v.ValidUsername(localizer, edit, old_data)) | |
119 | if edit: |
|
119 | if edit: | |
120 | new_password = All( |
|
120 | new_password = All( | |
121 | v.ValidPassword(localizer), |
|
121 | v.ValidPassword(localizer), | |
122 | v.UnicodeString(strip=False, min=6, max=72, not_empty=False) |
|
122 | v.UnicodeString(strip=False, min=6, max=72, not_empty=False) | |
123 | ) |
|
123 | ) | |
124 | password_confirmation = All( |
|
124 | password_confirmation = All( | |
125 | v.ValidPassword(localizer), |
|
125 | v.ValidPassword(localizer), | |
126 | v.UnicodeString(strip=False, min=6, max=72, not_empty=False), |
|
126 | v.UnicodeString(strip=False, min=6, max=72, not_empty=False), | |
127 | ) |
|
127 | ) | |
128 | admin = v.StringBoolean(if_missing=False) |
|
128 | admin = v.StringBoolean(if_missing=False) | |
129 | else: |
|
129 | else: | |
130 | password = All( |
|
130 | password = All( | |
131 | v.ValidPassword(localizer), |
|
131 | v.ValidPassword(localizer), | |
132 | v.UnicodeString(strip=False, min=6, max=72, not_empty=True) |
|
132 | v.UnicodeString(strip=False, min=6, max=72, not_empty=True) | |
133 | ) |
|
133 | ) | |
134 | password_confirmation = All( |
|
134 | password_confirmation = All( | |
135 | v.ValidPassword(localizer), |
|
135 | v.ValidPassword(localizer), | |
136 | v.UnicodeString(strip=False, min=6, max=72, not_empty=False) |
|
136 | v.UnicodeString(strip=False, min=6, max=72, not_empty=False) | |
137 | ) |
|
137 | ) | |
138 |
|
138 | |||
139 | password_change = v.StringBoolean(if_missing=False) |
|
139 | password_change = v.StringBoolean(if_missing=False) | |
140 | create_repo_group = v.StringBoolean(if_missing=False) |
|
140 | create_repo_group = v.StringBoolean(if_missing=False) | |
141 |
|
141 | |||
142 | active = v.StringBoolean(if_missing=False) |
|
142 | active = v.StringBoolean(if_missing=False) | |
143 | firstname = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
143 | firstname = v.UnicodeString(strip=True, min=1, not_empty=False) | |
144 | lastname = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
144 | lastname = v.UnicodeString(strip=True, min=1, not_empty=False) | |
145 | email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True)) |
|
145 | email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True)) | |
146 | extern_name = v.UnicodeString(strip=True) |
|
146 | extern_name = v.UnicodeString(strip=True) | |
147 | extern_type = v.UnicodeString(strip=True) |
|
147 | extern_type = v.UnicodeString(strip=True) | |
148 | language = v.OneOf(available_languages, hideList=False, |
|
148 | language = v.OneOf(available_languages, hideList=False, | |
149 | testValueList=True, if_missing=None) |
|
149 | testValueList=True, if_missing=None) | |
150 | chained_validators = [v.ValidPasswordsMatch(localizer)] |
|
150 | chained_validators = [v.ValidPasswordsMatch(localizer)] | |
151 | return _UserForm |
|
151 | return _UserForm | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | def UserGroupForm(localizer, edit=False, old_data=None, allow_disabled=False): |
|
154 | def UserGroupForm(localizer, edit=False, old_data=None, allow_disabled=False): | |
155 | old_data = old_data or {} |
|
155 | old_data = old_data or {} | |
156 | _ = localizer |
|
156 | _ = localizer | |
157 |
|
157 | |||
158 | class _UserGroupForm(formencode.Schema): |
|
158 | class _UserGroupForm(formencode.Schema): | |
159 | allow_extra_fields = True |
|
159 | allow_extra_fields = True | |
160 | filter_extra_fields = True |
|
160 | filter_extra_fields = True | |
161 |
|
161 | |||
162 | users_group_name = All( |
|
162 | users_group_name = All( | |
163 | v.UnicodeString(strip=True, min=1, not_empty=True), |
|
163 | v.UnicodeString(strip=True, min=1, not_empty=True), | |
164 | v.ValidUserGroup(localizer, edit, old_data) |
|
164 | v.ValidUserGroup(localizer, edit, old_data) | |
165 | ) |
|
165 | ) | |
166 | user_group_description = v.UnicodeString(strip=True, min=1, |
|
166 | user_group_description = v.UnicodeString(strip=True, min=1, | |
167 | not_empty=False) |
|
167 | not_empty=False) | |
168 |
|
168 | |||
169 | users_group_active = v.StringBoolean(if_missing=False) |
|
169 | users_group_active = v.StringBoolean(if_missing=False) | |
170 |
|
170 | |||
171 | if edit: |
|
171 | if edit: | |
172 | # this is user group owner |
|
172 | # this is user group owner | |
173 | user = All( |
|
173 | user = All( | |
174 | v.UnicodeString(not_empty=True), |
|
174 | v.UnicodeString(not_empty=True), | |
175 | v.ValidRepoUser(localizer, allow_disabled)) |
|
175 | v.ValidRepoUser(localizer, allow_disabled)) | |
176 | return _UserGroupForm |
|
176 | return _UserGroupForm | |
177 |
|
177 | |||
178 |
|
178 | |||
179 | def RepoGroupForm(localizer, edit=False, old_data=None, available_groups=None, |
|
179 | def RepoGroupForm(localizer, edit=False, old_data=None, available_groups=None, | |
180 | can_create_in_root=False, allow_disabled=False): |
|
180 | can_create_in_root=False, allow_disabled=False): | |
181 | _ = localizer |
|
181 | _ = localizer | |
182 | old_data = old_data or {} |
|
182 | old_data = old_data or {} | |
183 | available_groups = available_groups or [] |
|
183 | available_groups = available_groups or [] | |
184 |
|
184 | |||
185 | class _RepoGroupForm(formencode.Schema): |
|
185 | class _RepoGroupForm(formencode.Schema): | |
186 | allow_extra_fields = True |
|
186 | allow_extra_fields = True | |
187 | filter_extra_fields = False |
|
187 | filter_extra_fields = False | |
188 |
|
188 | |||
189 | group_name = All(v.UnicodeString(strip=True, min=1, not_empty=True), |
|
189 | group_name = All(v.UnicodeString(strip=True, min=1, not_empty=True), | |
190 | v.SlugifyName(localizer),) |
|
190 | v.SlugifyName(localizer),) | |
191 | group_description = v.UnicodeString(strip=True, min=1, |
|
191 | group_description = v.UnicodeString(strip=True, min=1, | |
192 | not_empty=False) |
|
192 | not_empty=False) | |
193 | group_copy_permissions = v.StringBoolean(if_missing=False) |
|
193 | group_copy_permissions = v.StringBoolean(if_missing=False) | |
194 |
|
194 | |||
195 | group_parent_id = v.OneOf(available_groups, hideList=False, |
|
195 | group_parent_id = v.OneOf(available_groups, hideList=False, | |
196 | testValueList=True, not_empty=True) |
|
196 | testValueList=True, not_empty=True) | |
197 | enable_locking = v.StringBoolean(if_missing=False) |
|
197 | enable_locking = v.StringBoolean(if_missing=False) | |
198 | chained_validators = [ |
|
198 | chained_validators = [ | |
199 | v.ValidRepoGroup(localizer, edit, old_data, can_create_in_root)] |
|
199 | v.ValidRepoGroup(localizer, edit, old_data, can_create_in_root)] | |
200 |
|
200 | |||
201 | if edit: |
|
201 | if edit: | |
202 | # this is repo group owner |
|
202 | # this is repo group owner | |
203 | user = All( |
|
203 | user = All( | |
204 | v.UnicodeString(not_empty=True), |
|
204 | v.UnicodeString(not_empty=True), | |
205 | v.ValidRepoUser(localizer, allow_disabled)) |
|
205 | v.ValidRepoUser(localizer, allow_disabled)) | |
206 | return _RepoGroupForm |
|
206 | return _RepoGroupForm | |
207 |
|
207 | |||
208 |
|
208 | |||
209 | def RegisterForm(localizer, edit=False, old_data=None): |
|
209 | def RegisterForm(localizer, edit=False, old_data=None): | |
210 | _ = localizer |
|
210 | _ = localizer | |
211 | old_data = old_data or {} |
|
211 | old_data = old_data or {} | |
212 |
|
212 | |||
213 | class _RegisterForm(formencode.Schema): |
|
213 | class _RegisterForm(formencode.Schema): | |
214 | allow_extra_fields = True |
|
214 | allow_extra_fields = True | |
215 | filter_extra_fields = True |
|
215 | filter_extra_fields = True | |
216 | username = All( |
|
216 | username = All( | |
217 | v.ValidUsername(localizer, edit, old_data), |
|
217 | v.ValidUsername(localizer, edit, old_data), | |
218 | v.UnicodeString(strip=True, min=1, not_empty=True) |
|
218 | v.UnicodeString(strip=True, min=1, not_empty=True) | |
219 | ) |
|
219 | ) | |
220 | password = All( |
|
220 | password = All( | |
221 | v.ValidPassword(localizer), |
|
221 | v.ValidPassword(localizer), | |
222 | v.UnicodeString(strip=False, min=6, max=72, not_empty=True) |
|
222 | v.UnicodeString(strip=False, min=6, max=72, not_empty=True) | |
223 | ) |
|
223 | ) | |
224 | password_confirmation = All( |
|
224 | password_confirmation = All( | |
225 | v.ValidPassword(localizer), |
|
225 | v.ValidPassword(localizer), | |
226 | v.UnicodeString(strip=False, min=6, max=72, not_empty=True) |
|
226 | v.UnicodeString(strip=False, min=6, max=72, not_empty=True) | |
227 | ) |
|
227 | ) | |
228 | active = v.StringBoolean(if_missing=False) |
|
228 | active = v.StringBoolean(if_missing=False) | |
229 | firstname = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
229 | firstname = v.UnicodeString(strip=True, min=1, not_empty=False) | |
230 | lastname = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
230 | lastname = v.UnicodeString(strip=True, min=1, not_empty=False) | |
231 | email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True)) |
|
231 | email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True)) | |
232 |
|
232 | |||
233 | chained_validators = [v.ValidPasswordsMatch(localizer)] |
|
233 | chained_validators = [v.ValidPasswordsMatch(localizer)] | |
234 | return _RegisterForm |
|
234 | return _RegisterForm | |
235 |
|
235 | |||
236 |
|
236 | |||
237 | def PasswordResetForm(localizer): |
|
237 | def PasswordResetForm(localizer): | |
238 | _ = localizer |
|
238 | _ = localizer | |
239 |
|
239 | |||
240 | class _PasswordResetForm(formencode.Schema): |
|
240 | class _PasswordResetForm(formencode.Schema): | |
241 | allow_extra_fields = True |
|
241 | allow_extra_fields = True | |
242 | filter_extra_fields = True |
|
242 | filter_extra_fields = True | |
243 | email = All(v.ValidSystemEmail(localizer), v.Email(not_empty=True)) |
|
243 | email = All(v.ValidSystemEmail(localizer), v.Email(not_empty=True)) | |
244 | return _PasswordResetForm |
|
244 | return _PasswordResetForm | |
245 |
|
245 | |||
246 |
|
246 | |||
247 | def RepoForm(localizer, edit=False, old_data=None, repo_groups=None, |
|
247 | def RepoForm(localizer, edit=False, old_data=None, repo_groups=None, | |
248 | landing_revs=None, allow_disabled=False): |
|
248 | landing_revs=None, allow_disabled=False): | |
249 | _ = localizer |
|
249 | _ = localizer | |
250 | old_data = old_data or {} |
|
250 | old_data = old_data or {} | |
251 | repo_groups = repo_groups or [] |
|
251 | repo_groups = repo_groups or [] | |
252 | landing_revs = landing_revs or [] |
|
252 | landing_revs = landing_revs or [] | |
253 | supported_backends = BACKENDS.keys() |
|
253 | supported_backends = BACKENDS.keys() | |
254 |
|
254 | |||
255 | class _RepoForm(formencode.Schema): |
|
255 | class _RepoForm(formencode.Schema): | |
256 | allow_extra_fields = True |
|
256 | allow_extra_fields = True | |
257 | filter_extra_fields = False |
|
257 | filter_extra_fields = False | |
258 | repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True), |
|
258 | repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True), | |
259 | v.SlugifyName(localizer), v.CannotHaveGitSuffix(localizer)) |
|
259 | v.SlugifyName(localizer), v.CannotHaveGitSuffix(localizer)) | |
260 | repo_group = All(v.CanWriteGroup(localizer, old_data), |
|
260 | repo_group = All(v.CanWriteGroup(localizer, old_data), | |
261 | v.OneOf(repo_groups, hideList=True)) |
|
261 | v.OneOf(repo_groups, hideList=True)) | |
262 | repo_type = v.OneOf(supported_backends, required=False, |
|
262 | repo_type = v.OneOf(supported_backends, required=False, | |
263 | if_missing=old_data.get('repo_type')) |
|
263 | if_missing=old_data.get('repo_type')) | |
264 | repo_description = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
264 | repo_description = v.UnicodeString(strip=True, min=1, not_empty=False) | |
265 | repo_private = v.StringBoolean(if_missing=False) |
|
265 | repo_private = v.StringBoolean(if_missing=False) | |
266 | repo_landing_rev = v.OneOf(landing_revs, hideList=True) |
|
266 | repo_landing_rev = v.OneOf(landing_revs, hideList=True) | |
267 | repo_copy_permissions = v.StringBoolean(if_missing=False) |
|
267 | repo_copy_permissions = v.StringBoolean(if_missing=False) | |
268 | clone_uri = All(v.UnicodeString(strip=True, min=1, not_empty=False)) |
|
268 | clone_uri = All(v.UnicodeString(strip=True, min=1, not_empty=False)) | |
269 |
|
269 | |||
270 | repo_enable_statistics = v.StringBoolean(if_missing=False) |
|
270 | repo_enable_statistics = v.StringBoolean(if_missing=False) | |
271 | repo_enable_downloads = v.StringBoolean(if_missing=False) |
|
271 | repo_enable_downloads = v.StringBoolean(if_missing=False) | |
272 | repo_enable_locking = v.StringBoolean(if_missing=False) |
|
272 | repo_enable_locking = v.StringBoolean(if_missing=False) | |
273 |
|
273 | |||
274 | if edit: |
|
274 | if edit: | |
275 | # this is repo owner |
|
275 | # this is repo owner | |
276 | user = All( |
|
276 | user = All( | |
277 | v.UnicodeString(not_empty=True), |
|
277 | v.UnicodeString(not_empty=True), | |
278 | v.ValidRepoUser(localizer, allow_disabled)) |
|
278 | v.ValidRepoUser(localizer, allow_disabled)) | |
279 | clone_uri_change = v.UnicodeString( |
|
279 | clone_uri_change = v.UnicodeString( | |
280 | not_empty=False, if_missing=v.Missing) |
|
280 | not_empty=False, if_missing=v.Missing) | |
281 |
|
281 | |||
282 | chained_validators = [v.ValidCloneUri(localizer), |
|
282 | chained_validators = [v.ValidCloneUri(localizer), | |
283 | v.ValidRepoName(localizer, edit, old_data)] |
|
283 | v.ValidRepoName(localizer, edit, old_data)] | |
284 | return _RepoForm |
|
284 | return _RepoForm | |
285 |
|
285 | |||
286 |
|
286 | |||
287 | def RepoPermsForm(localizer): |
|
287 | def RepoPermsForm(localizer): | |
288 | _ = localizer |
|
288 | _ = localizer | |
289 |
|
289 | |||
290 | class _RepoPermsForm(formencode.Schema): |
|
290 | class _RepoPermsForm(formencode.Schema): | |
291 | allow_extra_fields = True |
|
291 | allow_extra_fields = True | |
292 | filter_extra_fields = False |
|
292 | filter_extra_fields = False | |
293 | chained_validators = [v.ValidPerms(localizer, type_='repo')] |
|
293 | chained_validators = [v.ValidPerms(localizer, type_='repo')] | |
294 | return _RepoPermsForm |
|
294 | return _RepoPermsForm | |
295 |
|
295 | |||
296 |
|
296 | |||
297 | def RepoGroupPermsForm(localizer, valid_recursive_choices): |
|
297 | def RepoGroupPermsForm(localizer, valid_recursive_choices): | |
298 | _ = localizer |
|
298 | _ = localizer | |
299 |
|
299 | |||
300 | class _RepoGroupPermsForm(formencode.Schema): |
|
300 | class _RepoGroupPermsForm(formencode.Schema): | |
301 | allow_extra_fields = True |
|
301 | allow_extra_fields = True | |
302 | filter_extra_fields = False |
|
302 | filter_extra_fields = False | |
303 | recursive = v.OneOf(valid_recursive_choices) |
|
303 | recursive = v.OneOf(valid_recursive_choices) | |
304 | chained_validators = [v.ValidPerms(localizer, type_='repo_group')] |
|
304 | chained_validators = [v.ValidPerms(localizer, type_='repo_group')] | |
305 | return _RepoGroupPermsForm |
|
305 | return _RepoGroupPermsForm | |
306 |
|
306 | |||
307 |
|
307 | |||
308 | def UserGroupPermsForm(localizer): |
|
308 | def UserGroupPermsForm(localizer): | |
309 | _ = localizer |
|
309 | _ = localizer | |
310 |
|
310 | |||
311 | class _UserPermsForm(formencode.Schema): |
|
311 | class _UserPermsForm(formencode.Schema): | |
312 | allow_extra_fields = True |
|
312 | allow_extra_fields = True | |
313 | filter_extra_fields = False |
|
313 | filter_extra_fields = False | |
314 | chained_validators = [v.ValidPerms(localizer, type_='user_group')] |
|
314 | chained_validators = [v.ValidPerms(localizer, type_='user_group')] | |
315 | return _UserPermsForm |
|
315 | return _UserPermsForm | |
316 |
|
316 | |||
317 |
|
317 | |||
318 | def RepoFieldForm(localizer): |
|
318 | def RepoFieldForm(localizer): | |
319 | _ = localizer |
|
319 | _ = localizer | |
320 |
|
320 | |||
321 | class _RepoFieldForm(formencode.Schema): |
|
321 | class _RepoFieldForm(formencode.Schema): | |
322 | filter_extra_fields = True |
|
322 | filter_extra_fields = True | |
323 | allow_extra_fields = True |
|
323 | allow_extra_fields = True | |
324 |
|
324 | |||
325 | new_field_key = All(v.FieldKey(localizer), |
|
325 | new_field_key = All(v.FieldKey(localizer), | |
326 | v.UnicodeString(strip=True, min=3, not_empty=True)) |
|
326 | v.UnicodeString(strip=True, min=3, not_empty=True)) | |
327 | new_field_value = v.UnicodeString(not_empty=False, if_missing=u'') |
|
327 | new_field_value = v.UnicodeString(not_empty=False, if_missing=u'') | |
328 | new_field_type = v.OneOf(['str', 'unicode', 'list', 'tuple'], |
|
328 | new_field_type = v.OneOf(['str', 'unicode', 'list', 'tuple'], | |
329 | if_missing='str') |
|
329 | if_missing='str') | |
330 | new_field_label = v.UnicodeString(not_empty=False) |
|
330 | new_field_label = v.UnicodeString(not_empty=False) | |
331 | new_field_desc = v.UnicodeString(not_empty=False) |
|
331 | new_field_desc = v.UnicodeString(not_empty=False) | |
332 | return _RepoFieldForm |
|
332 | return _RepoFieldForm | |
333 |
|
333 | |||
334 |
|
334 | |||
335 | def RepoForkForm(localizer, edit=False, old_data=None, |
|
335 | def RepoForkForm(localizer, edit=False, old_data=None, | |
336 | supported_backends=BACKENDS.keys(), repo_groups=None, |
|
336 | supported_backends=BACKENDS.keys(), repo_groups=None, | |
337 | landing_revs=None): |
|
337 | landing_revs=None): | |
338 | _ = localizer |
|
338 | _ = localizer | |
339 | old_data = old_data or {} |
|
339 | old_data = old_data or {} | |
340 | repo_groups = repo_groups or [] |
|
340 | repo_groups = repo_groups or [] | |
341 | landing_revs = landing_revs or [] |
|
341 | landing_revs = landing_revs or [] | |
342 |
|
342 | |||
343 | class _RepoForkForm(formencode.Schema): |
|
343 | class _RepoForkForm(formencode.Schema): | |
344 | allow_extra_fields = True |
|
344 | allow_extra_fields = True | |
345 | filter_extra_fields = False |
|
345 | filter_extra_fields = False | |
346 | repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True), |
|
346 | repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True), | |
347 | v.SlugifyName(localizer)) |
|
347 | v.SlugifyName(localizer)) | |
348 | repo_group = All(v.CanWriteGroup(localizer, ), |
|
348 | repo_group = All(v.CanWriteGroup(localizer, ), | |
349 | v.OneOf(repo_groups, hideList=True)) |
|
349 | v.OneOf(repo_groups, hideList=True)) | |
350 | repo_type = All(v.ValidForkType(localizer, old_data), v.OneOf(supported_backends)) |
|
350 | repo_type = All(v.ValidForkType(localizer, old_data), v.OneOf(supported_backends)) | |
351 | description = v.UnicodeString(strip=True, min=1, not_empty=True) |
|
351 | description = v.UnicodeString(strip=True, min=1, not_empty=True) | |
352 | private = v.StringBoolean(if_missing=False) |
|
352 | private = v.StringBoolean(if_missing=False) | |
353 | copy_permissions = v.StringBoolean(if_missing=False) |
|
353 | copy_permissions = v.StringBoolean(if_missing=False) | |
354 | fork_parent_id = v.UnicodeString() |
|
354 | fork_parent_id = v.UnicodeString() | |
355 | chained_validators = [v.ValidForkName(localizer, edit, old_data)] |
|
355 | chained_validators = [v.ValidForkName(localizer, edit, old_data)] | |
356 | landing_rev = v.OneOf(landing_revs, hideList=True) |
|
356 | landing_rev = v.OneOf(landing_revs, hideList=True) | |
357 | return _RepoForkForm |
|
357 | return _RepoForkForm | |
358 |
|
358 | |||
359 |
|
359 | |||
360 | def ApplicationSettingsForm(localizer): |
|
360 | def ApplicationSettingsForm(localizer): | |
361 | _ = localizer |
|
361 | _ = localizer | |
362 |
|
362 | |||
363 | class _ApplicationSettingsForm(formencode.Schema): |
|
363 | class _ApplicationSettingsForm(formencode.Schema): | |
364 | allow_extra_fields = True |
|
364 | allow_extra_fields = True | |
365 | filter_extra_fields = False |
|
365 | filter_extra_fields = False | |
366 | rhodecode_title = v.UnicodeString(strip=True, max=40, not_empty=False) |
|
366 | rhodecode_title = v.UnicodeString(strip=True, max=40, not_empty=False) | |
367 | rhodecode_realm = v.UnicodeString(strip=True, min=1, not_empty=True) |
|
367 | rhodecode_realm = v.UnicodeString(strip=True, min=1, not_empty=True) | |
368 | rhodecode_pre_code = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
368 | rhodecode_pre_code = v.UnicodeString(strip=True, min=1, not_empty=False) | |
369 | rhodecode_post_code = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
369 | rhodecode_post_code = v.UnicodeString(strip=True, min=1, not_empty=False) | |
370 | rhodecode_captcha_public_key = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
370 | rhodecode_captcha_public_key = v.UnicodeString(strip=True, min=1, not_empty=False) | |
371 | rhodecode_captcha_private_key = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
371 | rhodecode_captcha_private_key = v.UnicodeString(strip=True, min=1, not_empty=False) | |
372 | rhodecode_create_personal_repo_group = v.StringBoolean(if_missing=False) |
|
372 | rhodecode_create_personal_repo_group = v.StringBoolean(if_missing=False) | |
373 | rhodecode_personal_repo_group_pattern = v.UnicodeString(strip=True, min=1, not_empty=False) |
|
373 | rhodecode_personal_repo_group_pattern = v.UnicodeString(strip=True, min=1, not_empty=False) | |
374 | return _ApplicationSettingsForm |
|
374 | return _ApplicationSettingsForm | |
375 |
|
375 | |||
376 |
|
376 | |||
377 | def ApplicationVisualisationForm(localizer): |
|
377 | def ApplicationVisualisationForm(localizer): | |
378 | from rhodecode.model.db import Repository |
|
378 | from rhodecode.model.db import Repository | |
379 | _ = localizer |
|
379 | _ = localizer | |
380 |
|
380 | |||
381 | class _ApplicationVisualisationForm(formencode.Schema): |
|
381 | class _ApplicationVisualisationForm(formencode.Schema): | |
382 | allow_extra_fields = True |
|
382 | allow_extra_fields = True | |
383 | filter_extra_fields = False |
|
383 | filter_extra_fields = False | |
384 | rhodecode_show_public_icon = v.StringBoolean(if_missing=False) |
|
384 | rhodecode_show_public_icon = v.StringBoolean(if_missing=False) | |
385 | rhodecode_show_private_icon = v.StringBoolean(if_missing=False) |
|
385 | rhodecode_show_private_icon = v.StringBoolean(if_missing=False) | |
386 | rhodecode_stylify_metatags = v.StringBoolean(if_missing=False) |
|
386 | rhodecode_stylify_metatags = v.StringBoolean(if_missing=False) | |
387 |
|
387 | |||
388 | rhodecode_repository_fields = v.StringBoolean(if_missing=False) |
|
388 | rhodecode_repository_fields = v.StringBoolean(if_missing=False) | |
389 | rhodecode_lightweight_journal = v.StringBoolean(if_missing=False) |
|
389 | rhodecode_lightweight_journal = v.StringBoolean(if_missing=False) | |
390 | rhodecode_dashboard_items = v.Int(min=5, not_empty=True) |
|
390 | rhodecode_dashboard_items = v.Int(min=5, not_empty=True) | |
391 | rhodecode_admin_grid_items = v.Int(min=5, not_empty=True) |
|
391 | rhodecode_admin_grid_items = v.Int(min=5, not_empty=True) | |
392 | rhodecode_show_version = v.StringBoolean(if_missing=False) |
|
392 | rhodecode_show_version = v.StringBoolean(if_missing=False) | |
393 | rhodecode_use_gravatar = v.StringBoolean(if_missing=False) |
|
393 | rhodecode_use_gravatar = v.StringBoolean(if_missing=False) | |
394 | rhodecode_markup_renderer = v.OneOf(['markdown', 'rst']) |
|
394 | rhodecode_markup_renderer = v.OneOf(['markdown', 'rst']) | |
395 | rhodecode_gravatar_url = v.UnicodeString(min=3) |
|
395 | rhodecode_gravatar_url = v.UnicodeString(min=3) | |
396 | rhodecode_clone_uri_tmpl = v.UnicodeString(not_empty=False, if_empty=Repository.DEFAULT_CLONE_URI) |
|
396 | rhodecode_clone_uri_tmpl = v.UnicodeString(not_empty=False, if_empty=Repository.DEFAULT_CLONE_URI) | |
397 | rhodecode_clone_uri_ssh_tmpl = v.UnicodeString(not_empty=False, if_empty=Repository.DEFAULT_CLONE_URI_SSH) |
|
397 | rhodecode_clone_uri_ssh_tmpl = v.UnicodeString(not_empty=False, if_empty=Repository.DEFAULT_CLONE_URI_SSH) | |
398 | rhodecode_support_url = v.UnicodeString() |
|
398 | rhodecode_support_url = v.UnicodeString() | |
399 | rhodecode_show_revision_number = v.StringBoolean(if_missing=False) |
|
399 | rhodecode_show_revision_number = v.StringBoolean(if_missing=False) | |
400 | rhodecode_show_sha_length = v.Int(min=4, not_empty=True) |
|
400 | rhodecode_show_sha_length = v.Int(min=4, not_empty=True) | |
401 | return _ApplicationVisualisationForm |
|
401 | return _ApplicationVisualisationForm | |
402 |
|
402 | |||
403 |
|
403 | |||
404 | class _BaseVcsSettingsForm(formencode.Schema): |
|
404 | class _BaseVcsSettingsForm(formencode.Schema): | |
405 |
|
405 | |||
406 | allow_extra_fields = True |
|
406 | allow_extra_fields = True | |
407 | filter_extra_fields = False |
|
407 | filter_extra_fields = False | |
408 | hooks_changegroup_repo_size = v.StringBoolean(if_missing=False) |
|
408 | hooks_changegroup_repo_size = v.StringBoolean(if_missing=False) | |
409 | hooks_changegroup_push_logger = v.StringBoolean(if_missing=False) |
|
409 | hooks_changegroup_push_logger = v.StringBoolean(if_missing=False) | |
410 | hooks_outgoing_pull_logger = v.StringBoolean(if_missing=False) |
|
410 | hooks_outgoing_pull_logger = v.StringBoolean(if_missing=False) | |
411 |
|
411 | |||
412 | # PR/Code-review |
|
412 | # PR/Code-review | |
413 | rhodecode_pr_merge_enabled = v.StringBoolean(if_missing=False) |
|
413 | rhodecode_pr_merge_enabled = v.StringBoolean(if_missing=False) | |
414 | rhodecode_use_outdated_comments = v.StringBoolean(if_missing=False) |
|
414 | rhodecode_use_outdated_comments = v.StringBoolean(if_missing=False) | |
415 |
|
415 | |||
416 | # hg |
|
416 | # hg | |
417 | extensions_largefiles = v.StringBoolean(if_missing=False) |
|
417 | extensions_largefiles = v.StringBoolean(if_missing=False) | |
418 | extensions_evolve = v.StringBoolean(if_missing=False) |
|
418 | extensions_evolve = v.StringBoolean(if_missing=False) | |
419 | phases_publish = v.StringBoolean(if_missing=False) |
|
419 | phases_publish = v.StringBoolean(if_missing=False) | |
420 |
|
420 | |||
421 | rhodecode_hg_use_rebase_for_merging = v.StringBoolean(if_missing=False) |
|
421 | rhodecode_hg_use_rebase_for_merging = v.StringBoolean(if_missing=False) | |
422 | rhodecode_hg_close_branch_before_merging = v.StringBoolean(if_missing=False) |
|
422 | rhodecode_hg_close_branch_before_merging = v.StringBoolean(if_missing=False) | |
423 |
|
423 | |||
424 | # git |
|
424 | # git | |
425 | vcs_git_lfs_enabled = v.StringBoolean(if_missing=False) |
|
425 | vcs_git_lfs_enabled = v.StringBoolean(if_missing=False) | |
426 | rhodecode_git_use_rebase_for_merging = v.StringBoolean(if_missing=False) |
|
426 | rhodecode_git_use_rebase_for_merging = v.StringBoolean(if_missing=False) | |
427 | rhodecode_git_close_branch_before_merging = v.StringBoolean(if_missing=False) |
|
427 | rhodecode_git_close_branch_before_merging = v.StringBoolean(if_missing=False) | |
428 |
|
428 | |||
429 | # svn |
|
429 | # svn | |
430 | vcs_svn_proxy_http_requests_enabled = v.StringBoolean(if_missing=False) |
|
430 | vcs_svn_proxy_http_requests_enabled = v.StringBoolean(if_missing=False) | |
431 | vcs_svn_proxy_http_server_url = v.UnicodeString(strip=True, if_missing=None) |
|
431 | vcs_svn_proxy_http_server_url = v.UnicodeString(strip=True, if_missing=None) | |
432 |
|
432 | |||
433 | # cache |
|
433 | # cache | |
434 | rhodecode_diff_cache = v.StringBoolean(if_missing=False) |
|
434 | rhodecode_diff_cache = v.StringBoolean(if_missing=False) | |
435 |
|
435 | |||
436 |
|
436 | |||
437 | def ApplicationUiSettingsForm(localizer): |
|
437 | def ApplicationUiSettingsForm(localizer): | |
438 | _ = localizer |
|
438 | _ = localizer | |
439 |
|
439 | |||
440 | class _ApplicationUiSettingsForm(_BaseVcsSettingsForm): |
|
440 | class _ApplicationUiSettingsForm(_BaseVcsSettingsForm): | |
441 | web_push_ssl = v.StringBoolean(if_missing=False) |
|
441 | web_push_ssl = v.StringBoolean(if_missing=False) | |
442 | paths_root_path = All( |
|
442 | paths_root_path = All( | |
443 | v.ValidPath(localizer), |
|
443 | v.ValidPath(localizer), | |
444 | v.UnicodeString(strip=True, min=1, not_empty=True) |
|
444 | v.UnicodeString(strip=True, min=1, not_empty=True) | |
445 | ) |
|
445 | ) | |
446 | largefiles_usercache = All( |
|
446 | largefiles_usercache = All( | |
447 | v.ValidPath(localizer), |
|
447 | v.ValidPath(localizer), | |
448 | v.UnicodeString(strip=True, min=2, not_empty=True)) |
|
448 | v.UnicodeString(strip=True, min=2, not_empty=True)) | |
449 | vcs_git_lfs_store_location = All( |
|
449 | vcs_git_lfs_store_location = All( | |
450 | v.ValidPath(localizer), |
|
450 | v.ValidPath(localizer), | |
451 | v.UnicodeString(strip=True, min=2, not_empty=True)) |
|
451 | v.UnicodeString(strip=True, min=2, not_empty=True)) | |
452 | extensions_hgsubversion = v.StringBoolean(if_missing=False) |
|
452 | extensions_hgsubversion = v.StringBoolean(if_missing=False) | |
453 | extensions_hggit = v.StringBoolean(if_missing=False) |
|
453 | extensions_hggit = v.StringBoolean(if_missing=False) | |
454 | new_svn_branch = v.ValidSvnPattern(localizer, section='vcs_svn_branch') |
|
454 | new_svn_branch = v.ValidSvnPattern(localizer, section='vcs_svn_branch') | |
455 | new_svn_tag = v.ValidSvnPattern(localizer, section='vcs_svn_tag') |
|
455 | new_svn_tag = v.ValidSvnPattern(localizer, section='vcs_svn_tag') | |
456 | return _ApplicationUiSettingsForm |
|
456 | return _ApplicationUiSettingsForm | |
457 |
|
457 | |||
458 |
|
458 | |||
459 | def RepoVcsSettingsForm(localizer, repo_name): |
|
459 | def RepoVcsSettingsForm(localizer, repo_name): | |
460 | _ = localizer |
|
460 | _ = localizer | |
461 |
|
461 | |||
462 | class _RepoVcsSettingsForm(_BaseVcsSettingsForm): |
|
462 | class _RepoVcsSettingsForm(_BaseVcsSettingsForm): | |
463 | inherit_global_settings = v.StringBoolean(if_missing=False) |
|
463 | inherit_global_settings = v.StringBoolean(if_missing=False) | |
464 | new_svn_branch = v.ValidSvnPattern(localizer, |
|
464 | new_svn_branch = v.ValidSvnPattern(localizer, | |
465 | section='vcs_svn_branch', repo_name=repo_name) |
|
465 | section='vcs_svn_branch', repo_name=repo_name) | |
466 | new_svn_tag = v.ValidSvnPattern(localizer, |
|
466 | new_svn_tag = v.ValidSvnPattern(localizer, | |
467 | section='vcs_svn_tag', repo_name=repo_name) |
|
467 | section='vcs_svn_tag', repo_name=repo_name) | |
468 | return _RepoVcsSettingsForm |
|
468 | return _RepoVcsSettingsForm | |
469 |
|
469 | |||
470 |
|
470 | |||
471 | def LabsSettingsForm(localizer): |
|
471 | def LabsSettingsForm(localizer): | |
472 | _ = localizer |
|
472 | _ = localizer | |
473 |
|
473 | |||
474 | class _LabSettingsForm(formencode.Schema): |
|
474 | class _LabSettingsForm(formencode.Schema): | |
475 | allow_extra_fields = True |
|
475 | allow_extra_fields = True | |
476 | filter_extra_fields = False |
|
476 | filter_extra_fields = False | |
477 | return _LabSettingsForm |
|
477 | return _LabSettingsForm | |
478 |
|
478 | |||
479 |
|
479 | |||
480 | def ApplicationPermissionsForm( |
|
480 | def ApplicationPermissionsForm( | |
481 | localizer, register_choices, password_reset_choices, |
|
481 | localizer, register_choices, password_reset_choices, | |
482 | extern_activate_choices): |
|
482 | extern_activate_choices): | |
483 | _ = localizer |
|
483 | _ = localizer | |
484 |
|
484 | |||
485 | class _DefaultPermissionsForm(formencode.Schema): |
|
485 | class _DefaultPermissionsForm(formencode.Schema): | |
486 | allow_extra_fields = True |
|
486 | allow_extra_fields = True | |
487 | filter_extra_fields = True |
|
487 | filter_extra_fields = True | |
488 |
|
488 | |||
489 | anonymous = v.StringBoolean(if_missing=False) |
|
489 | anonymous = v.StringBoolean(if_missing=False) | |
490 | default_register = v.OneOf(register_choices) |
|
490 | default_register = v.OneOf(register_choices) | |
491 | default_register_message = v.UnicodeString() |
|
491 | default_register_message = v.UnicodeString() | |
492 | default_password_reset = v.OneOf(password_reset_choices) |
|
492 | default_password_reset = v.OneOf(password_reset_choices) | |
493 | default_extern_activate = v.OneOf(extern_activate_choices) |
|
493 | default_extern_activate = v.OneOf(extern_activate_choices) | |
494 | return _DefaultPermissionsForm |
|
494 | return _DefaultPermissionsForm | |
495 |
|
495 | |||
496 |
|
496 | |||
497 | def ObjectPermissionsForm(localizer, repo_perms_choices, group_perms_choices, |
|
497 | def ObjectPermissionsForm(localizer, repo_perms_choices, group_perms_choices, | |
498 | user_group_perms_choices): |
|
498 | user_group_perms_choices): | |
499 | _ = localizer |
|
499 | _ = localizer | |
500 |
|
500 | |||
501 | class _ObjectPermissionsForm(formencode.Schema): |
|
501 | class _ObjectPermissionsForm(formencode.Schema): | |
502 | allow_extra_fields = True |
|
502 | allow_extra_fields = True | |
503 | filter_extra_fields = True |
|
503 | filter_extra_fields = True | |
504 | overwrite_default_repo = v.StringBoolean(if_missing=False) |
|
504 | overwrite_default_repo = v.StringBoolean(if_missing=False) | |
505 | overwrite_default_group = v.StringBoolean(if_missing=False) |
|
505 | overwrite_default_group = v.StringBoolean(if_missing=False) | |
506 | overwrite_default_user_group = v.StringBoolean(if_missing=False) |
|
506 | overwrite_default_user_group = v.StringBoolean(if_missing=False) | |
507 |
|
507 | |||
508 | default_repo_perm = v.OneOf(repo_perms_choices) |
|
508 | default_repo_perm = v.OneOf(repo_perms_choices) | |
509 | default_group_perm = v.OneOf(group_perms_choices) |
|
509 | default_group_perm = v.OneOf(group_perms_choices) | |
510 | default_user_group_perm = v.OneOf(user_group_perms_choices) |
|
510 | default_user_group_perm = v.OneOf(user_group_perms_choices) | |
511 |
|
511 | |||
512 | return _ObjectPermissionsForm |
|
512 | return _ObjectPermissionsForm | |
513 |
|
513 | |||
514 |
|
514 | |||
515 | def BranchPermissionsForm(localizer, branch_perms_choices): |
|
515 | def BranchPermissionsForm(localizer, branch_perms_choices): | |
516 | _ = localizer |
|
516 | _ = localizer | |
517 |
|
517 | |||
518 | class _BranchPermissionsForm(formencode.Schema): |
|
518 | class _BranchPermissionsForm(formencode.Schema): | |
519 | allow_extra_fields = True |
|
519 | allow_extra_fields = True | |
520 | filter_extra_fields = True |
|
520 | filter_extra_fields = True | |
521 | overwrite_default_branch = v.StringBoolean(if_missing=False) |
|
521 | overwrite_default_branch = v.StringBoolean(if_missing=False) | |
522 | default_branch_perm = v.OneOf(branch_perms_choices) |
|
522 | default_branch_perm = v.OneOf(branch_perms_choices) | |
523 |
|
523 | |||
524 | return _BranchPermissionsForm |
|
524 | return _BranchPermissionsForm | |
525 |
|
525 | |||
526 |
|
526 | |||
527 | def UserPermissionsForm(localizer, create_choices, create_on_write_choices, |
|
527 | def UserPermissionsForm(localizer, create_choices, create_on_write_choices, | |
528 | repo_group_create_choices, user_group_create_choices, |
|
528 | repo_group_create_choices, user_group_create_choices, | |
529 | fork_choices, inherit_default_permissions_choices): |
|
529 | fork_choices, inherit_default_permissions_choices): | |
530 | _ = localizer |
|
530 | _ = localizer | |
531 |
|
531 | |||
532 | class _DefaultPermissionsForm(formencode.Schema): |
|
532 | class _DefaultPermissionsForm(formencode.Schema): | |
533 | allow_extra_fields = True |
|
533 | allow_extra_fields = True | |
534 | filter_extra_fields = True |
|
534 | filter_extra_fields = True | |
535 |
|
535 | |||
536 | anonymous = v.StringBoolean(if_missing=False) |
|
536 | anonymous = v.StringBoolean(if_missing=False) | |
537 |
|
537 | |||
538 | default_repo_create = v.OneOf(create_choices) |
|
538 | default_repo_create = v.OneOf(create_choices) | |
539 | default_repo_create_on_write = v.OneOf(create_on_write_choices) |
|
539 | default_repo_create_on_write = v.OneOf(create_on_write_choices) | |
540 | default_user_group_create = v.OneOf(user_group_create_choices) |
|
540 | default_user_group_create = v.OneOf(user_group_create_choices) | |
541 | default_repo_group_create = v.OneOf(repo_group_create_choices) |
|
541 | default_repo_group_create = v.OneOf(repo_group_create_choices) | |
542 | default_fork_create = v.OneOf(fork_choices) |
|
542 | default_fork_create = v.OneOf(fork_choices) | |
543 | default_inherit_default_permissions = v.OneOf(inherit_default_permissions_choices) |
|
543 | default_inherit_default_permissions = v.OneOf(inherit_default_permissions_choices) | |
544 | return _DefaultPermissionsForm |
|
544 | return _DefaultPermissionsForm | |
545 |
|
545 | |||
546 |
|
546 | |||
547 | def UserIndividualPermissionsForm(localizer): |
|
547 | def UserIndividualPermissionsForm(localizer): | |
548 | _ = localizer |
|
548 | _ = localizer | |
549 |
|
549 | |||
550 | class _DefaultPermissionsForm(formencode.Schema): |
|
550 | class _DefaultPermissionsForm(formencode.Schema): | |
551 | allow_extra_fields = True |
|
551 | allow_extra_fields = True | |
552 | filter_extra_fields = True |
|
552 | filter_extra_fields = True | |
553 |
|
553 | |||
554 | inherit_default_permissions = v.StringBoolean(if_missing=False) |
|
554 | inherit_default_permissions = v.StringBoolean(if_missing=False) | |
555 | return _DefaultPermissionsForm |
|
555 | return _DefaultPermissionsForm | |
556 |
|
556 | |||
557 |
|
557 | |||
558 | def DefaultsForm(localizer, edit=False, old_data=None, supported_backends=BACKENDS.keys()): |
|
558 | def DefaultsForm(localizer, edit=False, old_data=None, supported_backends=BACKENDS.keys()): | |
559 | _ = localizer |
|
559 | _ = localizer | |
560 | old_data = old_data or {} |
|
560 | old_data = old_data or {} | |
561 |
|
561 | |||
562 | class _DefaultsForm(formencode.Schema): |
|
562 | class _DefaultsForm(formencode.Schema): | |
563 | allow_extra_fields = True |
|
563 | allow_extra_fields = True | |
564 | filter_extra_fields = True |
|
564 | filter_extra_fields = True | |
565 | default_repo_type = v.OneOf(supported_backends) |
|
565 | default_repo_type = v.OneOf(supported_backends) | |
566 | default_repo_private = v.StringBoolean(if_missing=False) |
|
566 | default_repo_private = v.StringBoolean(if_missing=False) | |
567 | default_repo_enable_statistics = v.StringBoolean(if_missing=False) |
|
567 | default_repo_enable_statistics = v.StringBoolean(if_missing=False) | |
568 | default_repo_enable_downloads = v.StringBoolean(if_missing=False) |
|
568 | default_repo_enable_downloads = v.StringBoolean(if_missing=False) | |
569 | default_repo_enable_locking = v.StringBoolean(if_missing=False) |
|
569 | default_repo_enable_locking = v.StringBoolean(if_missing=False) | |
570 | return _DefaultsForm |
|
570 | return _DefaultsForm | |
571 |
|
571 | |||
572 |
|
572 | |||
573 | def AuthSettingsForm(localizer): |
|
573 | def AuthSettingsForm(localizer): | |
574 | _ = localizer |
|
574 | _ = localizer | |
575 |
|
575 | |||
576 | class _AuthSettingsForm(formencode.Schema): |
|
576 | class _AuthSettingsForm(formencode.Schema): | |
577 | allow_extra_fields = True |
|
577 | allow_extra_fields = True | |
578 | filter_extra_fields = True |
|
578 | filter_extra_fields = True | |
579 | auth_plugins = All(v.ValidAuthPlugins(localizer), |
|
579 | auth_plugins = All(v.ValidAuthPlugins(localizer), | |
580 | v.UniqueListFromString(localizer)(not_empty=True)) |
|
580 | v.UniqueListFromString(localizer)(not_empty=True)) | |
581 | return _AuthSettingsForm |
|
581 | return _AuthSettingsForm | |
582 |
|
582 | |||
583 |
|
583 | |||
584 | def UserExtraEmailForm(localizer): |
|
584 | def UserExtraEmailForm(localizer): | |
585 | _ = localizer |
|
585 | _ = localizer | |
586 |
|
586 | |||
587 | class _UserExtraEmailForm(formencode.Schema): |
|
587 | class _UserExtraEmailForm(formencode.Schema): | |
588 | email = All(v.UniqSystemEmail(localizer), v.Email(not_empty=True)) |
|
588 | email = All(v.UniqSystemEmail(localizer), v.Email(not_empty=True)) | |
589 | return _UserExtraEmailForm |
|
589 | return _UserExtraEmailForm | |
590 |
|
590 | |||
591 |
|
591 | |||
592 | def UserExtraIpForm(localizer): |
|
592 | def UserExtraIpForm(localizer): | |
593 | _ = localizer |
|
593 | _ = localizer | |
594 |
|
594 | |||
595 | class _UserExtraIpForm(formencode.Schema): |
|
595 | class _UserExtraIpForm(formencode.Schema): | |
596 | ip = v.ValidIp(localizer)(not_empty=True) |
|
596 | ip = v.ValidIp(localizer)(not_empty=True) | |
597 | return _UserExtraIpForm |
|
597 | return _UserExtraIpForm | |
598 |
|
598 | |||
599 |
|
599 | |||
600 | def PullRequestForm(localizer, repo_id): |
|
600 | def PullRequestForm(localizer, repo_id): | |
601 | _ = localizer |
|
601 | _ = localizer | |
602 |
|
602 | |||
603 | class ReviewerForm(formencode.Schema): |
|
603 | class ReviewerForm(formencode.Schema): | |
604 | user_id = v.Int(not_empty=True) |
|
604 | user_id = v.Int(not_empty=True) | |
605 | reasons = All() |
|
605 | reasons = All() | |
606 | rules = All(v.UniqueList(localizer, convert=int)()) |
|
606 | rules = All(v.UniqueList(localizer, convert=int)()) | |
607 | mandatory = v.StringBoolean() |
|
607 | mandatory = v.StringBoolean() | |
608 |
|
608 | |||
609 | class _PullRequestForm(formencode.Schema): |
|
609 | class _PullRequestForm(formencode.Schema): | |
610 | allow_extra_fields = True |
|
610 | allow_extra_fields = True | |
611 | filter_extra_fields = True |
|
611 | filter_extra_fields = True | |
612 |
|
612 | |||
613 | common_ancestor = v.UnicodeString(strip=True, required=True) |
|
613 | common_ancestor = v.UnicodeString(strip=True, required=True) | |
614 | source_repo = v.UnicodeString(strip=True, required=True) |
|
614 | source_repo = v.UnicodeString(strip=True, required=True) | |
615 | source_ref = v.UnicodeString(strip=True, required=True) |
|
615 | source_ref = v.UnicodeString(strip=True, required=True) | |
616 | target_repo = v.UnicodeString(strip=True, required=True) |
|
616 | target_repo = v.UnicodeString(strip=True, required=True) | |
617 | target_ref = v.UnicodeString(strip=True, required=True) |
|
617 | target_ref = v.UnicodeString(strip=True, required=True) | |
618 | revisions = All(#v.NotReviewedRevisions(localizer, repo_id)(), |
|
618 | revisions = All(#v.NotReviewedRevisions(localizer, repo_id)(), | |
619 | v.UniqueList(localizer)(not_empty=True)) |
|
619 | v.UniqueList(localizer)(not_empty=True)) | |
620 | review_members = formencode.ForEach(ReviewerForm()) |
|
620 | review_members = formencode.ForEach(ReviewerForm()) | |
621 |
pullrequest_title = v.UnicodeString(strip=True, required=True, min= |
|
621 | pullrequest_title = v.UnicodeString(strip=True, required=True, min=1, max=255) | |
622 | pullrequest_desc = v.UnicodeString(strip=True, required=False) |
|
622 | pullrequest_desc = v.UnicodeString(strip=True, required=False) | |
623 | description_renderer = v.UnicodeString(strip=True, required=False) |
|
623 | description_renderer = v.UnicodeString(strip=True, required=False) | |
624 |
|
624 | |||
625 | return _PullRequestForm |
|
625 | return _PullRequestForm | |
626 |
|
626 | |||
627 |
|
627 | |||
628 | def IssueTrackerPatternsForm(localizer): |
|
628 | def IssueTrackerPatternsForm(localizer): | |
629 | _ = localizer |
|
629 | _ = localizer | |
630 |
|
630 | |||
631 | class _IssueTrackerPatternsForm(formencode.Schema): |
|
631 | class _IssueTrackerPatternsForm(formencode.Schema): | |
632 | allow_extra_fields = True |
|
632 | allow_extra_fields = True | |
633 | filter_extra_fields = False |
|
633 | filter_extra_fields = False | |
634 | chained_validators = [v.ValidPattern(localizer)] |
|
634 | chained_validators = [v.ValidPattern(localizer)] | |
635 | return _IssueTrackerPatternsForm |
|
635 | return _IssueTrackerPatternsForm |
@@ -1,777 +1,779 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2011-2019 RhodeCode GmbH |
|
3 | # Copyright (C) 2011-2019 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 |
|
21 | |||
22 | """ |
|
22 | """ | |
23 | repo group model for RhodeCode |
|
23 | repo group model for RhodeCode | |
24 | """ |
|
24 | """ | |
25 |
|
25 | |||
26 | import os |
|
26 | import os | |
27 | import datetime |
|
27 | import datetime | |
28 | import itertools |
|
28 | import itertools | |
29 | import logging |
|
29 | import logging | |
30 | import shutil |
|
30 | import shutil | |
31 | import traceback |
|
31 | import traceback | |
32 | import string |
|
32 | import string | |
33 |
|
33 | |||
34 | from zope.cachedescriptors.property import Lazy as LazyProperty |
|
34 | from zope.cachedescriptors.property import Lazy as LazyProperty | |
35 |
|
35 | |||
36 | from rhodecode import events |
|
36 | from rhodecode import events | |
37 | from rhodecode.model import BaseModel |
|
37 | from rhodecode.model import BaseModel | |
38 | from rhodecode.model.db import (_hash_key, |
|
38 | from rhodecode.model.db import (_hash_key, | |
39 | RepoGroup, UserRepoGroupToPerm, User, Permission, UserGroupRepoGroupToPerm, |
|
39 | RepoGroup, UserRepoGroupToPerm, User, Permission, UserGroupRepoGroupToPerm, | |
40 | UserGroup, Repository) |
|
40 | UserGroup, Repository) | |
41 | from rhodecode.model.settings import VcsSettingsModel, SettingsModel |
|
41 | from rhodecode.model.settings import VcsSettingsModel, SettingsModel | |
42 | from rhodecode.lib.caching_query import FromCache |
|
42 | from rhodecode.lib.caching_query import FromCache | |
43 | from rhodecode.lib.utils2 import action_logger_generic, datetime_to_time |
|
43 | from rhodecode.lib.utils2 import action_logger_generic, datetime_to_time | |
44 |
|
44 | |||
45 | log = logging.getLogger(__name__) |
|
45 | log = logging.getLogger(__name__) | |
46 |
|
46 | |||
47 |
|
47 | |||
48 | class RepoGroupModel(BaseModel): |
|
48 | class RepoGroupModel(BaseModel): | |
49 |
|
49 | |||
50 | cls = RepoGroup |
|
50 | cls = RepoGroup | |
51 | PERSONAL_GROUP_DESC = 'personal repo group of user `%(username)s`' |
|
51 | PERSONAL_GROUP_DESC = 'personal repo group of user `%(username)s`' | |
52 | PERSONAL_GROUP_PATTERN = '${username}' # default |
|
52 | PERSONAL_GROUP_PATTERN = '${username}' # default | |
53 |
|
53 | |||
54 | def _get_user_group(self, users_group): |
|
54 | def _get_user_group(self, users_group): | |
55 | return self._get_instance(UserGroup, users_group, |
|
55 | return self._get_instance(UserGroup, users_group, | |
56 | callback=UserGroup.get_by_group_name) |
|
56 | callback=UserGroup.get_by_group_name) | |
57 |
|
57 | |||
58 | def _get_repo_group(self, repo_group): |
|
58 | def _get_repo_group(self, repo_group): | |
59 | return self._get_instance(RepoGroup, repo_group, |
|
59 | return self._get_instance(RepoGroup, repo_group, | |
60 | callback=RepoGroup.get_by_group_name) |
|
60 | callback=RepoGroup.get_by_group_name) | |
61 |
|
61 | |||
62 | @LazyProperty |
|
62 | @LazyProperty | |
63 | def repos_path(self): |
|
63 | def repos_path(self): | |
64 | """ |
|
64 | """ | |
65 | Gets the repositories root path from database |
|
65 | Gets the repositories root path from database | |
66 | """ |
|
66 | """ | |
67 |
|
67 | |||
68 | settings_model = VcsSettingsModel(sa=self.sa) |
|
68 | settings_model = VcsSettingsModel(sa=self.sa) | |
69 | return settings_model.get_repos_location() |
|
69 | return settings_model.get_repos_location() | |
70 |
|
70 | |||
71 | def get_by_group_name(self, repo_group_name, cache=None): |
|
71 | def get_by_group_name(self, repo_group_name, cache=None): | |
72 | repo = self.sa.query(RepoGroup) \ |
|
72 | repo = self.sa.query(RepoGroup) \ | |
73 | .filter(RepoGroup.group_name == repo_group_name) |
|
73 | .filter(RepoGroup.group_name == repo_group_name) | |
74 |
|
74 | |||
75 | if cache: |
|
75 | if cache: | |
76 | name_key = _hash_key(repo_group_name) |
|
76 | name_key = _hash_key(repo_group_name) | |
77 | repo = repo.options( |
|
77 | repo = repo.options( | |
78 | FromCache("sql_cache_short", "get_repo_group_%s" % name_key)) |
|
78 | FromCache("sql_cache_short", "get_repo_group_%s" % name_key)) | |
79 | return repo.scalar() |
|
79 | return repo.scalar() | |
80 |
|
80 | |||
81 | def get_default_create_personal_repo_group(self): |
|
81 | def get_default_create_personal_repo_group(self): | |
82 | value = SettingsModel().get_setting_by_name( |
|
82 | value = SettingsModel().get_setting_by_name( | |
83 | 'create_personal_repo_group') |
|
83 | 'create_personal_repo_group') | |
84 | return value.app_settings_value if value else None or False |
|
84 | return value.app_settings_value if value else None or False | |
85 |
|
85 | |||
86 | def get_personal_group_name_pattern(self): |
|
86 | def get_personal_group_name_pattern(self): | |
87 | value = SettingsModel().get_setting_by_name( |
|
87 | value = SettingsModel().get_setting_by_name( | |
88 | 'personal_repo_group_pattern') |
|
88 | 'personal_repo_group_pattern') | |
89 | val = value.app_settings_value if value else None |
|
89 | val = value.app_settings_value if value else None | |
90 | group_template = val or self.PERSONAL_GROUP_PATTERN |
|
90 | group_template = val or self.PERSONAL_GROUP_PATTERN | |
91 |
|
91 | |||
92 | group_template = group_template.lstrip('/') |
|
92 | group_template = group_template.lstrip('/') | |
93 | return group_template |
|
93 | return group_template | |
94 |
|
94 | |||
95 | def get_personal_group_name(self, user): |
|
95 | def get_personal_group_name(self, user): | |
96 | template = self.get_personal_group_name_pattern() |
|
96 | template = self.get_personal_group_name_pattern() | |
97 | return string.Template(template).safe_substitute( |
|
97 | return string.Template(template).safe_substitute( | |
98 | username=user.username, |
|
98 | username=user.username, | |
99 | user_id=user.user_id, |
|
99 | user_id=user.user_id, | |
|
100 | first_name=user.first_name, | |||
|
101 | last_name=user.last_name, | |||
100 | ) |
|
102 | ) | |
101 |
|
103 | |||
102 | def create_personal_repo_group(self, user, commit_early=True): |
|
104 | def create_personal_repo_group(self, user, commit_early=True): | |
103 | desc = self.PERSONAL_GROUP_DESC % {'username': user.username} |
|
105 | desc = self.PERSONAL_GROUP_DESC % {'username': user.username} | |
104 | personal_repo_group_name = self.get_personal_group_name(user) |
|
106 | personal_repo_group_name = self.get_personal_group_name(user) | |
105 |
|
107 | |||
106 | # create a new one |
|
108 | # create a new one | |
107 | RepoGroupModel().create( |
|
109 | RepoGroupModel().create( | |
108 | group_name=personal_repo_group_name, |
|
110 | group_name=personal_repo_group_name, | |
109 | group_description=desc, |
|
111 | group_description=desc, | |
110 | owner=user.username, |
|
112 | owner=user.username, | |
111 | personal=True, |
|
113 | personal=True, | |
112 | commit_early=commit_early) |
|
114 | commit_early=commit_early) | |
113 |
|
115 | |||
114 | def _create_default_perms(self, new_group): |
|
116 | def _create_default_perms(self, new_group): | |
115 | # create default permission |
|
117 | # create default permission | |
116 | default_perm = 'group.read' |
|
118 | default_perm = 'group.read' | |
117 | def_user = User.get_default_user() |
|
119 | def_user = User.get_default_user() | |
118 | for p in def_user.user_perms: |
|
120 | for p in def_user.user_perms: | |
119 | if p.permission.permission_name.startswith('group.'): |
|
121 | if p.permission.permission_name.startswith('group.'): | |
120 | default_perm = p.permission.permission_name |
|
122 | default_perm = p.permission.permission_name | |
121 | break |
|
123 | break | |
122 |
|
124 | |||
123 | repo_group_to_perm = UserRepoGroupToPerm() |
|
125 | repo_group_to_perm = UserRepoGroupToPerm() | |
124 | repo_group_to_perm.permission = Permission.get_by_key(default_perm) |
|
126 | repo_group_to_perm.permission = Permission.get_by_key(default_perm) | |
125 |
|
127 | |||
126 | repo_group_to_perm.group = new_group |
|
128 | repo_group_to_perm.group = new_group | |
127 | repo_group_to_perm.user_id = def_user.user_id |
|
129 | repo_group_to_perm.user_id = def_user.user_id | |
128 | return repo_group_to_perm |
|
130 | return repo_group_to_perm | |
129 |
|
131 | |||
130 | def _get_group_name_and_parent(self, group_name_full, repo_in_path=False, |
|
132 | def _get_group_name_and_parent(self, group_name_full, repo_in_path=False, | |
131 | get_object=False): |
|
133 | get_object=False): | |
132 | """ |
|
134 | """ | |
133 | Get's the group name and a parent group name from given group name. |
|
135 | Get's the group name and a parent group name from given group name. | |
134 | If repo_in_path is set to truth, we asume the full path also includes |
|
136 | If repo_in_path is set to truth, we asume the full path also includes | |
135 | repo name, in such case we clean the last element. |
|
137 | repo name, in such case we clean the last element. | |
136 |
|
138 | |||
137 | :param group_name_full: |
|
139 | :param group_name_full: | |
138 | """ |
|
140 | """ | |
139 | split_paths = 1 |
|
141 | split_paths = 1 | |
140 | if repo_in_path: |
|
142 | if repo_in_path: | |
141 | split_paths = 2 |
|
143 | split_paths = 2 | |
142 | _parts = group_name_full.rsplit(RepoGroup.url_sep(), split_paths) |
|
144 | _parts = group_name_full.rsplit(RepoGroup.url_sep(), split_paths) | |
143 |
|
145 | |||
144 | if repo_in_path and len(_parts) > 1: |
|
146 | if repo_in_path and len(_parts) > 1: | |
145 | # such case last element is the repo_name |
|
147 | # such case last element is the repo_name | |
146 | _parts.pop(-1) |
|
148 | _parts.pop(-1) | |
147 | group_name_cleaned = _parts[-1] # just the group name |
|
149 | group_name_cleaned = _parts[-1] # just the group name | |
148 | parent_repo_group_name = None |
|
150 | parent_repo_group_name = None | |
149 |
|
151 | |||
150 | if len(_parts) > 1: |
|
152 | if len(_parts) > 1: | |
151 | parent_repo_group_name = _parts[0] |
|
153 | parent_repo_group_name = _parts[0] | |
152 |
|
154 | |||
153 | parent_group = None |
|
155 | parent_group = None | |
154 | if parent_repo_group_name: |
|
156 | if parent_repo_group_name: | |
155 | parent_group = RepoGroup.get_by_group_name(parent_repo_group_name) |
|
157 | parent_group = RepoGroup.get_by_group_name(parent_repo_group_name) | |
156 |
|
158 | |||
157 | if get_object: |
|
159 | if get_object: | |
158 | return group_name_cleaned, parent_repo_group_name, parent_group |
|
160 | return group_name_cleaned, parent_repo_group_name, parent_group | |
159 |
|
161 | |||
160 | return group_name_cleaned, parent_repo_group_name |
|
162 | return group_name_cleaned, parent_repo_group_name | |
161 |
|
163 | |||
162 | def check_exist_filesystem(self, group_name, exc_on_failure=True): |
|
164 | def check_exist_filesystem(self, group_name, exc_on_failure=True): | |
163 | create_path = os.path.join(self.repos_path, group_name) |
|
165 | create_path = os.path.join(self.repos_path, group_name) | |
164 | log.debug('creating new group in %s', create_path) |
|
166 | log.debug('creating new group in %s', create_path) | |
165 |
|
167 | |||
166 | if os.path.isdir(create_path): |
|
168 | if os.path.isdir(create_path): | |
167 | if exc_on_failure: |
|
169 | if exc_on_failure: | |
168 | abs_create_path = os.path.abspath(create_path) |
|
170 | abs_create_path = os.path.abspath(create_path) | |
169 | raise Exception('Directory `{}` already exists !'.format(abs_create_path)) |
|
171 | raise Exception('Directory `{}` already exists !'.format(abs_create_path)) | |
170 | return False |
|
172 | return False | |
171 | return True |
|
173 | return True | |
172 |
|
174 | |||
173 | def _create_group(self, group_name): |
|
175 | def _create_group(self, group_name): | |
174 | """ |
|
176 | """ | |
175 | makes repository group on filesystem |
|
177 | makes repository group on filesystem | |
176 |
|
178 | |||
177 | :param repo_name: |
|
179 | :param repo_name: | |
178 | :param parent_id: |
|
180 | :param parent_id: | |
179 | """ |
|
181 | """ | |
180 |
|
182 | |||
181 | self.check_exist_filesystem(group_name) |
|
183 | self.check_exist_filesystem(group_name) | |
182 | create_path = os.path.join(self.repos_path, group_name) |
|
184 | create_path = os.path.join(self.repos_path, group_name) | |
183 | log.debug('creating new group in %s', create_path) |
|
185 | log.debug('creating new group in %s', create_path) | |
184 | os.makedirs(create_path, mode=0o755) |
|
186 | os.makedirs(create_path, mode=0o755) | |
185 | log.debug('created group in %s', create_path) |
|
187 | log.debug('created group in %s', create_path) | |
186 |
|
188 | |||
187 | def _rename_group(self, old, new): |
|
189 | def _rename_group(self, old, new): | |
188 | """ |
|
190 | """ | |
189 | Renames a group on filesystem |
|
191 | Renames a group on filesystem | |
190 |
|
192 | |||
191 | :param group_name: |
|
193 | :param group_name: | |
192 | """ |
|
194 | """ | |
193 |
|
195 | |||
194 | if old == new: |
|
196 | if old == new: | |
195 | log.debug('skipping group rename') |
|
197 | log.debug('skipping group rename') | |
196 | return |
|
198 | return | |
197 |
|
199 | |||
198 | log.debug('renaming repository group from %s to %s', old, new) |
|
200 | log.debug('renaming repository group from %s to %s', old, new) | |
199 |
|
201 | |||
200 | old_path = os.path.join(self.repos_path, old) |
|
202 | old_path = os.path.join(self.repos_path, old) | |
201 | new_path = os.path.join(self.repos_path, new) |
|
203 | new_path = os.path.join(self.repos_path, new) | |
202 |
|
204 | |||
203 | log.debug('renaming repos paths from %s to %s', old_path, new_path) |
|
205 | log.debug('renaming repos paths from %s to %s', old_path, new_path) | |
204 |
|
206 | |||
205 | if os.path.isdir(new_path): |
|
207 | if os.path.isdir(new_path): | |
206 | raise Exception('Was trying to rename to already ' |
|
208 | raise Exception('Was trying to rename to already ' | |
207 | 'existing dir %s' % new_path) |
|
209 | 'existing dir %s' % new_path) | |
208 | shutil.move(old_path, new_path) |
|
210 | shutil.move(old_path, new_path) | |
209 |
|
211 | |||
210 | def _delete_filesystem_group(self, group, force_delete=False): |
|
212 | def _delete_filesystem_group(self, group, force_delete=False): | |
211 | """ |
|
213 | """ | |
212 | Deletes a group from a filesystem |
|
214 | Deletes a group from a filesystem | |
213 |
|
215 | |||
214 | :param group: instance of group from database |
|
216 | :param group: instance of group from database | |
215 | :param force_delete: use shutil rmtree to remove all objects |
|
217 | :param force_delete: use shutil rmtree to remove all objects | |
216 | """ |
|
218 | """ | |
217 | paths = group.full_path.split(RepoGroup.url_sep()) |
|
219 | paths = group.full_path.split(RepoGroup.url_sep()) | |
218 | paths = os.sep.join(paths) |
|
220 | paths = os.sep.join(paths) | |
219 |
|
221 | |||
220 | rm_path = os.path.join(self.repos_path, paths) |
|
222 | rm_path = os.path.join(self.repos_path, paths) | |
221 | log.info("Removing group %s", rm_path) |
|
223 | log.info("Removing group %s", rm_path) | |
222 | # delete only if that path really exists |
|
224 | # delete only if that path really exists | |
223 | if os.path.isdir(rm_path): |
|
225 | if os.path.isdir(rm_path): | |
224 | if force_delete: |
|
226 | if force_delete: | |
225 | shutil.rmtree(rm_path) |
|
227 | shutil.rmtree(rm_path) | |
226 | else: |
|
228 | else: | |
227 | # archive that group` |
|
229 | # archive that group` | |
228 | _now = datetime.datetime.now() |
|
230 | _now = datetime.datetime.now() | |
229 | _ms = str(_now.microsecond).rjust(6, '0') |
|
231 | _ms = str(_now.microsecond).rjust(6, '0') | |
230 | _d = 'rm__%s_GROUP_%s' % ( |
|
232 | _d = 'rm__%s_GROUP_%s' % ( | |
231 | _now.strftime('%Y%m%d_%H%M%S_' + _ms), group.name) |
|
233 | _now.strftime('%Y%m%d_%H%M%S_' + _ms), group.name) | |
232 | shutil.move(rm_path, os.path.join(self.repos_path, _d)) |
|
234 | shutil.move(rm_path, os.path.join(self.repos_path, _d)) | |
233 |
|
235 | |||
234 | def create(self, group_name, group_description, owner, just_db=False, |
|
236 | def create(self, group_name, group_description, owner, just_db=False, | |
235 | copy_permissions=False, personal=None, commit_early=True): |
|
237 | copy_permissions=False, personal=None, commit_early=True): | |
236 |
|
238 | |||
237 | (group_name_cleaned, |
|
239 | (group_name_cleaned, | |
238 | parent_group_name) = RepoGroupModel()._get_group_name_and_parent(group_name) |
|
240 | parent_group_name) = RepoGroupModel()._get_group_name_and_parent(group_name) | |
239 |
|
241 | |||
240 | parent_group = None |
|
242 | parent_group = None | |
241 | if parent_group_name: |
|
243 | if parent_group_name: | |
242 | parent_group = self._get_repo_group(parent_group_name) |
|
244 | parent_group = self._get_repo_group(parent_group_name) | |
243 | if not parent_group: |
|
245 | if not parent_group: | |
244 | # we tried to create a nested group, but the parent is not |
|
246 | # we tried to create a nested group, but the parent is not | |
245 | # existing |
|
247 | # existing | |
246 | raise ValueError( |
|
248 | raise ValueError( | |
247 | 'Parent group `%s` given in `%s` group name ' |
|
249 | 'Parent group `%s` given in `%s` group name ' | |
248 | 'is not yet existing.' % (parent_group_name, group_name)) |
|
250 | 'is not yet existing.' % (parent_group_name, group_name)) | |
249 |
|
251 | |||
250 | # because we are doing a cleanup, we need to check if such directory |
|
252 | # because we are doing a cleanup, we need to check if such directory | |
251 | # already exists. If we don't do that we can accidentally delete |
|
253 | # already exists. If we don't do that we can accidentally delete | |
252 | # existing directory via cleanup that can cause data issues, since |
|
254 | # existing directory via cleanup that can cause data issues, since | |
253 | # delete does a folder rename to special syntax later cleanup |
|
255 | # delete does a folder rename to special syntax later cleanup | |
254 | # functions can delete this |
|
256 | # functions can delete this | |
255 | cleanup_group = self.check_exist_filesystem(group_name, |
|
257 | cleanup_group = self.check_exist_filesystem(group_name, | |
256 | exc_on_failure=False) |
|
258 | exc_on_failure=False) | |
257 | user = self._get_user(owner) |
|
259 | user = self._get_user(owner) | |
258 | if not user: |
|
260 | if not user: | |
259 | raise ValueError('Owner %s not found as rhodecode user', owner) |
|
261 | raise ValueError('Owner %s not found as rhodecode user', owner) | |
260 |
|
262 | |||
261 | try: |
|
263 | try: | |
262 | new_repo_group = RepoGroup() |
|
264 | new_repo_group = RepoGroup() | |
263 | new_repo_group.user = user |
|
265 | new_repo_group.user = user | |
264 | new_repo_group.group_description = group_description or group_name |
|
266 | new_repo_group.group_description = group_description or group_name | |
265 | new_repo_group.parent_group = parent_group |
|
267 | new_repo_group.parent_group = parent_group | |
266 | new_repo_group.group_name = group_name |
|
268 | new_repo_group.group_name = group_name | |
267 | new_repo_group.personal = personal |
|
269 | new_repo_group.personal = personal | |
268 |
|
270 | |||
269 | self.sa.add(new_repo_group) |
|
271 | self.sa.add(new_repo_group) | |
270 |
|
272 | |||
271 | # create an ADMIN permission for owner except if we're super admin, |
|
273 | # create an ADMIN permission for owner except if we're super admin, | |
272 | # later owner should go into the owner field of groups |
|
274 | # later owner should go into the owner field of groups | |
273 | if not user.is_admin: |
|
275 | if not user.is_admin: | |
274 | self.grant_user_permission(repo_group=new_repo_group, |
|
276 | self.grant_user_permission(repo_group=new_repo_group, | |
275 | user=owner, perm='group.admin') |
|
277 | user=owner, perm='group.admin') | |
276 |
|
278 | |||
277 | if parent_group and copy_permissions: |
|
279 | if parent_group and copy_permissions: | |
278 | # copy permissions from parent |
|
280 | # copy permissions from parent | |
279 | user_perms = UserRepoGroupToPerm.query() \ |
|
281 | user_perms = UserRepoGroupToPerm.query() \ | |
280 | .filter(UserRepoGroupToPerm.group == parent_group).all() |
|
282 | .filter(UserRepoGroupToPerm.group == parent_group).all() | |
281 |
|
283 | |||
282 | group_perms = UserGroupRepoGroupToPerm.query() \ |
|
284 | group_perms = UserGroupRepoGroupToPerm.query() \ | |
283 | .filter(UserGroupRepoGroupToPerm.group == parent_group).all() |
|
285 | .filter(UserGroupRepoGroupToPerm.group == parent_group).all() | |
284 |
|
286 | |||
285 | for perm in user_perms: |
|
287 | for perm in user_perms: | |
286 | # don't copy over the permission for user who is creating |
|
288 | # don't copy over the permission for user who is creating | |
287 | # this group, if he is not super admin he get's admin |
|
289 | # this group, if he is not super admin he get's admin | |
288 | # permission set above |
|
290 | # permission set above | |
289 | if perm.user != user or user.is_admin: |
|
291 | if perm.user != user or user.is_admin: | |
290 | UserRepoGroupToPerm.create( |
|
292 | UserRepoGroupToPerm.create( | |
291 | perm.user, new_repo_group, perm.permission) |
|
293 | perm.user, new_repo_group, perm.permission) | |
292 |
|
294 | |||
293 | for perm in group_perms: |
|
295 | for perm in group_perms: | |
294 | UserGroupRepoGroupToPerm.create( |
|
296 | UserGroupRepoGroupToPerm.create( | |
295 | perm.users_group, new_repo_group, perm.permission) |
|
297 | perm.users_group, new_repo_group, perm.permission) | |
296 | else: |
|
298 | else: | |
297 | perm_obj = self._create_default_perms(new_repo_group) |
|
299 | perm_obj = self._create_default_perms(new_repo_group) | |
298 | self.sa.add(perm_obj) |
|
300 | self.sa.add(perm_obj) | |
299 |
|
301 | |||
300 | # now commit the changes, earlier so we are sure everything is in |
|
302 | # now commit the changes, earlier so we are sure everything is in | |
301 | # the database. |
|
303 | # the database. | |
302 | if commit_early: |
|
304 | if commit_early: | |
303 | self.sa.commit() |
|
305 | self.sa.commit() | |
304 | if not just_db: |
|
306 | if not just_db: | |
305 | self._create_group(new_repo_group.group_name) |
|
307 | self._create_group(new_repo_group.group_name) | |
306 |
|
308 | |||
307 | # trigger the post hook |
|
309 | # trigger the post hook | |
308 | from rhodecode.lib.hooks_base import log_create_repository_group |
|
310 | from rhodecode.lib.hooks_base import log_create_repository_group | |
309 | repo_group = RepoGroup.get_by_group_name(group_name) |
|
311 | repo_group = RepoGroup.get_by_group_name(group_name) | |
310 | log_create_repository_group( |
|
312 | log_create_repository_group( | |
311 | created_by=user.username, **repo_group.get_dict()) |
|
313 | created_by=user.username, **repo_group.get_dict()) | |
312 |
|
314 | |||
313 | # Trigger create event. |
|
315 | # Trigger create event. | |
314 | events.trigger(events.RepoGroupCreateEvent(repo_group)) |
|
316 | events.trigger(events.RepoGroupCreateEvent(repo_group)) | |
315 |
|
317 | |||
316 | return new_repo_group |
|
318 | return new_repo_group | |
317 | except Exception: |
|
319 | except Exception: | |
318 | self.sa.rollback() |
|
320 | self.sa.rollback() | |
319 | log.exception('Exception occurred when creating repository group, ' |
|
321 | log.exception('Exception occurred when creating repository group, ' | |
320 | 'doing cleanup...') |
|
322 | 'doing cleanup...') | |
321 | # rollback things manually ! |
|
323 | # rollback things manually ! | |
322 | repo_group = RepoGroup.get_by_group_name(group_name) |
|
324 | repo_group = RepoGroup.get_by_group_name(group_name) | |
323 | if repo_group: |
|
325 | if repo_group: | |
324 | RepoGroup.delete(repo_group.group_id) |
|
326 | RepoGroup.delete(repo_group.group_id) | |
325 | self.sa.commit() |
|
327 | self.sa.commit() | |
326 | if cleanup_group: |
|
328 | if cleanup_group: | |
327 | RepoGroupModel()._delete_filesystem_group(repo_group) |
|
329 | RepoGroupModel()._delete_filesystem_group(repo_group) | |
328 | raise |
|
330 | raise | |
329 |
|
331 | |||
330 | def update_permissions( |
|
332 | def update_permissions( | |
331 | self, repo_group, perm_additions=None, perm_updates=None, |
|
333 | self, repo_group, perm_additions=None, perm_updates=None, | |
332 | perm_deletions=None, recursive=None, check_perms=True, |
|
334 | perm_deletions=None, recursive=None, check_perms=True, | |
333 | cur_user=None): |
|
335 | cur_user=None): | |
334 | from rhodecode.model.repo import RepoModel |
|
336 | from rhodecode.model.repo import RepoModel | |
335 | from rhodecode.lib.auth import HasUserGroupPermissionAny |
|
337 | from rhodecode.lib.auth import HasUserGroupPermissionAny | |
336 |
|
338 | |||
337 | if not perm_additions: |
|
339 | if not perm_additions: | |
338 | perm_additions = [] |
|
340 | perm_additions = [] | |
339 | if not perm_updates: |
|
341 | if not perm_updates: | |
340 | perm_updates = [] |
|
342 | perm_updates = [] | |
341 | if not perm_deletions: |
|
343 | if not perm_deletions: | |
342 | perm_deletions = [] |
|
344 | perm_deletions = [] | |
343 |
|
345 | |||
344 | req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin') |
|
346 | req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin') | |
345 |
|
347 | |||
346 | changes = { |
|
348 | changes = { | |
347 | 'added': [], |
|
349 | 'added': [], | |
348 | 'updated': [], |
|
350 | 'updated': [], | |
349 | 'deleted': [] |
|
351 | 'deleted': [] | |
350 | } |
|
352 | } | |
351 |
|
353 | |||
352 | def _set_perm_user(obj, user, perm): |
|
354 | def _set_perm_user(obj, user, perm): | |
353 | if isinstance(obj, RepoGroup): |
|
355 | if isinstance(obj, RepoGroup): | |
354 | self.grant_user_permission( |
|
356 | self.grant_user_permission( | |
355 | repo_group=obj, user=user, perm=perm) |
|
357 | repo_group=obj, user=user, perm=perm) | |
356 | elif isinstance(obj, Repository): |
|
358 | elif isinstance(obj, Repository): | |
357 | # private repos will not allow to change the default |
|
359 | # private repos will not allow to change the default | |
358 | # permissions using recursive mode |
|
360 | # permissions using recursive mode | |
359 | if obj.private and user == User.DEFAULT_USER: |
|
361 | if obj.private and user == User.DEFAULT_USER: | |
360 | return |
|
362 | return | |
361 |
|
363 | |||
362 | # we set group permission but we have to switch to repo |
|
364 | # we set group permission but we have to switch to repo | |
363 | # permission |
|
365 | # permission | |
364 | perm = perm.replace('group.', 'repository.') |
|
366 | perm = perm.replace('group.', 'repository.') | |
365 | RepoModel().grant_user_permission( |
|
367 | RepoModel().grant_user_permission( | |
366 | repo=obj, user=user, perm=perm) |
|
368 | repo=obj, user=user, perm=perm) | |
367 |
|
369 | |||
368 | def _set_perm_group(obj, users_group, perm): |
|
370 | def _set_perm_group(obj, users_group, perm): | |
369 | if isinstance(obj, RepoGroup): |
|
371 | if isinstance(obj, RepoGroup): | |
370 | self.grant_user_group_permission( |
|
372 | self.grant_user_group_permission( | |
371 | repo_group=obj, group_name=users_group, perm=perm) |
|
373 | repo_group=obj, group_name=users_group, perm=perm) | |
372 | elif isinstance(obj, Repository): |
|
374 | elif isinstance(obj, Repository): | |
373 | # we set group permission but we have to switch to repo |
|
375 | # we set group permission but we have to switch to repo | |
374 | # permission |
|
376 | # permission | |
375 | perm = perm.replace('group.', 'repository.') |
|
377 | perm = perm.replace('group.', 'repository.') | |
376 | RepoModel().grant_user_group_permission( |
|
378 | RepoModel().grant_user_group_permission( | |
377 | repo=obj, group_name=users_group, perm=perm) |
|
379 | repo=obj, group_name=users_group, perm=perm) | |
378 |
|
380 | |||
379 | def _revoke_perm_user(obj, user): |
|
381 | def _revoke_perm_user(obj, user): | |
380 | if isinstance(obj, RepoGroup): |
|
382 | if isinstance(obj, RepoGroup): | |
381 | self.revoke_user_permission(repo_group=obj, user=user) |
|
383 | self.revoke_user_permission(repo_group=obj, user=user) | |
382 | elif isinstance(obj, Repository): |
|
384 | elif isinstance(obj, Repository): | |
383 | RepoModel().revoke_user_permission(repo=obj, user=user) |
|
385 | RepoModel().revoke_user_permission(repo=obj, user=user) | |
384 |
|
386 | |||
385 | def _revoke_perm_group(obj, user_group): |
|
387 | def _revoke_perm_group(obj, user_group): | |
386 | if isinstance(obj, RepoGroup): |
|
388 | if isinstance(obj, RepoGroup): | |
387 | self.revoke_user_group_permission( |
|
389 | self.revoke_user_group_permission( | |
388 | repo_group=obj, group_name=user_group) |
|
390 | repo_group=obj, group_name=user_group) | |
389 | elif isinstance(obj, Repository): |
|
391 | elif isinstance(obj, Repository): | |
390 | RepoModel().revoke_user_group_permission( |
|
392 | RepoModel().revoke_user_group_permission( | |
391 | repo=obj, group_name=user_group) |
|
393 | repo=obj, group_name=user_group) | |
392 |
|
394 | |||
393 | # start updates |
|
395 | # start updates | |
394 | log.debug('Now updating permissions for %s in recursive mode:%s', |
|
396 | log.debug('Now updating permissions for %s in recursive mode:%s', | |
395 | repo_group, recursive) |
|
397 | repo_group, recursive) | |
396 |
|
398 | |||
397 | # initialize check function, we'll call that multiple times |
|
399 | # initialize check function, we'll call that multiple times | |
398 | has_group_perm = HasUserGroupPermissionAny(*req_perms) |
|
400 | has_group_perm = HasUserGroupPermissionAny(*req_perms) | |
399 |
|
401 | |||
400 | for obj in repo_group.recursive_groups_and_repos(): |
|
402 | for obj in repo_group.recursive_groups_and_repos(): | |
401 | # iterated obj is an instance of a repos group or repository in |
|
403 | # iterated obj is an instance of a repos group or repository in | |
402 | # that group, recursive option can be: none, repos, groups, all |
|
404 | # that group, recursive option can be: none, repos, groups, all | |
403 | if recursive == 'all': |
|
405 | if recursive == 'all': | |
404 | obj = obj |
|
406 | obj = obj | |
405 | elif recursive == 'repos': |
|
407 | elif recursive == 'repos': | |
406 | # skip groups, other than this one |
|
408 | # skip groups, other than this one | |
407 | if isinstance(obj, RepoGroup) and not obj == repo_group: |
|
409 | if isinstance(obj, RepoGroup) and not obj == repo_group: | |
408 | continue |
|
410 | continue | |
409 | elif recursive == 'groups': |
|
411 | elif recursive == 'groups': | |
410 | # skip repos |
|
412 | # skip repos | |
411 | if isinstance(obj, Repository): |
|
413 | if isinstance(obj, Repository): | |
412 | continue |
|
414 | continue | |
413 | else: # recursive == 'none': |
|
415 | else: # recursive == 'none': | |
414 | # DEFAULT option - don't apply to iterated objects |
|
416 | # DEFAULT option - don't apply to iterated objects | |
415 | # also we do a break at the end of this loop. if we are not |
|
417 | # also we do a break at the end of this loop. if we are not | |
416 | # in recursive mode |
|
418 | # in recursive mode | |
417 | obj = repo_group |
|
419 | obj = repo_group | |
418 |
|
420 | |||
419 | change_obj = obj.get_api_data() |
|
421 | change_obj = obj.get_api_data() | |
420 |
|
422 | |||
421 | # update permissions |
|
423 | # update permissions | |
422 | for member_id, perm, member_type in perm_updates: |
|
424 | for member_id, perm, member_type in perm_updates: | |
423 | member_id = int(member_id) |
|
425 | member_id = int(member_id) | |
424 | if member_type == 'user': |
|
426 | if member_type == 'user': | |
425 | member_name = User.get(member_id).username |
|
427 | member_name = User.get(member_id).username | |
426 | # this updates also current one if found |
|
428 | # this updates also current one if found | |
427 | _set_perm_user(obj, user=member_id, perm=perm) |
|
429 | _set_perm_user(obj, user=member_id, perm=perm) | |
428 | elif member_type == 'user_group': |
|
430 | elif member_type == 'user_group': | |
429 | member_name = UserGroup.get(member_id).users_group_name |
|
431 | member_name = UserGroup.get(member_id).users_group_name | |
430 | if not check_perms or has_group_perm(member_name, |
|
432 | if not check_perms or has_group_perm(member_name, | |
431 | user=cur_user): |
|
433 | user=cur_user): | |
432 | _set_perm_group(obj, users_group=member_id, perm=perm) |
|
434 | _set_perm_group(obj, users_group=member_id, perm=perm) | |
433 | else: |
|
435 | else: | |
434 | raise ValueError("member_type must be 'user' or 'user_group' " |
|
436 | raise ValueError("member_type must be 'user' or 'user_group' " | |
435 | "got {} instead".format(member_type)) |
|
437 | "got {} instead".format(member_type)) | |
436 |
|
438 | |||
437 | changes['updated'].append( |
|
439 | changes['updated'].append( | |
438 | {'change_obj': change_obj, 'type': member_type, |
|
440 | {'change_obj': change_obj, 'type': member_type, | |
439 | 'id': member_id, 'name': member_name, 'new_perm': perm}) |
|
441 | 'id': member_id, 'name': member_name, 'new_perm': perm}) | |
440 |
|
442 | |||
441 | # set new permissions |
|
443 | # set new permissions | |
442 | for member_id, perm, member_type in perm_additions: |
|
444 | for member_id, perm, member_type in perm_additions: | |
443 | member_id = int(member_id) |
|
445 | member_id = int(member_id) | |
444 | if member_type == 'user': |
|
446 | if member_type == 'user': | |
445 | member_name = User.get(member_id).username |
|
447 | member_name = User.get(member_id).username | |
446 | _set_perm_user(obj, user=member_id, perm=perm) |
|
448 | _set_perm_user(obj, user=member_id, perm=perm) | |
447 | elif member_type == 'user_group': |
|
449 | elif member_type == 'user_group': | |
448 | # check if we have permissions to alter this usergroup |
|
450 | # check if we have permissions to alter this usergroup | |
449 | member_name = UserGroup.get(member_id).users_group_name |
|
451 | member_name = UserGroup.get(member_id).users_group_name | |
450 | if not check_perms or has_group_perm(member_name, |
|
452 | if not check_perms or has_group_perm(member_name, | |
451 | user=cur_user): |
|
453 | user=cur_user): | |
452 | _set_perm_group(obj, users_group=member_id, perm=perm) |
|
454 | _set_perm_group(obj, users_group=member_id, perm=perm) | |
453 | else: |
|
455 | else: | |
454 | raise ValueError("member_type must be 'user' or 'user_group' " |
|
456 | raise ValueError("member_type must be 'user' or 'user_group' " | |
455 | "got {} instead".format(member_type)) |
|
457 | "got {} instead".format(member_type)) | |
456 |
|
458 | |||
457 | changes['added'].append( |
|
459 | changes['added'].append( | |
458 | {'change_obj': change_obj, 'type': member_type, |
|
460 | {'change_obj': change_obj, 'type': member_type, | |
459 | 'id': member_id, 'name': member_name, 'new_perm': perm}) |
|
461 | 'id': member_id, 'name': member_name, 'new_perm': perm}) | |
460 |
|
462 | |||
461 | # delete permissions |
|
463 | # delete permissions | |
462 | for member_id, perm, member_type in perm_deletions: |
|
464 | for member_id, perm, member_type in perm_deletions: | |
463 | member_id = int(member_id) |
|
465 | member_id = int(member_id) | |
464 | if member_type == 'user': |
|
466 | if member_type == 'user': | |
465 | member_name = User.get(member_id).username |
|
467 | member_name = User.get(member_id).username | |
466 | _revoke_perm_user(obj, user=member_id) |
|
468 | _revoke_perm_user(obj, user=member_id) | |
467 | elif member_type == 'user_group': |
|
469 | elif member_type == 'user_group': | |
468 | # check if we have permissions to alter this usergroup |
|
470 | # check if we have permissions to alter this usergroup | |
469 | member_name = UserGroup.get(member_id).users_group_name |
|
471 | member_name = UserGroup.get(member_id).users_group_name | |
470 | if not check_perms or has_group_perm(member_name, |
|
472 | if not check_perms or has_group_perm(member_name, | |
471 | user=cur_user): |
|
473 | user=cur_user): | |
472 | _revoke_perm_group(obj, user_group=member_id) |
|
474 | _revoke_perm_group(obj, user_group=member_id) | |
473 | else: |
|
475 | else: | |
474 | raise ValueError("member_type must be 'user' or 'user_group' " |
|
476 | raise ValueError("member_type must be 'user' or 'user_group' " | |
475 | "got {} instead".format(member_type)) |
|
477 | "got {} instead".format(member_type)) | |
476 |
|
478 | |||
477 | changes['deleted'].append( |
|
479 | changes['deleted'].append( | |
478 | {'change_obj': change_obj, 'type': member_type, |
|
480 | {'change_obj': change_obj, 'type': member_type, | |
479 | 'id': member_id, 'name': member_name, 'new_perm': perm}) |
|
481 | 'id': member_id, 'name': member_name, 'new_perm': perm}) | |
480 |
|
482 | |||
481 | # if it's not recursive call for all,repos,groups |
|
483 | # if it's not recursive call for all,repos,groups | |
482 | # break the loop and don't proceed with other changes |
|
484 | # break the loop and don't proceed with other changes | |
483 | if recursive not in ['all', 'repos', 'groups']: |
|
485 | if recursive not in ['all', 'repos', 'groups']: | |
484 | break |
|
486 | break | |
485 |
|
487 | |||
486 | return changes |
|
488 | return changes | |
487 |
|
489 | |||
488 | def update(self, repo_group, form_data): |
|
490 | def update(self, repo_group, form_data): | |
489 | try: |
|
491 | try: | |
490 | repo_group = self._get_repo_group(repo_group) |
|
492 | repo_group = self._get_repo_group(repo_group) | |
491 | old_path = repo_group.full_path |
|
493 | old_path = repo_group.full_path | |
492 |
|
494 | |||
493 | # change properties |
|
495 | # change properties | |
494 | if 'group_description' in form_data: |
|
496 | if 'group_description' in form_data: | |
495 | repo_group.group_description = form_data['group_description'] |
|
497 | repo_group.group_description = form_data['group_description'] | |
496 |
|
498 | |||
497 | if 'enable_locking' in form_data: |
|
499 | if 'enable_locking' in form_data: | |
498 | repo_group.enable_locking = form_data['enable_locking'] |
|
500 | repo_group.enable_locking = form_data['enable_locking'] | |
499 |
|
501 | |||
500 | if 'group_parent_id' in form_data: |
|
502 | if 'group_parent_id' in form_data: | |
501 | parent_group = ( |
|
503 | parent_group = ( | |
502 | self._get_repo_group(form_data['group_parent_id'])) |
|
504 | self._get_repo_group(form_data['group_parent_id'])) | |
503 | repo_group.group_parent_id = ( |
|
505 | repo_group.group_parent_id = ( | |
504 | parent_group.group_id if parent_group else None) |
|
506 | parent_group.group_id if parent_group else None) | |
505 | repo_group.parent_group = parent_group |
|
507 | repo_group.parent_group = parent_group | |
506 |
|
508 | |||
507 | # mikhail: to update the full_path, we have to explicitly |
|
509 | # mikhail: to update the full_path, we have to explicitly | |
508 | # update group_name |
|
510 | # update group_name | |
509 | group_name = form_data.get('group_name', repo_group.name) |
|
511 | group_name = form_data.get('group_name', repo_group.name) | |
510 | repo_group.group_name = repo_group.get_new_name(group_name) |
|
512 | repo_group.group_name = repo_group.get_new_name(group_name) | |
511 |
|
513 | |||
512 | new_path = repo_group.full_path |
|
514 | new_path = repo_group.full_path | |
513 |
|
515 | |||
514 | if 'user' in form_data: |
|
516 | if 'user' in form_data: | |
515 | repo_group.user = User.get_by_username(form_data['user']) |
|
517 | repo_group.user = User.get_by_username(form_data['user']) | |
516 | repo_group.updated_on = datetime.datetime.now() |
|
518 | repo_group.updated_on = datetime.datetime.now() | |
517 | self.sa.add(repo_group) |
|
519 | self.sa.add(repo_group) | |
518 |
|
520 | |||
519 | # iterate over all members of this groups and do fixes |
|
521 | # iterate over all members of this groups and do fixes | |
520 | # set locking if given |
|
522 | # set locking if given | |
521 | # if obj is a repoGroup also fix the name of the group according |
|
523 | # if obj is a repoGroup also fix the name of the group according | |
522 | # to the parent |
|
524 | # to the parent | |
523 | # if obj is a Repo fix it's name |
|
525 | # if obj is a Repo fix it's name | |
524 | # this can be potentially heavy operation |
|
526 | # this can be potentially heavy operation | |
525 | for obj in repo_group.recursive_groups_and_repos(): |
|
527 | for obj in repo_group.recursive_groups_and_repos(): | |
526 | # set the value from it's parent |
|
528 | # set the value from it's parent | |
527 | obj.enable_locking = repo_group.enable_locking |
|
529 | obj.enable_locking = repo_group.enable_locking | |
528 | if isinstance(obj, RepoGroup): |
|
530 | if isinstance(obj, RepoGroup): | |
529 | new_name = obj.get_new_name(obj.name) |
|
531 | new_name = obj.get_new_name(obj.name) | |
530 | log.debug('Fixing group %s to new name %s', |
|
532 | log.debug('Fixing group %s to new name %s', | |
531 | obj.group_name, new_name) |
|
533 | obj.group_name, new_name) | |
532 | obj.group_name = new_name |
|
534 | obj.group_name = new_name | |
533 | obj.updated_on = datetime.datetime.now() |
|
535 | obj.updated_on = datetime.datetime.now() | |
534 | elif isinstance(obj, Repository): |
|
536 | elif isinstance(obj, Repository): | |
535 | # we need to get all repositories from this new group and |
|
537 | # we need to get all repositories from this new group and | |
536 | # rename them accordingly to new group path |
|
538 | # rename them accordingly to new group path | |
537 | new_name = obj.get_new_name(obj.just_name) |
|
539 | new_name = obj.get_new_name(obj.just_name) | |
538 | log.debug('Fixing repo %s to new name %s', |
|
540 | log.debug('Fixing repo %s to new name %s', | |
539 | obj.repo_name, new_name) |
|
541 | obj.repo_name, new_name) | |
540 | obj.repo_name = new_name |
|
542 | obj.repo_name = new_name | |
541 | obj.updated_on = datetime.datetime.now() |
|
543 | obj.updated_on = datetime.datetime.now() | |
542 | self.sa.add(obj) |
|
544 | self.sa.add(obj) | |
543 |
|
545 | |||
544 | self._rename_group(old_path, new_path) |
|
546 | self._rename_group(old_path, new_path) | |
545 |
|
547 | |||
546 | # Trigger update event. |
|
548 | # Trigger update event. | |
547 | events.trigger(events.RepoGroupUpdateEvent(repo_group)) |
|
549 | events.trigger(events.RepoGroupUpdateEvent(repo_group)) | |
548 |
|
550 | |||
549 | return repo_group |
|
551 | return repo_group | |
550 | except Exception: |
|
552 | except Exception: | |
551 | log.error(traceback.format_exc()) |
|
553 | log.error(traceback.format_exc()) | |
552 | raise |
|
554 | raise | |
553 |
|
555 | |||
554 | def delete(self, repo_group, force_delete=False, fs_remove=True): |
|
556 | def delete(self, repo_group, force_delete=False, fs_remove=True): | |
555 | repo_group = self._get_repo_group(repo_group) |
|
557 | repo_group = self._get_repo_group(repo_group) | |
556 | if not repo_group: |
|
558 | if not repo_group: | |
557 | return False |
|
559 | return False | |
558 | try: |
|
560 | try: | |
559 | self.sa.delete(repo_group) |
|
561 | self.sa.delete(repo_group) | |
560 | if fs_remove: |
|
562 | if fs_remove: | |
561 | self._delete_filesystem_group(repo_group, force_delete) |
|
563 | self._delete_filesystem_group(repo_group, force_delete) | |
562 | else: |
|
564 | else: | |
563 | log.debug('skipping removal from filesystem') |
|
565 | log.debug('skipping removal from filesystem') | |
564 |
|
566 | |||
565 | # Trigger delete event. |
|
567 | # Trigger delete event. | |
566 | events.trigger(events.RepoGroupDeleteEvent(repo_group)) |
|
568 | events.trigger(events.RepoGroupDeleteEvent(repo_group)) | |
567 | return True |
|
569 | return True | |
568 |
|
570 | |||
569 | except Exception: |
|
571 | except Exception: | |
570 | log.error('Error removing repo_group %s', repo_group) |
|
572 | log.error('Error removing repo_group %s', repo_group) | |
571 | raise |
|
573 | raise | |
572 |
|
574 | |||
573 | def grant_user_permission(self, repo_group, user, perm): |
|
575 | def grant_user_permission(self, repo_group, user, perm): | |
574 | """ |
|
576 | """ | |
575 | Grant permission for user on given repository group, or update |
|
577 | Grant permission for user on given repository group, or update | |
576 | existing one if found |
|
578 | existing one if found | |
577 |
|
579 | |||
578 | :param repo_group: Instance of RepoGroup, repositories_group_id, |
|
580 | :param repo_group: Instance of RepoGroup, repositories_group_id, | |
579 | or repositories_group name |
|
581 | or repositories_group name | |
580 | :param user: Instance of User, user_id or username |
|
582 | :param user: Instance of User, user_id or username | |
581 | :param perm: Instance of Permission, or permission_name |
|
583 | :param perm: Instance of Permission, or permission_name | |
582 | """ |
|
584 | """ | |
583 |
|
585 | |||
584 | repo_group = self._get_repo_group(repo_group) |
|
586 | repo_group = self._get_repo_group(repo_group) | |
585 | user = self._get_user(user) |
|
587 | user = self._get_user(user) | |
586 | permission = self._get_perm(perm) |
|
588 | permission = self._get_perm(perm) | |
587 |
|
589 | |||
588 | # check if we have that permission already |
|
590 | # check if we have that permission already | |
589 | obj = self.sa.query(UserRepoGroupToPerm)\ |
|
591 | obj = self.sa.query(UserRepoGroupToPerm)\ | |
590 | .filter(UserRepoGroupToPerm.user == user)\ |
|
592 | .filter(UserRepoGroupToPerm.user == user)\ | |
591 | .filter(UserRepoGroupToPerm.group == repo_group)\ |
|
593 | .filter(UserRepoGroupToPerm.group == repo_group)\ | |
592 | .scalar() |
|
594 | .scalar() | |
593 | if obj is None: |
|
595 | if obj is None: | |
594 | # create new ! |
|
596 | # create new ! | |
595 | obj = UserRepoGroupToPerm() |
|
597 | obj = UserRepoGroupToPerm() | |
596 | obj.group = repo_group |
|
598 | obj.group = repo_group | |
597 | obj.user = user |
|
599 | obj.user = user | |
598 | obj.permission = permission |
|
600 | obj.permission = permission | |
599 | self.sa.add(obj) |
|
601 | self.sa.add(obj) | |
600 | log.debug('Granted perm %s to %s on %s', perm, user, repo_group) |
|
602 | log.debug('Granted perm %s to %s on %s', perm, user, repo_group) | |
601 | action_logger_generic( |
|
603 | action_logger_generic( | |
602 | 'granted permission: {} to user: {} on repogroup: {}'.format( |
|
604 | 'granted permission: {} to user: {} on repogroup: {}'.format( | |
603 | perm, user, repo_group), namespace='security.repogroup') |
|
605 | perm, user, repo_group), namespace='security.repogroup') | |
604 | return obj |
|
606 | return obj | |
605 |
|
607 | |||
606 | def revoke_user_permission(self, repo_group, user): |
|
608 | def revoke_user_permission(self, repo_group, user): | |
607 | """ |
|
609 | """ | |
608 | Revoke permission for user on given repository group |
|
610 | Revoke permission for user on given repository group | |
609 |
|
611 | |||
610 | :param repo_group: Instance of RepoGroup, repositories_group_id, |
|
612 | :param repo_group: Instance of RepoGroup, repositories_group_id, | |
611 | or repositories_group name |
|
613 | or repositories_group name | |
612 | :param user: Instance of User, user_id or username |
|
614 | :param user: Instance of User, user_id or username | |
613 | """ |
|
615 | """ | |
614 |
|
616 | |||
615 | repo_group = self._get_repo_group(repo_group) |
|
617 | repo_group = self._get_repo_group(repo_group) | |
616 | user = self._get_user(user) |
|
618 | user = self._get_user(user) | |
617 |
|
619 | |||
618 | obj = self.sa.query(UserRepoGroupToPerm)\ |
|
620 | obj = self.sa.query(UserRepoGroupToPerm)\ | |
619 | .filter(UserRepoGroupToPerm.user == user)\ |
|
621 | .filter(UserRepoGroupToPerm.user == user)\ | |
620 | .filter(UserRepoGroupToPerm.group == repo_group)\ |
|
622 | .filter(UserRepoGroupToPerm.group == repo_group)\ | |
621 | .scalar() |
|
623 | .scalar() | |
622 | if obj: |
|
624 | if obj: | |
623 | self.sa.delete(obj) |
|
625 | self.sa.delete(obj) | |
624 | log.debug('Revoked perm on %s on %s', repo_group, user) |
|
626 | log.debug('Revoked perm on %s on %s', repo_group, user) | |
625 | action_logger_generic( |
|
627 | action_logger_generic( | |
626 | 'revoked permission from user: {} on repogroup: {}'.format( |
|
628 | 'revoked permission from user: {} on repogroup: {}'.format( | |
627 | user, repo_group), namespace='security.repogroup') |
|
629 | user, repo_group), namespace='security.repogroup') | |
628 |
|
630 | |||
629 | def grant_user_group_permission(self, repo_group, group_name, perm): |
|
631 | def grant_user_group_permission(self, repo_group, group_name, perm): | |
630 | """ |
|
632 | """ | |
631 | Grant permission for user group on given repository group, or update |
|
633 | Grant permission for user group on given repository group, or update | |
632 | existing one if found |
|
634 | existing one if found | |
633 |
|
635 | |||
634 | :param repo_group: Instance of RepoGroup, repositories_group_id, |
|
636 | :param repo_group: Instance of RepoGroup, repositories_group_id, | |
635 | or repositories_group name |
|
637 | or repositories_group name | |
636 | :param group_name: Instance of UserGroup, users_group_id, |
|
638 | :param group_name: Instance of UserGroup, users_group_id, | |
637 | or user group name |
|
639 | or user group name | |
638 | :param perm: Instance of Permission, or permission_name |
|
640 | :param perm: Instance of Permission, or permission_name | |
639 | """ |
|
641 | """ | |
640 | repo_group = self._get_repo_group(repo_group) |
|
642 | repo_group = self._get_repo_group(repo_group) | |
641 | group_name = self._get_user_group(group_name) |
|
643 | group_name = self._get_user_group(group_name) | |
642 | permission = self._get_perm(perm) |
|
644 | permission = self._get_perm(perm) | |
643 |
|
645 | |||
644 | # check if we have that permission already |
|
646 | # check if we have that permission already | |
645 | obj = self.sa.query(UserGroupRepoGroupToPerm)\ |
|
647 | obj = self.sa.query(UserGroupRepoGroupToPerm)\ | |
646 | .filter(UserGroupRepoGroupToPerm.group == repo_group)\ |
|
648 | .filter(UserGroupRepoGroupToPerm.group == repo_group)\ | |
647 | .filter(UserGroupRepoGroupToPerm.users_group == group_name)\ |
|
649 | .filter(UserGroupRepoGroupToPerm.users_group == group_name)\ | |
648 | .scalar() |
|
650 | .scalar() | |
649 |
|
651 | |||
650 | if obj is None: |
|
652 | if obj is None: | |
651 | # create new |
|
653 | # create new | |
652 | obj = UserGroupRepoGroupToPerm() |
|
654 | obj = UserGroupRepoGroupToPerm() | |
653 |
|
655 | |||
654 | obj.group = repo_group |
|
656 | obj.group = repo_group | |
655 | obj.users_group = group_name |
|
657 | obj.users_group = group_name | |
656 | obj.permission = permission |
|
658 | obj.permission = permission | |
657 | self.sa.add(obj) |
|
659 | self.sa.add(obj) | |
658 | log.debug('Granted perm %s to %s on %s', perm, group_name, repo_group) |
|
660 | log.debug('Granted perm %s to %s on %s', perm, group_name, repo_group) | |
659 | action_logger_generic( |
|
661 | action_logger_generic( | |
660 | 'granted permission: {} to usergroup: {} on repogroup: {}'.format( |
|
662 | 'granted permission: {} to usergroup: {} on repogroup: {}'.format( | |
661 | perm, group_name, repo_group), namespace='security.repogroup') |
|
663 | perm, group_name, repo_group), namespace='security.repogroup') | |
662 | return obj |
|
664 | return obj | |
663 |
|
665 | |||
664 | def revoke_user_group_permission(self, repo_group, group_name): |
|
666 | def revoke_user_group_permission(self, repo_group, group_name): | |
665 | """ |
|
667 | """ | |
666 | Revoke permission for user group on given repository group |
|
668 | Revoke permission for user group on given repository group | |
667 |
|
669 | |||
668 | :param repo_group: Instance of RepoGroup, repositories_group_id, |
|
670 | :param repo_group: Instance of RepoGroup, repositories_group_id, | |
669 | or repositories_group name |
|
671 | or repositories_group name | |
670 | :param group_name: Instance of UserGroup, users_group_id, |
|
672 | :param group_name: Instance of UserGroup, users_group_id, | |
671 | or user group name |
|
673 | or user group name | |
672 | """ |
|
674 | """ | |
673 | repo_group = self._get_repo_group(repo_group) |
|
675 | repo_group = self._get_repo_group(repo_group) | |
674 | group_name = self._get_user_group(group_name) |
|
676 | group_name = self._get_user_group(group_name) | |
675 |
|
677 | |||
676 | obj = self.sa.query(UserGroupRepoGroupToPerm)\ |
|
678 | obj = self.sa.query(UserGroupRepoGroupToPerm)\ | |
677 | .filter(UserGroupRepoGroupToPerm.group == repo_group)\ |
|
679 | .filter(UserGroupRepoGroupToPerm.group == repo_group)\ | |
678 | .filter(UserGroupRepoGroupToPerm.users_group == group_name)\ |
|
680 | .filter(UserGroupRepoGroupToPerm.users_group == group_name)\ | |
679 | .scalar() |
|
681 | .scalar() | |
680 | if obj: |
|
682 | if obj: | |
681 | self.sa.delete(obj) |
|
683 | self.sa.delete(obj) | |
682 | log.debug('Revoked perm to %s on %s', repo_group, group_name) |
|
684 | log.debug('Revoked perm to %s on %s', repo_group, group_name) | |
683 | action_logger_generic( |
|
685 | action_logger_generic( | |
684 | 'revoked permission from usergroup: {} on repogroup: {}'.format( |
|
686 | 'revoked permission from usergroup: {} on repogroup: {}'.format( | |
685 | group_name, repo_group), namespace='security.repogroup') |
|
687 | group_name, repo_group), namespace='security.repogroup') | |
686 |
|
688 | |||
687 | def get_repo_groups_as_dict(self, repo_group_list=None, admin=False, |
|
689 | def get_repo_groups_as_dict(self, repo_group_list=None, admin=False, | |
688 | super_user_actions=False): |
|
690 | super_user_actions=False): | |
689 |
|
691 | |||
690 | from pyramid.threadlocal import get_current_request |
|
692 | from pyramid.threadlocal import get_current_request | |
691 | _render = get_current_request().get_partial_renderer( |
|
693 | _render = get_current_request().get_partial_renderer( | |
692 | 'rhodecode:templates/data_table/_dt_elements.mako') |
|
694 | 'rhodecode:templates/data_table/_dt_elements.mako') | |
693 | c = _render.get_call_context() |
|
695 | c = _render.get_call_context() | |
694 | h = _render.get_helpers() |
|
696 | h = _render.get_helpers() | |
695 |
|
697 | |||
696 | def quick_menu(repo_group_name): |
|
698 | def quick_menu(repo_group_name): | |
697 | return _render('quick_repo_group_menu', repo_group_name) |
|
699 | return _render('quick_repo_group_menu', repo_group_name) | |
698 |
|
700 | |||
699 | def repo_group_lnk(repo_group_name): |
|
701 | def repo_group_lnk(repo_group_name): | |
700 | return _render('repo_group_name', repo_group_name) |
|
702 | return _render('repo_group_name', repo_group_name) | |
701 |
|
703 | |||
702 | def last_change(last_change): |
|
704 | def last_change(last_change): | |
703 | if admin and isinstance(last_change, datetime.datetime) and not last_change.tzinfo: |
|
705 | if admin and isinstance(last_change, datetime.datetime) and not last_change.tzinfo: | |
704 | last_change = last_change + datetime.timedelta(seconds= |
|
706 | last_change = last_change + datetime.timedelta(seconds= | |
705 | (datetime.datetime.now() - datetime.datetime.utcnow()).seconds) |
|
707 | (datetime.datetime.now() - datetime.datetime.utcnow()).seconds) | |
706 | return _render("last_change", last_change) |
|
708 | return _render("last_change", last_change) | |
707 |
|
709 | |||
708 | def desc(desc, personal): |
|
710 | def desc(desc, personal): | |
709 | return _render( |
|
711 | return _render( | |
710 | 'repo_group_desc', desc, personal, c.visual.stylify_metatags) |
|
712 | 'repo_group_desc', desc, personal, c.visual.stylify_metatags) | |
711 |
|
713 | |||
712 | def repo_group_actions(repo_group_id, repo_group_name, gr_count): |
|
714 | def repo_group_actions(repo_group_id, repo_group_name, gr_count): | |
713 | return _render( |
|
715 | return _render( | |
714 | 'repo_group_actions', repo_group_id, repo_group_name, gr_count) |
|
716 | 'repo_group_actions', repo_group_id, repo_group_name, gr_count) | |
715 |
|
717 | |||
716 | def repo_group_name(repo_group_name, children_groups): |
|
718 | def repo_group_name(repo_group_name, children_groups): | |
717 | return _render("repo_group_name", repo_group_name, children_groups) |
|
719 | return _render("repo_group_name", repo_group_name, children_groups) | |
718 |
|
720 | |||
719 | def user_profile(username): |
|
721 | def user_profile(username): | |
720 | return _render('user_profile', username) |
|
722 | return _render('user_profile', username) | |
721 |
|
723 | |||
722 | repo_group_data = [] |
|
724 | repo_group_data = [] | |
723 | for group in repo_group_list: |
|
725 | for group in repo_group_list: | |
724 |
|
726 | |||
725 | row = { |
|
727 | row = { | |
726 | "menu": quick_menu(group.group_name), |
|
728 | "menu": quick_menu(group.group_name), | |
727 | "name": repo_group_lnk(group.group_name), |
|
729 | "name": repo_group_lnk(group.group_name), | |
728 | "name_raw": group.group_name, |
|
730 | "name_raw": group.group_name, | |
729 | "last_change": last_change(group.last_db_change), |
|
731 | "last_change": last_change(group.last_db_change), | |
730 | "last_change_raw": datetime_to_time(group.last_db_change), |
|
732 | "last_change_raw": datetime_to_time(group.last_db_change), | |
731 |
|
733 | |||
732 | "last_changeset": "", |
|
734 | "last_changeset": "", | |
733 | "last_changeset_raw": "", |
|
735 | "last_changeset_raw": "", | |
734 |
|
736 | |||
735 | "desc": desc(group.description_safe, group.personal), |
|
737 | "desc": desc(group.description_safe, group.personal), | |
736 | "top_level_repos": 0, |
|
738 | "top_level_repos": 0, | |
737 | "owner": user_profile(group.user.username) |
|
739 | "owner": user_profile(group.user.username) | |
738 | } |
|
740 | } | |
739 | if admin: |
|
741 | if admin: | |
740 | repo_count = group.repositories.count() |
|
742 | repo_count = group.repositories.count() | |
741 | children_groups = map( |
|
743 | children_groups = map( | |
742 | h.safe_unicode, |
|
744 | h.safe_unicode, | |
743 | itertools.chain((g.name for g in group.parents), |
|
745 | itertools.chain((g.name for g in group.parents), | |
744 | (x.name for x in [group]))) |
|
746 | (x.name for x in [group]))) | |
745 | row.update({ |
|
747 | row.update({ | |
746 | "action": repo_group_actions( |
|
748 | "action": repo_group_actions( | |
747 | group.group_id, group.group_name, repo_count), |
|
749 | group.group_id, group.group_name, repo_count), | |
748 | "top_level_repos": repo_count, |
|
750 | "top_level_repos": repo_count, | |
749 | "name": repo_group_name(group.group_name, children_groups), |
|
751 | "name": repo_group_name(group.group_name, children_groups), | |
750 |
|
752 | |||
751 | }) |
|
753 | }) | |
752 | repo_group_data.append(row) |
|
754 | repo_group_data.append(row) | |
753 |
|
755 | |||
754 | return repo_group_data |
|
756 | return repo_group_data | |
755 |
|
757 | |||
756 | def _get_defaults(self, repo_group_name): |
|
758 | def _get_defaults(self, repo_group_name): | |
757 | repo_group = RepoGroup.get_by_group_name(repo_group_name) |
|
759 | repo_group = RepoGroup.get_by_group_name(repo_group_name) | |
758 |
|
760 | |||
759 | if repo_group is None: |
|
761 | if repo_group is None: | |
760 | return None |
|
762 | return None | |
761 |
|
763 | |||
762 | defaults = repo_group.get_dict() |
|
764 | defaults = repo_group.get_dict() | |
763 | defaults['repo_group_name'] = repo_group.name |
|
765 | defaults['repo_group_name'] = repo_group.name | |
764 | defaults['repo_group_description'] = repo_group.group_description |
|
766 | defaults['repo_group_description'] = repo_group.group_description | |
765 | defaults['repo_group_enable_locking'] = repo_group.enable_locking |
|
767 | defaults['repo_group_enable_locking'] = repo_group.enable_locking | |
766 |
|
768 | |||
767 | # we use -1 as this is how in HTML, we mark an empty group |
|
769 | # we use -1 as this is how in HTML, we mark an empty group | |
768 | defaults['repo_group'] = defaults['group_parent_id'] or -1 |
|
770 | defaults['repo_group'] = defaults['group_parent_id'] or -1 | |
769 |
|
771 | |||
770 | # fill owner |
|
772 | # fill owner | |
771 | if repo_group.user: |
|
773 | if repo_group.user: | |
772 | defaults.update({'user': repo_group.user.username}) |
|
774 | defaults.update({'user': repo_group.user.username}) | |
773 | else: |
|
775 | else: | |
774 | replacement_user = User.get_first_super_admin().username |
|
776 | replacement_user = User.get_first_super_admin().username | |
775 | defaults.update({'user': replacement_user}) |
|
777 | defaults.update({'user': replacement_user}) | |
776 |
|
778 | |||
777 | return defaults |
|
779 | return defaults |
@@ -1,143 +1,148 b'' | |||||
1 | ## -*- coding: utf-8 -*- |
|
1 | ## -*- coding: utf-8 -*- | |
2 | <%namespace name="base" file="/base/base.mako"/> |
|
2 | <%namespace name="base" file="/base/base.mako"/> | |
3 | %if c.repo_commits: |
|
3 | %if c.repo_commits: | |
4 | <table class="rctable repo_summary table_disp"> |
|
4 | <table class="rctable repo_summary table_disp"> | |
5 | <tr> |
|
5 | <tr> | |
6 |
|
6 | |||
7 | <th class="status"></th> |
|
7 | <th class="status"></th> | |
8 | <th>${_('Commit')}</th> |
|
8 | <th>${_('Commit')}</th> | |
9 | <th>${_('Commit message')}</th> |
|
9 | <th>${_('Commit message')}</th> | |
10 | <th>${_('Age')}</th> |
|
10 | <th>${_('Age')}</th> | |
11 | <th>${_('Author')}</th> |
|
11 | <th>${_('Author')}</th> | |
12 | <th colspan="2">${_('Refs')}</th> |
|
12 | <th colspan="2">${_('Refs')}</th> | |
13 | </tr> |
|
13 | </tr> | |
14 |
|
14 | |||
15 | ## to speed up lookups cache some functions before the loop |
|
15 | ## to speed up lookups cache some functions before the loop | |
16 | <% |
|
16 | <% | |
17 | active_patterns = h.get_active_pattern_entries(c.repo_name) |
|
17 | active_patterns = h.get_active_pattern_entries(c.repo_name) | |
18 | urlify_commit_message = h.partial(h.urlify_commit_message, active_pattern_entries=active_patterns) |
|
18 | urlify_commit_message = h.partial(h.urlify_commit_message, active_pattern_entries=active_patterns) | |
19 | %> |
|
19 | %> | |
20 | %for cnt,cs in enumerate(c.repo_commits): |
|
20 | %for cnt,cs in enumerate(c.repo_commits): | |
21 | <tr class="parity${cnt%2}"> |
|
21 | <tr class="parity${cnt%2}"> | |
22 |
|
22 | |||
23 | <td class="td-status"> |
|
23 | <td class="td-status"> | |
24 | %if c.statuses.get(cs.raw_id): |
|
24 | %if c.statuses.get(cs.raw_id): | |
25 | <div class="changeset-status-ico shortlog"> |
|
25 | <div class="changeset-status-ico shortlog"> | |
26 | %if c.statuses.get(cs.raw_id)[2]: |
|
26 | %if c.statuses.get(cs.raw_id)[2]: | |
27 | <a class="tooltip" title="${_('Commit status: %s\nClick to open associated pull request #%s') % (c.statuses.get(cs.raw_id)[0], c.statuses.get(cs.raw_id)[2])}" href="${h.route_path('pullrequest_show',repo_name=c.statuses.get(cs.raw_id)[3],pull_request_id=c.statuses.get(cs.raw_id)[2])}"> |
|
27 | <a class="tooltip" title="${_('Commit status: %s\nClick to open associated pull request #%s') % (c.statuses.get(cs.raw_id)[0], c.statuses.get(cs.raw_id)[2])}" href="${h.route_path('pullrequest_show',repo_name=c.statuses.get(cs.raw_id)[3],pull_request_id=c.statuses.get(cs.raw_id)[2])}"> | |
28 | <div class="${'flag_status {}'.format(c.statuses.get(cs.raw_id)[0])}"></div> |
|
28 | <div class="${'flag_status {}'.format(c.statuses.get(cs.raw_id)[0])}"></div> | |
29 | </a> |
|
29 | </a> | |
30 | %else: |
|
30 | %else: | |
31 | <a class="tooltip" title="${_('Commit status: {}').format(h.commit_status_lbl(c.statuses.get(cs.raw_id)[0]))}" href="${h.route_path('repo_commit',repo_name=c.repo_name,commit_id=cs.raw_id,_anchor='comment-%s' % c.comments[cs.raw_id][0].comment_id)}"> |
|
31 | <a class="tooltip" title="${_('Commit status: {}').format(h.commit_status_lbl(c.statuses.get(cs.raw_id)[0]))}" href="${h.route_path('repo_commit',repo_name=c.repo_name,commit_id=cs.raw_id,_anchor='comment-%s' % c.comments[cs.raw_id][0].comment_id)}"> | |
32 | <div class="${'flag_status {}'.format(c.statuses.get(cs.raw_id)[0])}"></div> |
|
32 | <div class="${'flag_status {}'.format(c.statuses.get(cs.raw_id)[0])}"></div> | |
33 | </a> |
|
33 | </a> | |
34 | %endif |
|
34 | %endif | |
35 | </div> |
|
35 | </div> | |
36 | %else: |
|
36 | %else: | |
37 | <div class="tooltip flag_status not_reviewed" title="${_('Commit status: Not Reviewed')}"></div> |
|
37 | <div class="tooltip flag_status not_reviewed" title="${_('Commit status: Not Reviewed')}"></div> | |
38 | %endif |
|
38 | %endif | |
39 | </td> |
|
39 | </td> | |
40 | <td class="td-commit"> |
|
40 | <td class="td-commit"> | |
41 | <code> |
|
41 | <code> | |
42 | <a href="${h.route_path('repo_commit', repo_name=c.repo_name, commit_id=cs.raw_id)}">${h.show_id(cs)}</a> |
|
42 | <a href="${h.route_path('repo_commit', repo_name=c.repo_name, commit_id=cs.raw_id)}">${h.show_id(cs)}</a> | |
43 | <i class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${cs.raw_id}" title="${_('Copy the full commit id')}"></i> |
|
43 | <i class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${cs.raw_id}" title="${_('Copy the full commit id')}"></i> | |
44 | </code> |
|
44 | </code> | |
45 | </td> |
|
45 | </td> | |
46 |
|
46 | |||
47 | <td class="td-description mid"> |
|
47 | <td class="td-description mid"> | |
48 | <div class="log-container truncate-wrap"> |
|
48 | <div class="log-container truncate-wrap"> | |
49 | <div class="message truncate" id="c-${cs.raw_id}">${urlify_commit_message(cs.message, c.repo_name)}</div> |
|
49 | <div class="message truncate" id="c-${cs.raw_id}">${urlify_commit_message(cs.message, c.repo_name)}</div> | |
50 | </div> |
|
50 | </div> | |
51 | </td> |
|
51 | </td> | |
52 |
|
52 | |||
53 | <td class="td-time"> |
|
53 | <td class="td-time"> | |
54 | ${h.age_component(cs.date)} |
|
54 | ${h.age_component(cs.date)} | |
55 | </td> |
|
55 | </td> | |
56 | <td class="td-user author"> |
|
56 | <td class="td-user author"> | |
57 | ${base.gravatar_with_user(cs.author)} |
|
57 | ${base.gravatar_with_user(cs.author)} | |
58 | </td> |
|
58 | </td> | |
59 |
|
59 | |||
60 | <td class="td-tags"> |
|
60 | <td class="td-tags"> | |
61 | <div class="autoexpand"> |
|
61 | <div class="autoexpand"> | |
62 | %if h.is_hg(c.rhodecode_repo): |
|
62 | %if h.is_hg(c.rhodecode_repo): | |
63 | %for book in cs.bookmarks: |
|
63 | %for book in cs.bookmarks: | |
64 | <span class="booktag tag" title="${h.tooltip(_('Bookmark %s') % book)}"> |
|
64 | <span class="booktag tag" title="${h.tooltip(_('Bookmark %s') % book)}"> | |
65 | <a href="${h.route_path('repo_files:default_path',repo_name=c.repo_name,commit_id=cs.raw_id, _query=dict(at=book))}"><i class="icon-bookmark"></i>${h.shorter(book)}</a> |
|
65 | <a href="${h.route_path('repo_files:default_path',repo_name=c.repo_name,commit_id=cs.raw_id, _query=dict(at=book))}"><i class="icon-bookmark"></i>${h.shorter(book)}</a> | |
66 | </span> |
|
66 | </span> | |
67 | %endfor |
|
67 | %endfor | |
68 | %endif |
|
68 | %endif | |
69 | ## tags |
|
69 | ## tags | |
70 | %for tag in cs.tags: |
|
70 | %for tag in cs.tags: | |
71 | <span class="tagtag tag" title="${h.tooltip(_('Tag %s') % tag)}"> |
|
71 | <span class="tagtag tag" title="${h.tooltip(_('Tag %s') % tag)}"> | |
72 | <a href="${h.route_path('repo_files:default_path',repo_name=c.repo_name,commit_id=cs.raw_id, _query=dict(at=tag))}"><i class="icon-tag"></i>${h.shorter(tag)}</a> |
|
72 | <a href="${h.route_path('repo_files:default_path',repo_name=c.repo_name,commit_id=cs.raw_id, _query=dict(at=tag))}"><i class="icon-tag"></i>${h.shorter(tag)}</a> | |
73 | </span> |
|
73 | </span> | |
74 | %endfor |
|
74 | %endfor | |
75 |
|
75 | |||
76 | ## branch |
|
76 | ## branch | |
77 | %if cs.branch: |
|
77 | %if cs.branch: | |
78 | <span class="branchtag tag" title="${h.tooltip(_('Branch %s') % cs.branch)}"> |
|
78 | <span class="branchtag tag" title="${h.tooltip(_('Branch %s') % cs.branch)}"> | |
79 | <a href="${h.route_path('repo_changelog',repo_name=c.repo_name,_query=dict(branch=cs.branch))}"><i class="icon-code-fork"></i>${h.shorter(cs.branch)}</a> |
|
79 | <a href="${h.route_path('repo_changelog',repo_name=c.repo_name,_query=dict(branch=cs.branch))}"><i class="icon-code-fork"></i>${h.shorter(cs.branch)}</a> | |
80 | </span> |
|
80 | </span> | |
81 | %endif |
|
81 | %endif | |
82 | </div> |
|
82 | </div> | |
83 | </td> |
|
83 | </td> | |
84 | <td class="td-comments"> |
|
84 | <td class="td-comments"> | |
85 | <% cs_comments = c.comments.get(cs.raw_id,[]) %> |
|
85 | <% cs_comments = c.comments.get(cs.raw_id,[]) %> | |
86 | % if cs_comments: |
|
86 | % if cs_comments: | |
87 | <a title="${_('Commit has comments')}" href="${h.route_path('repo_commit',repo_name=c.repo_name,commit_id=cs.raw_id,_anchor='comment-%s' % cs_comments[0].comment_id)}"> |
|
87 | <a title="${_('Commit has comments')}" href="${h.route_path('repo_commit',repo_name=c.repo_name,commit_id=cs.raw_id,_anchor='comment-%s' % cs_comments[0].comment_id)}"> | |
88 | <i class="icon-comment"></i> ${len(cs_comments)} |
|
88 | <i class="icon-comment"></i> ${len(cs_comments)} | |
89 | </a> |
|
89 | </a> | |
90 | % else: |
|
90 | % else: | |
91 | <i class="icon-comment"></i> ${len(cs_comments)} |
|
91 | <i class="icon-comment"></i> ${len(cs_comments)} | |
92 | % endif |
|
92 | % endif | |
93 | </td> |
|
93 | </td> | |
94 | </tr> |
|
94 | </tr> | |
95 | %endfor |
|
95 | %endfor | |
96 |
|
96 | |||
97 | </table> |
|
97 | </table> | |
98 |
|
98 | |||
99 | <script type="text/javascript"> |
|
99 | <script type="text/javascript"> | |
100 |
$(document).pjax('#shortlog_data .pager_link','#shortlog_data', {timeout: |
|
100 | $(document).pjax('#shortlog_data .pager_link','#shortlog_data', {timeout: 5000, scrollTo: false, push: false}); | |
101 | $(document).on('pjax:success', function(){ timeagoActivate(); }); |
|
101 | $(document).on('pjax:success', function(){ timeagoActivate(); }); | |
|
102 | $(document).on('pjax:timeout', function(event) { | |||
|
103 | // Prevent default timeout redirection behavior | |||
|
104 | event.preventDefault() | |||
|
105 | }) | |||
|
106 | ||||
102 | </script> |
|
107 | </script> | |
103 |
|
108 | |||
104 | <div class="pagination-wh pagination-left"> |
|
109 | <div class="pagination-wh pagination-left"> | |
105 | ${c.repo_commits.pager('$link_previous ~2~ $link_next')} |
|
110 | ${c.repo_commits.pager('$link_previous ~2~ $link_next')} | |
106 | </div> |
|
111 | </div> | |
107 | %else: |
|
112 | %else: | |
108 |
|
113 | |||
109 | %if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name): |
|
114 | %if h.HasRepoPermissionAny('repository.write','repository.admin')(c.repo_name): | |
110 | <div class="quick_start"> |
|
115 | <div class="quick_start"> | |
111 | <div class="fieldset"> |
|
116 | <div class="fieldset"> | |
112 | <p><b>${_('Add or upload files directly via RhodeCode:')}</b></p> |
|
117 | <p><b>${_('Add or upload files directly via RhodeCode:')}</b></p> | |
113 | <div id="add_node_id" class="add_node"> |
|
118 | <div id="add_node_id" class="add_node"> | |
114 | <a href="${h.route_path('repo_files_add_file',repo_name=c.repo_name,commit_id=0, f_path='', _anchor='edit')}" class="btn btn-default">${_('Add New File')}</a> |
|
119 | <a href="${h.route_path('repo_files_add_file',repo_name=c.repo_name,commit_id=0, f_path='', _anchor='edit')}" class="btn btn-default">${_('Add New File')}</a> | |
115 | </div> |
|
120 | </div> | |
116 | %endif |
|
121 | %endif | |
117 | </div> |
|
122 | </div> | |
118 |
|
123 | |||
119 | %if not h.is_svn(c.rhodecode_repo): |
|
124 | %if not h.is_svn(c.rhodecode_repo): | |
120 | <div class="fieldset"> |
|
125 | <div class="fieldset"> | |
121 | <p><b>${_('Push new repo:')}</b></p> |
|
126 | <p><b>${_('Push new repo:')}</b></p> | |
122 | <pre> |
|
127 | <pre> | |
123 | ${c.rhodecode_repo.alias} clone ${c.clone_repo_url} |
|
128 | ${c.rhodecode_repo.alias} clone ${c.clone_repo_url} | |
124 | ${c.rhodecode_repo.alias} add README # add first file |
|
129 | ${c.rhodecode_repo.alias} add README # add first file | |
125 | ${c.rhodecode_repo.alias} commit -m "Initial" # commit with message |
|
130 | ${c.rhodecode_repo.alias} commit -m "Initial" # commit with message | |
126 | ${c.rhodecode_repo.alias} push ${'origin master' if h.is_git(c.rhodecode_repo) else ''} # push changes back |
|
131 | ${c.rhodecode_repo.alias} push ${'origin master' if h.is_git(c.rhodecode_repo) else ''} # push changes back | |
127 | </pre> |
|
132 | </pre> | |
128 | </div> |
|
133 | </div> | |
129 |
|
134 | |||
130 | <div class="fieldset"> |
|
135 | <div class="fieldset"> | |
131 | <p><b>${_('Existing repository?')}</b></p> |
|
136 | <p><b>${_('Existing repository?')}</b></p> | |
132 | <pre> |
|
137 | <pre> | |
133 | %if h.is_git(c.rhodecode_repo): |
|
138 | %if h.is_git(c.rhodecode_repo): | |
134 | git remote add origin ${c.clone_repo_url} |
|
139 | git remote add origin ${c.clone_repo_url} | |
135 | git push -u origin master |
|
140 | git push -u origin master | |
136 | %else: |
|
141 | %else: | |
137 | hg push ${c.clone_repo_url} |
|
142 | hg push ${c.clone_repo_url} | |
138 | %endif |
|
143 | %endif | |
139 | </pre> |
|
144 | </pre> | |
140 | </div> |
|
145 | </div> | |
141 | %endif |
|
146 | %endif | |
142 | </div> |
|
147 | </div> | |
143 | %endif |
|
148 | %endif |
General Comments 0
You need to be logged in to leave comments.
Login now