##// END OF EJS Templates
Added pre-create user hook....
marcink -
r4074:3b136af3 default
parent child Browse files
Show More
@@ -53,6 +53,29 b' CREATE_REPO_HOOK = _crrepohook'
53
53
54
54
55 #==============================================================================
55 #==============================================================================
56 # PRE CREATE USER HOOK
57 #==============================================================================
58 # this function will be executed before each user is created
59 def _pre_cruserhook(*args, **kwargs):
60 """
61 Pre create user HOOK, it returns a tuple of bool, reason.
62 If bool is False the user creation will be stopped and reason
63 will be displayed to the user.
64 kwargs available:
65 :param username:
66 :param password:
67 :param email:
68 :param firstname:
69 :param lastname:
70 :param active:
71 :param admin:
72 :param created_by:
73 """
74 reason = 'allowed'
75 return True, reason
76 PRE_CREATE_USER_HOOK = _pre_cruserhook
77
78 #==============================================================================
56 # POST CREATE USER HOOK
79 # POST CREATE USER HOOK
57 #==============================================================================
80 #==============================================================================
58 # this function will be executed after each user is created
81 # this function will be executed after each user is created
@@ -35,7 +35,7 b' from pylons.i18n.translation import _'
35
35
36 import rhodecode
36 import rhodecode
37 from rhodecode.lib.exceptions import DefaultUserException, \
37 from rhodecode.lib.exceptions import DefaultUserException, \
38 UserOwnsReposException
38 UserOwnsReposException, UserCreationError
39 from rhodecode.lib import helpers as h
39 from rhodecode.lib import helpers as h
40 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
40 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
41 AuthUser
41 AuthUser
@@ -137,6 +137,8 b' class UsersController(BaseController):'
137 errors=errors.error_dict or {},
137 errors=errors.error_dict or {},
138 prefix_error=False,
138 prefix_error=False,
139 encoding="UTF-8")
139 encoding="UTF-8")
140 except UserCreationError, e:
141 h.flash(e, 'error')
140 except Exception:
142 except Exception:
141 log.error(traceback.format_exc())
143 log.error(traceback.format_exc())
142 h.flash(_('Error occurred during creation of user %s') \
144 h.flash(_('Error occurred during creation of user %s') \
@@ -37,6 +37,7 b' from pylons import request, response, se'
37 import rhodecode.lib.helpers as h
37 import rhodecode.lib.helpers as h
38 from rhodecode.lib.auth import AuthUser, HasPermissionAnyDecorator
38 from rhodecode.lib.auth import AuthUser, HasPermissionAnyDecorator
39 from rhodecode.lib.base import BaseController, render
39 from rhodecode.lib.base import BaseController, render
40 from rhodecode.lib.exceptions import UserCreationError
40 from rhodecode.model.db import User
41 from rhodecode.model.db import User
41 from rhodecode.model.forms import LoginForm, RegisterForm, PasswordResetForm
42 from rhodecode.model.forms import LoginForm, RegisterForm, PasswordResetForm
42 from rhodecode.model.user import UserModel
43 from rhodecode.model.user import UserModel
@@ -120,6 +121,12 b' class LoginController(BaseController):'
120 errors=errors.error_dict or {},
121 errors=errors.error_dict or {},
121 prefix_error=False,
122 prefix_error=False,
122 encoding="UTF-8")
123 encoding="UTF-8")
124 except UserCreationError, e:
125 # container auth or other auth functions that create users on
126 # the fly can throw this exception signaling that there's issue
127 # with user creation, explanation should be provided in
128 # Exception itself
129 h.flash(e, 'error')
123
130
124 return render('/login.html')
131 return render('/login.html')
125
132
@@ -147,6 +154,12 b' class LoginController(BaseController):'
147 errors=errors.error_dict or {},
154 errors=errors.error_dict or {},
148 prefix_error=False,
155 prefix_error=False,
149 encoding="UTF-8")
156 encoding="UTF-8")
157 except UserCreationError, e:
158 # container auth or other auth functions that create users on
159 # the fly can throw this exception signaling that there's issue
160 # with user creation, explanation should be provided in
161 # Exception itself
162 h.flash(e, 'error')
150
163
151 return render('/register.html')
164 return render('/register.html')
152
165
@@ -22,6 +22,7 b' from rhodecode.lib.utils2 import str2boo'
22 from rhodecode.lib.auth import AuthUser, get_container_username, authfunc,\
22 from rhodecode.lib.auth import AuthUser, get_container_username, authfunc,\
23 HasPermissionAnyMiddleware, CookieStoreWrapper
23 HasPermissionAnyMiddleware, CookieStoreWrapper
24 from rhodecode.lib.utils import get_repo_slug
24 from rhodecode.lib.utils import get_repo_slug
25 from rhodecode.lib.exceptions import UserCreationError
25 from rhodecode.model import meta
26 from rhodecode.model import meta
26
27
27 from rhodecode.model.db import Repository, RhodeCodeUi, User, RhodeCodeSetting
28 from rhodecode.model.db import Repository, RhodeCodeUi, User, RhodeCodeSetting
@@ -300,7 +301,17 b' class BaseController(WSGIController):'
300 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
301 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
301 user_id = cookie_store.get('user_id', None)
302 user_id = cookie_store.get('user_id', None)
302 username = get_container_username(environ, config)
303 username = get_container_username(environ, config)
304 try:
303 auth_user = AuthUser(user_id, api_key, username, self.ip_addr)
305 auth_user = AuthUser(user_id, api_key, username, self.ip_addr)
306 except UserCreationError, e:
307 from rhodecode.lib import helpers as h
308 h.flash(e, 'error')
309 # container auth or other auth functions that create users on
310 # the fly can throw this exception signaling that there's issue
311 # with user creation, explanation should be provided in
312 # Exception itself
313 auth_user = AuthUser(ip_addr=self.ip_addr)
314
304 request.user = auth_user
315 request.user = auth_user
305 self.rhodecode_user = c.rhodecode_user = auth_user
316 self.rhodecode_user = c.rhodecode_user = auth_user
306 if not self.rhodecode_user.is_authenticated and \
317 if not self.rhodecode_user.is_authenticated and \
@@ -90,3 +90,11 b' class HTTPLockedRC(HTTPClientError):'
90
90
91 class IMCCommitError(Exception):
91 class IMCCommitError(Exception):
92 pass
92 pass
93
94
95 class UserCreationError(Exception):
96 pass
97
98
99 class RepositoryCreationError(Exception):
100 pass
@@ -34,7 +34,7 b' from rhodecode.lib import helpers as h'
34 from rhodecode.lib.utils import action_logger
34 from rhodecode.lib.utils import action_logger
35 from rhodecode.lib.vcs.backends.base import EmptyChangeset
35 from rhodecode.lib.vcs.backends.base import EmptyChangeset
36 from rhodecode.lib.compat import json
36 from rhodecode.lib.compat import json
37 from rhodecode.lib.exceptions import HTTPLockedRC
37 from rhodecode.lib.exceptions import HTTPLockedRC, UserCreationError
38 from rhodecode.lib.utils2 import safe_str, _extract_extras
38 from rhodecode.lib.utils2 import safe_str, _extract_extras
39 from rhodecode.model.db import Repository, User
39 from rhodecode.model.db import Repository, User
40
40
@@ -252,6 +252,15 b' def log_create_repository(repository_dic'
252 return 0
252 return 0
253
253
254
254
255 def check_allowed_create_user(user_dict, created_by, **kwargs):
256 from rhodecode import EXTENSIONS
257 callback = getattr(EXTENSIONS, 'PRE_CREATE_USER_HOOK', None)
258 if isfunction(callback):
259 allowed, reason = callback(created_by=created_by, **user_dict)
260 if not allowed:
261 raise UserCreationError(reason)
262
263
255 def log_create_user(user_dict, created_by, **kwargs):
264 def log_create_user(user_dict, created_by, **kwargs):
256 """
265 """
257 Post create user Hook. This is a dummy function for admins to re-use
266 Post create user Hook. This is a dummy function for admins to re-use
@@ -36,9 +36,9 b' from sqlalchemy.orm import joinedload'
36 from rhodecode.lib.utils2 import safe_unicode, generate_api_key, get_current_rhodecode_user
36 from rhodecode.lib.utils2 import safe_unicode, generate_api_key, get_current_rhodecode_user
37 from rhodecode.lib.caching_query import FromCache
37 from rhodecode.lib.caching_query import FromCache
38 from rhodecode.model import BaseModel
38 from rhodecode.model import BaseModel
39 from rhodecode.model.db import User, UserRepoToPerm, Repository, Permission, \
39 from rhodecode.model.db import User, Repository, Permission, \
40 UserToPerm, UserGroupRepoToPerm, UserGroupToPerm, UserGroupMember, \
40 UserToPerm, UserGroupRepoToPerm, UserGroupToPerm, UserGroupMember, \
41 Notification, RepoGroup, UserRepoGroupToPerm, UserGroupRepoGroupToPerm, \
41 Notification, RepoGroup, UserGroupRepoGroupToPerm, \
42 UserEmailMap, UserIpMap, UserGroupUserGroupToPerm, UserGroup
42 UserEmailMap, UserIpMap, UserGroupUserGroupToPerm, UserGroup
43 from rhodecode.lib.exceptions import DefaultUserException, \
43 from rhodecode.lib.exceptions import DefaultUserException, \
44 UserOwnsReposException
44 UserOwnsReposException
@@ -83,6 +83,17 b' class UserModel(BaseModel):'
83 def create(self, form_data, cur_user=None):
83 def create(self, form_data, cur_user=None):
84 if not cur_user:
84 if not cur_user:
85 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
85 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
86
87 from rhodecode.lib.hooks import log_create_user, check_allowed_create_user
88 _fd = form_data
89 form_data = {
90 'username': _fd['username'], 'password': _fd['password'],
91 'email': _fd['email'], 'firstname': _fd['firstname'], 'lastname': _fd['lastname'],
92 'active': _fd['active'], 'admin': False
93 }
94 # raises UserCreationError if it's not allowed
95 check_allowed_create_user(form_data, cur_user)
96
86 from rhodecode.lib.auth import get_crypt_password
97 from rhodecode.lib.auth import get_crypt_password
87 try:
98 try:
88 new_user = User()
99 new_user = User()
@@ -96,7 +107,6 b' class UserModel(BaseModel):'
96 new_user.api_key = generate_api_key(form_data['username'])
107 new_user.api_key = generate_api_key(form_data['username'])
97 self.sa.add(new_user)
108 self.sa.add(new_user)
98
109
99 from rhodecode.lib.hooks import log_create_user
100 log_create_user(new_user.get_dict(), cur_user)
110 log_create_user(new_user.get_dict(), cur_user)
101 return new_user
111 return new_user
102 except Exception:
112 except Exception:
@@ -124,6 +134,14 b' class UserModel(BaseModel):'
124 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
134 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
125
135
126 from rhodecode.lib.auth import get_crypt_password
136 from rhodecode.lib.auth import get_crypt_password
137 from rhodecode.lib.hooks import log_create_user, check_allowed_create_user
138 form_data = {
139 'username': username, 'password': password,
140 'email': email, 'firstname': firstname, 'lastname': lastname,
141 'active': active, 'admin': admin
142 }
143 # raises UserCreationError if it's not allowed
144 check_allowed_create_user(form_data, cur_user)
127
145
128 log.debug('Checking for %s account in RhodeCode database' % username)
146 log.debug('Checking for %s account in RhodeCode database' % username)
129 user = User.get_by_username(username, case_insensitive=True)
147 user = User.get_by_username(username, case_insensitive=True)
@@ -151,7 +169,6 b' class UserModel(BaseModel):'
151 self.sa.add(new_user)
169 self.sa.add(new_user)
152
170
153 if not edit:
171 if not edit:
154 from rhodecode.lib.hooks import log_create_user
155 log_create_user(new_user.get_dict(), cur_user)
172 log_create_user(new_user.get_dict(), cur_user)
156 return new_user
173 return new_user
157 except (DatabaseError,):
174 except (DatabaseError,):
@@ -169,23 +186,33 b' class UserModel(BaseModel):'
169 if not cur_user:
186 if not cur_user:
170 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
187 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
171 if self.get_by_username(username, case_insensitive=True) is None:
188 if self.get_by_username(username, case_insensitive=True) is None:
172
173 # autogenerate email for container account without one
189 # autogenerate email for container account without one
174 generate_email = lambda usr: '%s@container_auth.account' % usr
190 generate_email = lambda usr: '%s@container_auth.account' % usr
191 firstname = attrs['name']
192 lastname = attrs['lastname']
193 active = attrs.get('active', True)
194 email = attrs['email'] or generate_email(username)
195
196 from rhodecode.lib.hooks import log_create_user, check_allowed_create_user
197 form_data = {
198 'username': username, 'password': None,
199 'email': email, 'firstname': firstname, 'lastname': lastname,
200 'active': attrs.get('active', True), 'admin': False
201 }
202 # raises UserCreationError if it's not allowed
203 check_allowed_create_user(form_data, cur_user)
175
204
176 try:
205 try:
177 new_user = User()
206 new_user = User()
178 new_user.username = username
207 new_user.username = username
179 new_user.password = None
208 new_user.password = None
180 new_user.api_key = generate_api_key(username)
209 new_user.api_key = generate_api_key(username)
181 new_user.email = attrs['email']
210 new_user.email = email
182 new_user.active = attrs.get('active', True)
211 new_user.active = active
183 new_user.name = attrs['name'] or generate_email(username)
212 new_user.name = firstname
184 new_user.lastname = attrs['lastname']
213 new_user.lastname = lastname
185
214
186 self.sa.add(new_user)
215 self.sa.add(new_user)
187
188 from rhodecode.lib.hooks import log_create_user
189 log_create_user(new_user.get_dict(), cur_user)
216 log_create_user(new_user.get_dict(), cur_user)
190 return new_user
217 return new_user
191 except (DatabaseError,):
218 except (DatabaseError,):
@@ -212,26 +239,37 b' class UserModel(BaseModel):'
212 from rhodecode.lib.auth import get_crypt_password
239 from rhodecode.lib.auth import get_crypt_password
213 log.debug('Checking for such ldap account in RhodeCode database')
240 log.debug('Checking for such ldap account in RhodeCode database')
214 if self.get_by_username(username, case_insensitive=True) is None:
241 if self.get_by_username(username, case_insensitive=True) is None:
242 # autogenerate email for container account without one
243 generate_email = lambda usr: '%s@ldap.account' % usr
244 password = get_crypt_password(password)
245 firstname = attrs['name']
246 lastname = attrs['lastname']
247 active = attrs.get('active', True)
248 email = attrs['email'] or generate_email(username)
215
249
216 # autogenerate email for ldap account without one
250 from rhodecode.lib.hooks import log_create_user, check_allowed_create_user
217 generate_email = lambda usr: '%s@ldap.account' % usr
251 form_data = {
252 'username': username, 'password': password,
253 'email': email, 'firstname': firstname, 'lastname': lastname,
254 'active': attrs.get('active', True), 'admin': False
255 }
256 # raises UserCreationError if it's not allowed
257 check_allowed_create_user(form_data, cur_user)
218
258
219 try:
259 try:
220 new_user = User()
260 new_user = User()
221 username = username.lower()
261 username = username.lower()
222 # add ldap account always lowercase
262 # add ldap account always lowercase
223 new_user.username = username
263 new_user.username = username
224 new_user.password = get_crypt_password(password)
264 new_user.password = password
225 new_user.api_key = generate_api_key(username)
265 new_user.api_key = generate_api_key(username)
226 new_user.email = attrs['email'] or generate_email(username)
266 new_user.email = email
227 new_user.active = attrs.get('active', True)
267 new_user.active = active
228 new_user.ldap_dn = safe_unicode(user_dn)
268 new_user.ldap_dn = safe_unicode(user_dn)
229 new_user.name = attrs['name']
269 new_user.name = firstname
230 new_user.lastname = attrs['lastname']
270 new_user.lastname = lastname
231
232 self.sa.add(new_user)
271 self.sa.add(new_user)
233
272
234 from rhodecode.lib.hooks import log_create_user
235 log_create_user(new_user.get_dict(), cur_user)
273 log_create_user(new_user.get_dict(), cur_user)
236 return new_user
274 return new_user
237 except (DatabaseError,):
275 except (DatabaseError,):
@@ -6,7 +6,16 b''
6 </%def>
6 </%def>
7
7
8 <div id="register">
8 <div id="register">
9
9 <div class="flash_msg">
10 <% messages = h.flash.pop_messages() %>
11 % if messages:
12 <ul id="flash-messages">
13 % for message in messages:
14 <li class="${message.category}_msg">${message}</li>
15 % endfor
16 </ul>
17 % endif
18 </div>
10 <div class="title top-left-rounded-corner top-right-rounded-corner">
19 <div class="title top-left-rounded-corner top-right-rounded-corner">
11 <h5>${_('Sign Up to')} ${c.rhodecode_name}</h5>
20 <h5>${_('Sign Up to')} ${c.rhodecode_name}</h5>
12 </div>
21 </div>
General Comments 0
You need to be logged in to leave comments. Login now