Wiki source code of Registration

Version 3.1 by teamwire004 on 2024/07/12 13:06

Hide last authors
teamwire-admin 1.1 1 {{template name="register_macros.vm"/}}
2
3 {{velocity}}
4 ## The registration is enabled:
5 ## - on the main wiki
6 ## - on a subwiki if there is no service "$services.wiki.user"
7 ## - on a subwiki where the user scope allows local users
8 #if($xcontext.isMainWiki() || "$!services.wiki.user" == '' || $services.wiki.user.getUserScope() != "GLOBAL_ONLY")
9 ## These are defined in other places around XWiki, changing them here will result in undefined behavior.
10 #set($redirectParam = 'xredirect')
11 #set($userSpace = 'XWiki.')
12 #set($loginPage = 'XWiki.XWikiLogin')
13 #set($loginAction = 'loginsubmit')
14 ##
15 #set($documentName = 'XWiki.Registration')
16 ##
17 ## Security measure:
18 ## If this document is changed such that it must have programming permission in order to run, change this to false.
19 #set($sandbox = true)
20 ##
teamwire004 3.1 21 #set ($registrationConfig = $NULL)
22 #_loadConfig($registrationConfig)
teamwire-admin 1.1 23 ##
24 #*
25 * You may include this document in other documents using {{include reference="XWiki.Registration"/}}
26 * To specify that the user is invited and should be allowed to register even if Guest does not have permission to
27 * register, set $invited to true. NOTE: The including script must have programming permission to do this.
28 *
29 * To specify some code which should run after registration is successfully completed, set
30 * $doAfterRegistration to a define block of velocity code like so:
31 * #define($doAfterRegistration)
32 * some code
33 * #end
34 * Output from running this code will not be printed.
35 *
36 * The fields which will be seen on the registration page are defined here.
37 * $fields is an array and each field is a Map. The names shown below are Map keys.
38 *
39 * Each field must have:
40 * name - this is the name of the field, it will be the value for "name" and "id"
41 *
42 * Each field may have:
43 * label - this String will be written above the field.
44 *
45 * tag - the HTML tag which will be created, default is <input>, may also be a non form tag such as <img>
46 *
47 * params - a Map, each key value pair will be in the html tag. eg: {"size" : "30"} becomes <input size=30...
48 *
49 * validate a Map describing how to validate the field, validation is done in javascript then redone in velocity
50 * | for security and because not everyone has javascript.
51 * |
52 * +-mandatory (Optional) - Will fail if the field is not filled in.
53 * | +-failureMessage (Required) - The message to display if the field is not filled in.
54 * | +-noscript (Optional) - will not be checked by javascript
55 * |
56 * +-regex (Optional) - Will validate the field using a regular expression.
57 * | | because of character escaping, you must provide a different expression for the
58 * | | javascript validation and the server side validation. Both javascript and server side
59 * | | validation are optional, but if you provide neither, then your field will not be validated.
60 * | |
61 * | +-failureMessage (Optional) - The message to display if the regex evaluation returns false.
62 * | +-jsFailureMessage (Optional) - The message for Javascript to display if regex fails.
63 * | | If jsFailureMessage is not defined Javascript uses failureMessage.
64 * | | NOTE: Javascript injects the failure message using createTextNode so &lt; will
65 * | | be displayed as &lt;
66 * | |
67 * | +-pattern (Optional) - The regular expression to test the input at the server side, it's important to use
68 * | | this if you need to validate the field for security reasons, also it is good because not
69 * | | all browsers use javascript or have it enabled.
70 * | |
71 * | +-jsPattern (Optional) - The regular expression to use for client side, you can use escaped characters to avoid
72 * | | them being parsed as HTML or javascript. To get javascript to unescape characters use:
73 * | | {"jsPattern" : "'+unescape('%5E%5B%24')+'"}
74 * | | NOTE: If no jsPattern is specified, the jsValidator will try to validate
75 * | | using the server pattern.
76 * | |
77 * | +-noscript (Optional) - will not be checked by javascript
78 * |
79 * +-mustMatch (Optional) - Will fail if the entry into the field is not the same as the entry in another field.
80 * | | Good for password confirmation.
81 * | |
82 * | +-failureMessage (Required) - The message to display if the field doesn't match the named field.
83 * | +-name (Required) - The name of the field which this field must match.
84 * | +-noscript (Optional) - will not be checked by javascript
85 * |
86 * +-programmaticValidation (Optional) - This form of validation executes a piece of code which you give it and
87 * | | if the code returns the word "failed" then it gives the error message.
88 * | | Remember to put the code in singel quotes ('') because you want the value
89 * | | of 'code' to equal the literal code, not the output from running it.
90 * | |
91 * | +-code (Required) - The code which will be executed to test whether the field is filled in correctly.
92 * | +-failureMessage (Required) - The message which will be displayed if evaluating the code returns "false"
93 * |
94 * +-fieldOkayMessage (Optional) - The message which is displayed by LiveValidation when a field is validated as okay.
95 * If not specified, will be $defaultFieldOkayMessage
96 *
97 * noReturn - If this is specified, the field will not be filled in if there is an error and the user has to fix their
98 * registration information. If you don't want a password to be passed back in html then set this true
99 * for the password fields. Used for the captcha because it makes no sense to pass back a captcha answer.
100 *
101 * doAfterRegistration - Some Velocity code which will be executed after a successfull registration.
102 * This is used in the favorite color example.
103 * Remember to put the code in singel quotes ('') because you want the 'code' entry to equal the literal
104 * code, not the output from running it.
105 *
106 * Each field may not have: (reserved names)
107 * error - This is used to pass back any error message from the server side code.
108 *
109 * NOTE: This template uses a registration method which requires:
110 * * register_first_name
111 * * register_last_name
112 * * xwikiname
113 * * register_password
114 * * register2_password
115 * * register_email
116 * * template
117 * Removing or renaming any of these fields will result in undefined behavior.
118 *
119 *###
120 #set($fields = [])
121 ##
122 ## The first name field, no checking.
123 #set($field =
124 {'name' : 'register_first_name',
125 'label' : $services.localization.render('core.register.firstName'),
126 'params' : {
127 'type' : 'text',
teamwire004 3.1 128 'size' : '60',
129 'autocomplete' : 'given-name'
teamwire-admin 1.1 130 }
131 })
132 #set($discard = $fields.add($field))
133 ##
134 ## The last name field, no checking.
135 #set($field =
136 {'name' : 'register_last_name',
137 'label' : $services.localization.render('core.register.lastName'),
138 'params' : {
139 'type' : 'text',
teamwire004 3.1 140 'size' : '60',
141 'autocomplete' : 'family-name'
teamwire-admin 1.1 142 }
143 })
144 #set($discard = $fields.add($field))
145 ##
146 ## The user name field, mandatory and programmatically checked to make sure the username doesn't exist.
147 #set($field =
148 {'name' : 'xwikiname',
149 'label' : $services.localization.render('core.register.username'),
150 'params' : {
151 'type' : 'text',
152 'onfocus' : 'prepareName(document.forms.register);',
teamwire004 3.1 153 'size' : '60',
154 'autocomplete' : 'username'
teamwire-admin 1.1 155 },
156 'validate' : {
157 'mandatory' : {
158 'failureMessage' : $services.localization.render('core.validation.required.message')
159 },
160 'programmaticValidation' : {
161 'code' : '#nameAvailable($request.get("xwikiname"))',
162 'failureMessage' : $services.localization.render('core.register.userAlreadyExists')
163 }
164 }
165 })
166 #set($discard = $fields.add($field))
167 ## Make sure the chosen user name is not already taken
168 ## This macro is called by programmaticValidation for xwikiname (above)
169 #macro (nameAvailable, $name)
170 #if ($xwiki.exists("$userSpace$name"))
171 failed
172 #end
173 #end
174 ##
175 ##The password field, mandatory and must be at least 6 characters long.
176 ##The confirm password field, mandatory, must match password field, and must also be 6+ characters long.
teamwire004 3.1 177 #definePasswordFields($fields, 'register_password', 'register2_password', $registrationConfig.passwordOptions)
teamwire-admin 1.1 178 ##
179 ## The email address field, regex checked with an email pattern. Mandatory if registration uses email verification
180 #set($field =
181 {'name' : 'register_email',
182 'label' : $services.localization.render('core.register.email'),
183 'params' : {
184 'type' : 'text',
teamwire004 3.1 185 'size' : '60',
186 'autocomplete' : 'email'
teamwire-admin 1.1 187 },
188 'validate' : {
189 'regex' : {
190 'pattern' : '/^([^@\s]+)@((?:[-a-zA-Z0-9]+\.)+[a-zA-Z]{2,})$/',
191 'failureMessage' : $services.localization.render('xe.admin.registration.invalidEmail')
192 }
193 }
194 })
teamwire004 3.1 195 #if($registrationConfig.useEmailVerification)
teamwire-admin 1.1 196 #set($field.validate.mandatory = {'failureMessage' : $services.localization.render('core.validation.required.message')})
197 #end
198 #set($discard = $fields.add($field))
199 ##
200 #*********
201 ## Uncomment this code to see an example of how you can easily add a field to the registration page
202 ## NOTE: In order to save the favorite color in the "doAfterRegistration" hook, this page must be
203 ## saved by an administrator and can not self sandboxing.
204 #set($sandbox = false)
205 #set($field =
206 {'name' : 'favorite_color',
207 'label' : 'What is your favorite color',
208 'params' : {
209 'type' : 'text',
210 'size' : '60'
211 },
212 'validate' : {
213 'mandatory' : {
214 'failureMessage' : $services.localization.render('core.validation.required.message')
215 },
216 'regex' : {
217 'pattern' : '/^green$/',
218 'failureMessage' : 'You are not cool enough to register here.'
219 },
220 'fieldOkayMessage' : 'You are awesome.'
221 },
222 'doAfterRegistration' : '#saveFavoriteColor()'
223 })
224 #set($discard = $fields.add($field))
225 ## Save the user's favorite color on their user page.
226 #macro(saveFavoriteColor)
227 #set($xwikiname = $request.get('xwikiname'))
228 #set($userDoc = $xwiki.getDocument("$userSpace$xwikiname"))
229 $userDoc.setContent("$userDoc.getContent() ${xwikiname}'s favorite color is $request.get('favorite_color')!")
230 ## The user (who is not yet logged in) can't save documents so saveWithProgrammingRights
231 ## will save the document as long as the user who last saved this registration page has programming rights.
232 $userDoc.saveWithProgrammingRights("Saved favorite color from registration form.")
233 #end
234 *********###
235 ##
236 ## To disable the CAPTCHA on this page, comment out the next entry.
237 ## The CAPTCHA, not really an input field but still defined the same way.
238 #if($services.captcha
239 && !$invited
240 && $xcontext.getUser() == "XWiki.XWikiGuest"
teamwire004 3.1 241 && $registrationConfig.requireCaptcha)
teamwire-admin 1.1 242 ## The CAPTCHA field, programmatically checked to make sure the CAPTCHA is right.
243 ## Not checked by javascript because javascript can't check the CAPTCHA and the Ok message because it passes the
244 ## mandatory test is misleading.
245 ## Also, not filled back in if there is an error ('noReturn').
246 #set($field =
247 {'name' : 'captcha_placeholder',
248 'label' : $services.localization.render('core.captcha.instruction'),
249 'skipLabelFor' : true,
250 'type' : 'html',
251 'html' : "$!{services.captcha.default.display()}",
252 'validate' : {
253 'programmaticValidation' : {
254 'code' : '#if (!$services.captcha.default.isValid())failed#end',
255 'failureMessage' : $services.localization.render('core.captcha.captchaAnswerIsWrong')
256 }
257 },
258 'noReturn' : true
259 })
260 #set($discard = $fields.add($field))
261 #end
262 ## Pass the redirect parameter on so that the login page may redirect to the right place.
263 ## Not necessary in Firefox 3.0.10 or Opera 9.64, I don't know about IE or Safari.
264 #set($field =
265 {'name' : $redirectParam,
266 'params' : {
267 'type' : 'hidden'
268 }
269 })
270 #set($discard = $fields.add($field))
271 ##
272 #######################################################################
273 ## The Code.
274 #######################################################################
275 ##
276 ## This application's HTML is dynamically generated and editing in WYSIWYG would not work
277 #if($xcontext.getAction() == 'edit')
278 $response.sendRedirect("$xwiki.getURL($doc.getFullName(), 'edit')?editor=wiki")
279 #end
280 ##
281 ## If this document has PR and is not included from another document then it's author should be set to Guest
282 ## for the duration of it's execution in order to improve security.
283 ## Note we compare document ids because
284 #if($sandbox
285 && $xcontext.hasProgrammingRights()
286 && $xcontext.getDoc().getDocumentReference().equals($xwiki.getDocument($documentName).getDocumentReference()))
287 ##
288 $xcontext.dropPermissions()##
289 #end
290 ##
291 ## Access level to register must be explicitly checked because it is only checked in XWiki.prepareDocuments
292 ## and this page is accessible through view action.
293 #if(!$xcontext.hasAccessLevel('register', 'XWiki.XWikiPreferences'))
294 ## Make an exception if another document with programming permission (Invitation app) has included this
295 ## document and set $invited to true.
296 #if(!$invited || !$xcontext.hasProgrammingRights())
297 $response.sendRedirect("$xwiki.getURL($doc.getFullName(), 'login')")
298 #end
299 #end
300 ##
301 ## Display the heading
teamwire004 3.1 302 $registrationConfig.heading
teamwire-admin 1.1 303 ## If the submit button has been pressed, then we test the input and maybe create the user.
304 #if($request.getParameter('xwikiname'))
305 ## Do server side validation of input fields.
306 ## This must not be in a #set directive as it will output messages if something goes wrong.
307 #validateFields($fields, $request)
308 ## If server side validation was successfull, create the user
309 #if($allFieldsValid)
310 #createUser($fields, $request, $response, $doAfterRegistration)
311 #end
312 #end
313 ## If the registration was not successful or if the user hasn't submitted the info yet
314 ## Then we display the registration form.
315 #if(!$registrationDone)
teamwire004 3.1 316 $registrationConfig.welcomeMessage
teamwire-admin 1.1 317
318 {{html clean="false"}}
319 <form id="register" action="$xwiki.relativeRequestURL" method="post" class="xform half">
320 <div class="hidden">
321 #if ($request.xpage == 'registerinline')
322 #skinExtensionHooks
323 #end
324 #set ($userDirectoryReference = $services.model.createDocumentReference('', 'Main', 'UserDirectory'))
325 #if ($xwiki.exists($userDirectoryReference))
326 <input type="hidden" name="parent" value="$!{services.model.serialize($userDirectoryReference, 'default')}" />
327 #end
328 </div>
teamwire004 2.1 329 ## Note that the macro inject the form_token field.
teamwire-admin 1.1 330 #generateHtml($fields, $request)
331 <p class="buttons">
332 <span class="buttonwrapper">
333 <input type="submit" value="$services.localization.render('core.register.submit')" class="button"/>
334 </span>
335 </p>
336 </form>
337 {{/html}}
338
339 ##
340 ## Allow permitted users to configure this application.
341 #if($xcontext.getUser() != 'XWiki.XWikiGuest' && $xcontext.hasAccessLevel("edit", $documentName))
342 [[{{translation key="xe.admin.registration.youCanConfigureRegistrationHere"/}}>>XWiki.XWikiPreferences?section=Registration&editor=globaladmin#HCustomizeXWikiRegistration]]
343 {{html}}<a href="$xwiki.getURL($documentName, 'edit', 'editor=wiki')">$services.localization.render('xe.admin.registration.youCanConfigureRegistrationFieldsHere')</a>{{/html}}
344 #end
345 #end
346 #else
347 ## The registration is not allowed on the subwiki
348 ## Redirecting to main wiki's registration page since local user registration is not allowed.
349 #set($mainWikiRegisterPageReference = $services.model.createDocumentReference($services.wiki.mainWikiId, 'XWiki', 'Register'))
350 #set($temp = $response.sendRedirect($xwiki.getURL($mainWikiRegisterPageReference, 'register', $request.queryString)))
351 #end
352 ##
353 #*
354 * Create the user.
355 * Calls $xwiki.createUser to create a new user.
356 *
357 * @param $request An XWikiRequest object which made the register request.
358 * @param $response The XWikiResponse object to send any redirects to.
359 * @param $doAfterRegistration code block to run after registration completes successfully.
360 *###
361 #macro(createUser, $fields, $request, $response, $doAfterRegistration)
362 ## CSRF check
363 #if(${services.csrf.isTokenValid("$!{request.getParameter('form_token')}")})
364 ## See if email verification is required and register the user.
365 #if($xwiki.getXWikiPreferenceAsInt('use_email_verification', 0) == 1)
366 #set($reg = $xwiki.createUser(true))
367 #else
368 #set($reg = $xwiki.createUser(false))
369 #end
370 #else
371 $response.sendRedirect("$!{services.csrf.getResubmissionURL()}")
372 #end
373 ##
374 ## Handle output from the registration.
375 #if($reg && $reg <= 0)
376 {{error}}
377 #if($reg == -2)
378 {{translation key="core.register.passwordMismatch"/}}
379 ## -3 means username taken, -8 means username is superadmin name
380 #elseif($reg == -3 || $reg == -8)
381 {{translation key="core.register.userAlreadyExists"/}}
382 #elseif($reg == -4)
383 {{translation key="core.register.invalidUsername"/}}
teamwire004 3.1 384 #elseif ($reg == -9)
385 {{translation key="core.register.invalidCaptcha"/}}
386 ## Note that -10 is reserved already (see api.XWiki#createUser)
teamwire-admin 1.1 387 #elseif($reg == -11)
388 {{translation key="core.register.mailSenderWronglyConfigured"/}}
389 #else
390 {{translation key="core.register.registerFailed" parameters="$reg"/}}
391 #end
392 {{/error}}
393 #elseif($reg)
394 ## Registration was successful
395 #set($registrationDone = true)
396 ##
397 ## If there is any thing to "doAfterRegistration" then do it.
398 #foreach($field in $fields)
399 #if($field.get('doAfterRegistration'))
400 #evaluate($field.get('doAfterRegistration'))
401 #end
402 #end
403 ## If there is a "global" doAfterRegistration, do that as well.
404 ## Calling toString() on a #define block will execute it and we discard the result.
405 #set($discard = $doAfterRegistration.toString())
406 ##
407 ## Define some strings which may be used by autoLogin or loginButton
408 #set($userName = $!request.get('xwikiname'))
409 #set($password = $!request.get('register_password'))
410 #set($loginURL = $xwiki.getURL($loginPage, $loginAction))
411 #if("$!request.getParameter($redirectParam)" != '')
412 #set($redirect = $request.getParameter($redirectParam))
413 #else
teamwire004 3.1 414 #set($redirect = $registrationConfig.defaultRedirect)
teamwire-admin 1.1 415 #end
416 ## Display a "registration successful" message
417
teamwire004 3.1 418 #evaluate($registrationConfig.registrationSuccessMessage)
teamwire-admin 1.1 419
420 ## Empty line prevents message from being forced into a <p> block.
421
422 ## Give the user a login button which posts their username and password to loginsubmit
teamwire004 3.1 423 #if($registrationConfig.loginButton)
teamwire-admin 1.1 424
425 {{html clean=false wiki=false}}
426 <form id="loginForm" action="$loginURL" method="post">
427 <div class="centered">
428 <input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
429 <input id="j_username" name="j_username" type="hidden" value="$escapetool.xml($!userName)" />
430 <input id="j_password" name="j_password" type="hidden" value="$escapetool.xml($!password)" />
431 <input id="$redirectParam" name="$redirectParam" type="hidden" value="$escapetool.xml($redirect)" />
432 <span class="buttonwrapper">
433 <input type="submit" value="$services.localization.render('login')" class="button"/>
434 </span>
435 </div>
436 </form>
437 ## We don't want autoLogin if we are administrators adding users...
teamwire004 3.1 438 #if ($registrationConfig.autoLogin && $request.xpage != 'registerinline')
teamwire004 2.1 439 <script>
teamwire-admin 1.1 440 document.observe('xwiki:dom:loaded', function() {
441 document.forms['loginForm'].submit();
442 });
443 </script>
444 #end
445 {{/html}}
446
447 #end
448 #end
449 ##
450 #end## createUser Macro
451 {{/velocity}}