Wiki source code of Registration

Last modified by teamwire004 on 2025/04/01 07:23

Show last authors
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 ##
21 #set ($registrationConfig = $NULL)
22 #_loadConfig($registrationConfig)
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($mainFields = [])
121
122 ## The first name field.
123 #set($field =
124 {'name' : 'register_first_name',
125 'label' : $services.localization.render('core.register.firstName'),
126 'params' : {
127 'type' : 'text',
128 'size' : '60',
129 'autocomplete' : 'given-name'
130 }
131 })
132 #set($discard = $mainFields.add($field))
133 ##
134 ## The last name field.
135 #set($field =
136 {'name' : 'register_last_name',
137 'label' : $services.localization.render('core.register.lastName'),
138 'params' : {
139 'type' : 'text',
140 'size' : '60',
141 'autocomplete' : 'family-name'
142 }
143 })
144 #set($discard = $mainFields.add($field))
145 ## The user name field, mandatory and programmatically checked to make sure the username doesn't exist.
146 #set($field =
147 {'name' : 'xwikiname',
148 'label' : $services.localization.render('core.register.username'),
149 'params' : {
150 'type' : 'text',
151 'onfocus' : 'prepareName(document.forms.register);',
152 'size' : '60',
153 'autocomplete' : 'username'
154 },
155 'validate' : {
156 'mandatory' : {
157 'failureMessage' : $services.localization.render('core.validation.required.message')
158 },
159 'programmaticValidation' : {
160 'code' : '#nameAvailable($request.get("xwikiname"))',
161 'failureMessage' : $services.localization.render('core.register.userAlreadyExists')
162 }
163 }
164 })
165 #set($discard = $mainFields.add($field))
166 ## Make sure the chosen user name is not already taken
167 ## This macro is called by programmaticValidation for xwikiname (above)
168 #macro (nameAvailable, $name)
169 #if ($xwiki.exists("$userSpace$name"))
170 failed
171 #end
172 #end
173 ##
174 ##The password field, mandatory and must be at least 6 characters long.
175 ##The confirm password field, mandatory, must match password field, and must also be 6+ characters long.
176 #definePasswordFields($mainFields, 'register_password', 'register2_password', $registrationConfig.passwordOptions)
177 ##
178 ## The email address field, regex checked with an email pattern. Mandatory if registration uses email verification
179 #set($field =
180 {'name' : 'register_email',
181 'label' : $services.localization.render('core.register.email'),
182 'params' : {
183 'type' : 'text',
184 'size' : '60',
185 'autocomplete' : 'email'
186 },
187 'validate' : {
188 'regex' : {
189 'pattern' : '/^([^@\s]+)@((?:[-a-zA-Z0-9]+\.)+[a-zA-Z]{2,})$/',
190 'failureMessage' : $services.localization.render('xe.admin.registration.invalidEmail')
191 }
192 }
193 })
194 #if($registrationConfig.useEmailVerification)
195 #set($field.validate.mandatory = {'failureMessage' : $services.localization.render('core.validation.required.message')})
196 #end
197 #set($discard = $mainFields.add($field))
198 ##
199 #*********
200 ## Uncomment this code to see an example of how you can easily add a field to the registration page
201 ## NOTE: In order to save the favorite color in the "doAfterRegistration" hook, this page must be
202 ## saved by an administrator and can not self sandboxing.
203 #set($sandbox = false)
204 #set($field =
205 {'name' : 'favorite_color',
206 'label' : 'What is your favorite color',
207 'params' : {
208 'type' : 'text',
209 'size' : '60'
210 },
211 'validate' : {
212 'mandatory' : {
213 'failureMessage' : $services.localization.render('core.validation.required.message')
214 },
215 'regex' : {
216 'pattern' : '/^green$/',
217 'failureMessage' : 'You are not cool enough to register here.'
218 },
219 'fieldOkayMessage' : 'You are awesome.'
220 },
221 'doAfterRegistration' : '#saveFavoriteColor()'
222 })
223 #set($discard = $mainFields.add($field))
224 ## Save the user's favorite color on their user page.
225 #macro(saveFavoriteColor)
226 #set($xwikiname = $request.get('xwikiname'))
227 #set($userDoc = $xwiki.getDocument("$userSpace$xwikiname"))
228 $userDoc.setContent("$userDoc.getContent() ${xwikiname}'s favorite color is $request.get('favorite_color')!")
229 ## The user (who is not yet logged in) can't save documents so saveWithProgrammingRights
230 ## will save the document as long as the user who last saved this registration page has programming rights.
231 $userDoc.saveWithProgrammingRights("Saved favorite color from registration form.")
232 #end
233 *********###
234 ##
235 ## To disable the CAPTCHA on this page, comment out the next entry.
236 ## The CAPTCHA, not really an input field but still defined the same way.
237 #if($services.captcha
238 && !$invited
239 && $xcontext.getUser() == "XWiki.XWikiGuest"
240 && $registrationConfig.requireCaptcha)
241 ## The CAPTCHA field, programmatically checked to make sure the CAPTCHA is right.
242 ## Not checked by javascript because javascript can't check the CAPTCHA and the Ok message because it passes the
243 ## mandatory test is misleading.
244 ## Also, not filled back in if there is an error ('noReturn').
245 #set($field =
246 {'name' : 'captcha_placeholder',
247 'label' : $services.localization.render('core.captcha.label'),
248 'skipLabelFor' : true,
249 'type' : 'html',
250 'html' : "<span class='xHint'>$escapetool.xml($services.localization.render('core.captcha.instruction'))
251 </span> $!{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 = $mainFields.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 = $mainFields.add($field))
271 #set($fields = $mainFields)
272 ##
273 #######################################################################
274 ## The Code.
275 #######################################################################
276 ##
277 ## This application's HTML is dynamically generated and editing in WYSIWYG would not work
278 #if($xcontext.getAction() == 'edit')
279 $response.sendRedirect("$xwiki.getURL($doc.getFullName(), 'edit')?editor=wiki")
280 #end
281 ##
282 ## If this document has PR and is not included from another document then it's author should be set to Guest
283 ## for the duration of it's execution in order to improve security.
284 ## Note we compare document ids because
285 #if($sandbox
286 && $xcontext.hasProgrammingRights()
287 && $xcontext.getDoc().getDocumentReference().equals($xwiki.getDocument($documentName).getDocumentReference()))
288 ##
289 $xcontext.dropPermissions()##
290 #end
291 ##
292 ## Access level to register must be explicitly checked because it is only checked in XWiki.prepareDocuments
293 ## and this page is accessible through view action.
294 #if(!$xcontext.hasAccessLevel('register', 'XWiki.XWikiPreferences'))
295 ## Make an exception if another document with programming permission (Invitation app) has included this
296 ## document and set $invited to true.
297 #if(!$invited || !$xcontext.hasProgrammingRights())
298 $response.sendRedirect("$xwiki.getURL($doc.getFullName(), 'login')")
299 #end
300 #end
301 ##
302 ## Display the heading
303 $registrationConfig.heading
304 ## If the submit button has been pressed, then we test the input and maybe create the user.
305 #if($request.getParameter('xwikiname'))
306 ## Do server side validation of input fields.
307 ## This will output messages if something goes wrong, nothing if everything is alright.
308 ## We need to trim the output so that we can keep indentations in the validation script.
309 #set ($validationText = $stringtool.trim("#validateFields($fields, $request)"))
310 $validationText##
311 ## If server side validation was successful, create the user
312 #if($allFieldsValid)
313 #createUser($fields, $request, $response, $doAfterRegistration)
314 #end
315 #end
316 ## If the registration was not successful or if the user hasn't submitted the info yet
317 ## Then we display the registration form.
318 #if(!$registrationDone)
319 $registrationConfig.welcomeMessage
320
321 {{html clean="false"}}
322 <form id="register" action="$xwiki.relativeRequestURL" method="post" class="xform half">
323 <div class="hidden">
324 #if ($request.xpage == 'registerinline')
325 #skinExtensionHooks
326 #end
327 #set ($userDirectoryReference = $services.model.createDocumentReference('', 'Main', 'UserDirectory'))
328 #if ($xwiki.exists($userDirectoryReference))
329 <input type="hidden" name="parent" value="$!{services.model.serialize($userDirectoryReference, 'default')}" />
330 #end
331 </div>
332 ## Note that the macro inject the form_token field.
333 #generateHtml($mainFields, $request, 'false')
334 <input type="hidden" name="form_token" value="$services.csrf.getToken()" />
335 #generateJavascript($fields)
336 <p class="buttons">
337 <span class="buttonwrapper">
338 <input type="submit" value="$services.localization.render('core.register.submit')" class="button"/>
339 </span>
340 </p>
341 </form>
342 {{/html}}
343
344 ##
345 ## Allow permitted users to configure this application.
346 #if($xcontext.getUser() != 'XWiki.XWikiGuest' && $xcontext.hasAccessLevel("edit", $documentName))
347 [[{{translation key="xe.admin.registration.youCanConfigureRegistrationHere"/}}>>XWiki.XWikiPreferences?section=Registration&editor=globaladmin#HCustomizeXWikiRegistration]]
348 {{html}}<a href="$xwiki.getURL($documentName, 'edit', 'editor=wiki')">$services.localization.render('xe.admin.registration.youCanConfigureRegistrationFieldsHere')</a>{{/html}}
349 #end
350 #end
351 #else
352 ## The registration is not allowed on the subwiki
353 ## Redirecting to main wiki's registration page since local user registration is not allowed.
354 #set($mainWikiRegisterPageReference = $services.model.createDocumentReference($services.wiki.mainWikiId, 'XWiki', 'Register'))
355 #set($temp = $response.sendRedirect($xwiki.getURL($mainWikiRegisterPageReference, 'register', $request.queryString)))
356 #end
357 ##
358 #*
359 * Create the user.
360 * Calls $xwiki.createUser to create a new user.
361 *
362 * @param $request An XWikiRequest object which made the register request.
363 * @param $response The XWikiResponse object to send any redirects to.
364 * @param $doAfterRegistration code block to run after registration completes successfully.
365 *###
366 #macro(createUser, $fields, $request, $response, $doAfterRegistration)
367 ## CSRF check
368 #if(${services.csrf.isTokenValid("$!{request.getParameter('form_token')}")})
369 ## See if email verification is required and register the user.
370 #if($xwiki.getXWikiPreferenceAsInt('use_email_verification', 0) == 1)
371 #set($reg = $xwiki.createUser(true))
372 #else
373 #set($reg = $xwiki.createUser(false))
374 #end
375 #else
376 $response.sendRedirect("$!{services.csrf.getResubmissionURL()}")
377 #end
378 ##
379 ## Handle output from the registration.
380 #if($reg && $reg <= 0)
381 {{error}}
382 #if($reg == -2)
383 {{translation key="core.register.passwordMismatch"/}}
384 ## -3 means username taken, -8 means username is superadmin name
385 #elseif($reg == -3 || $reg == -8)
386 {{translation key="core.register.userAlreadyExists"/}}
387 #elseif($reg == -4)
388 {{translation key="core.register.invalidUsername"/}}
389 #elseif ($reg == -9)
390 {{translation key="core.register.invalidCaptcha"/}}
391 ## Note that -10 is reserved already (see api.XWiki#createUser)
392 #elseif($reg == -11)
393 {{translation key="core.register.mailSenderWronglyConfigured"/}}
394 #else
395 {{translation key="core.register.registerFailed" parameters="$reg"/}}
396 #end
397 {{/error}}
398 #elseif($reg)
399 ## Registration was successful
400 #set($registrationDone = true)
401 ##
402 ## If there is any thing to "doAfterRegistration" then do it.
403 #foreach($field in $fields)
404 #if($field.get('doAfterRegistration'))
405 #evaluate($field.get('doAfterRegistration'))
406 #end
407 #end
408 ## If there is a "global" doAfterRegistration, do that as well.
409 ## Calling toString() on a #define block will execute it and we discard the result.
410 #set($discard = $doAfterRegistration.toString())
411 ##
412 ## Define some strings which may be used by autoLogin or loginButton
413 #set($userName = $!request.get('xwikiname'))
414 #set($password = $!request.get('register_password'))
415 #set($loginURL = $xwiki.getURL($loginPage, $loginAction))
416 #if("$!request.getParameter($redirectParam)" != '')
417 #set($redirect = $request.getParameter($redirectParam))
418 #else
419 #set($redirect = $registrationConfig.defaultRedirect)
420 #end
421 ## Display a "registration successful" message
422 ## Define some strings which may be used by the welcome message
423 #set($firstName = $!request.get('register_first_name'))
424 #set($lastName = $!request.get('register_last_name'))
425 #evaluate($registrationConfig.registrationSuccessMessage)
426
427 ## Empty line prevents message from being forced into a <p> block.
428
429 ## Give the user a login button which posts their username and password to loginsubmit
430 #if($registrationConfig.loginButton)
431
432 {{html clean=false wiki=false}}
433 <form id="loginForm" action="$loginURL" method="post">
434 <div class="centered">
435 <input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
436 <input id="j_username" name="j_username" type="hidden" value="$escapetool.xml($!userName)" />
437 <input id="j_password" name="j_password" type="hidden" value="$escapetool.xml($!password)" />
438 <input id="$redirectParam" name="$redirectParam" type="hidden" value="$escapetool.xml($redirect)" />
439 <span class="buttonwrapper">
440 <input type="submit" value="$services.localization.render('login')" class="button"/>
441 </span>
442 #set ($mainPage = $services.wiki.currentWikiDescriptor.mainPageReference)
443 #if ($xwiki.checkAccess($mainPage, 'view'))
444 <span class="buttonwrapper">
445 <a href="$!xwiki.getURL($mainPage)" rel="home" class="button secondary">
446 $services.localization.render('core.register.successful.backtohome')
447 </a>
448 </span>
449 #end
450 </div>
451 </form>
452 ## We don't want autoLogin if we are administrators adding users...
453 #if ($registrationConfig.autoLogin && $request.xpage != 'registerinline')
454 <script>
455 document.observe('xwiki:dom:loaded', function() {
456 document.forms['loginForm'].submit();
457 });
458 </script>
459 #end
460 {{/html}}
461
462 #end
463 #end
464 ##
465 #end## createUser Macro
466 {{/velocity}}