/
Register.pm
executable file
·2431 lines (2084 loc) · 76.7 KB
/
Register.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# See bottom of file for license and copyright information
=begin TML
---+ package Foswiki::UI::Register
User registration handling.
=cut
package Foswiki::UI::Register;
use strict;
use warnings;
use Assert;
use Error qw( :try );
use Storable;
use Foswiki ();
use Foswiki::Form ();
use Foswiki::LoginManager ();
use Foswiki::OopsException ();
use Foswiki::Sandbox ();
use Foswiki::UI ();
BEGIN {
if ( $Foswiki::cfg{UseLocale} ) {
require locale;
import locale();
}
}
# Keys from the user data that should *not* be included in
# the user topic.
my %SKIPKEYS = (
'Photo' => 1,
'WikiName' => 1,
'LoginName' => 1,
'Password' => 1,
'Confirm' => 1,
'Email' => 1,
'AddToGroups' => 1,
'templatetopic' => 1,
);
my @requiredFields = qw(WikiName FirstName LastName Email);
=begin TML
---++ StaticMethod register_cgi( $session )
=register= command handler.
This method is designed to be
invoked via the =UI::run= method.
=cut
sub register_cgi {
my $session = shift;
# Register -> Verify -> Approve -> Finish
my $action = $session->{request}->param('action') || '';
# Dispatch the registration action
# CAUTION: Only routines intended to be called directly using the
# action parameter should be named _action_...
my $handler = "_action_$action";
if ( defined &$handler ) {
# absolute URL context for email generation
$session->enterContext('absolute_urls');
no strict 'refs';
&$handler($session);
use strict 'refs';
$session->leaveContext('absolute_urls');
}
else {
throw Foswiki::OopsException(
'attention',
web => $session->{webName},
topic => $session->{topicName},
def => 'unrecognized_action'
);
}
}
# Handler for 'register' action
sub _action_register {
my $session = shift;
# Check that the method was POST
my $query = $session->{request};
if ( $query
&& $query->method()
&& uc( $query->method() ) ne 'POST' )
{
throw Foswiki::OopsException(
'attention',
web => $session->{webName},
topic => $session->{topicName},
def => 'post_method_only',
params => ['register']
);
}
if ( !$session->inContext('registration_supported') ) {
throw Foswiki::OopsException(
'register',
web => $session->{webName},
topic => $session->{topicName},
def => 'registration_not_supported'
);
}
if ( !$Foswiki::cfg{Register}{EnableNewUserRegistration} ) {
throw Foswiki::OopsException(
'register',
web => $session->{webName},
topic => $session->{topicName},
def => 'registration_disabled'
);
}
Foswiki::UI::checkValidationKey($session);
_innerRegister($session);
if ( $Foswiki::cfg{Register}{NeedVerification} ) {
my $query = $session->{request};
my $data = _getDataFromQuery( $session->{users}, $query );
# Add some extra fields for compatibility with older registerconfirm templates
$data->{FirstLastName} = $data->{Name};
_requireConfirmation( $session, $data, 'Verification', 'confirm',
$data->{Email} );
}
elsif ( $Foswiki::cfg{Register}{NeedApproval} ) {
my $query = $session->{request};
my $data = _getDataFromQuery( $session->{users}, $query );
$data->{FirstLastName} = $data->{Name};
my $approvers = $Foswiki::cfg{Register}{Approvers}
|| $Foswiki::cfg{AdminUserWikiName};
_requireConfirmation( $session, $data, 'Approval', 'approve',
$approvers );
}
else {
# No need for confirmation
_complete( $session, undef, 1 );
}
}
# Handler for 'verify' action
sub _action_verify {
my $session = shift;
my $code = $session->{request}->param('code');
unless ($code) {
throw Error::Simple('verification failed: no verification code!');
}
my $data = _loadPendingRegistration( $session, $code );
if ( !exists $data->{Email} ) {
throw Foswiki::OopsException(
'register',
status => 200,
web => $Foswiki::cfg{UsersWebName},
topic => $data->{WikiName},
def => 'rego_not_found',
params => [$code]
);
}
throw Foswiki::OopsException(
'register',
def => 'bad_ver_code',
params => [ $code, 'Invalid verification code ' ]
) unless $data->{VerificationCode} eq $code;
delete $data->{VerificationCode};
_clearPendingRegistrationsForUser($code);
if ( $Foswiki::cfg{Register}{NeedApproval} ) {
my $approvers = $Foswiki::cfg{Register}{Approvers}
|| $Foswiki::cfg{AdminUserWikiName};
_requireConfirmation( $session, $data, 'Approval', 'approve',
$approvers );
}
else {
# No need for approval
_complete( $session, $data, 1 );
}
}
# Handle approval denial
sub _action_disapprove {
my $session = shift;
my $data = _checkApproval( $session, 0 );
$session->logger->log( 'warning',
"Registration denied: registration for $data->{WikiName} <$data->{Email}> was denied by $data->{Referee}"
);
# Display the form to optionally gather feedback and email the rejectee
throw Foswiki::OopsException(
'register',
status => 200,
web => $Foswiki::cfg{UsersWebName},
topic => $data->{WikiName},
def => 'rego_denied',
params => [ $data->{WikiName}, $data->{Email}, $data->{Referee} ]
);
}
# Handle approval confirmation
sub _action_approve {
my $session = shift;
my $data = _checkApproval( $session, 1 );
my $code = $session->{request}->param('code');
throw Foswiki::OopsException(
'register',
def => 'bad_ver_code',
params => [ $code, 'Invalid approval code ' ]
) unless $data->{ApprovalCode} eq $code;
delete $data->{ApprovalCode};
# SMELL: verify that someone is logged in, and they are allowed
# to approve this registration!
_complete( $session, $data, 0 );
throw Foswiki::OopsException(
'register',
status => 200,
web => $Foswiki::cfg{UsersWebName},
topic => $data->{WikiName},
topic => $data->{WikiName},
def => 'rego_approved',
params => [ $data->{WikiName} ]
);
}
# Handle approver action; either approve or deny
sub _checkApproval {
my ( $session, $approve ) = @_;
my $code = $session->{request}->param('code');
unless ($code) {
throw Error::Simple('approval failed: no approval code!');
}
if ( $code eq 'DENIED' ) {
# The registration has been denied; serve up denial feedback
my $data = {
EmailAddress => scalar( $session->{request}->param('email') ),
Referee => scalar( $session->{request}->param('referee') ),
WikiName => Foswiki::Sandbox::untaint(
scalar( $session->{request}->param('wikiname') )
|| 'UnknownUser',
\&Foswiki::Sandbox::validateTopicName
),
Feedback => scalar( $session->{request}->param('feedback') )
};
my $err = _sendEmail( $session, 'registerdenied', $data );
if ($err) {
$session->logger->log( 'warning',
"Registration rejected: registration_mail_failed - Email: $data->{EmailAddress}, Error $err"
);
throw Foswiki::OopsException(
'register',
def => 'registration_mail_failed',
web => $Foswiki::cfg{UsersWebName},
topic => $data->{WikiName},
params => [ $data->{EmailAddress}, $err ]
);
}
throw Foswiki::OopsException(
'register',
status => 200,
web => $Foswiki::cfg{UsersWebName},
topic => $data->{WikiName},
def => 'rego_denial',
params => [ $data->{WikiName}, $data->{EmailAddress} ]
);
}
# Must be logged in to approve
throw Foswiki::AccessControlException( 'APPROVE', $session->{user},
$session->{webName}, $session->{topicName}, 'Not logged in' )
unless $session->inContext('authenticated');
my $data = _loadPendingRegistration( $session, $code );
_clearPendingRegistrationsForUser($code);
if ( !exists $data->{Email} ) {
throw Foswiki::OopsException(
'register',
status => 200,
web => $Foswiki::cfg{UsersWebName},
topic => $data->{WikiName},
def => 'rego_not_found',
params => [$code]
);
}
# check if the user is already registered; if so, their registration
# must have been approved
my $cUID = $session->{users}->getCanonicalUserID( $data->{WikiName} );
if ( $cUID && $session->{users}->userExists($cUID) ) {
throw Foswiki::OopsException(
'register',
status => 200,
web => $Foswiki::cfg{UsersWebName},
topic => $data->{WikiName},
def => 'duplicate_activation',
params => [ $data->{WikiName} ]
);
}
# Record who is doing the approving
$data->{Referee} = $session->{users}->getWikiName( $session->{user} );
return $data;
}
# Handle password reset;
# SMELL: is this used any more? It should be going through =manage=.
sub _resetPassword {
my $session = shift;
if ( !$session->inContext('passwords_modifyable') ) {
throw Foswiki::OopsException(
'register',
web => $session->{webName},
topic => $session->{topicName},
def => 'passwords_disabled'
);
}
# resetpasswd calls checkValidationKey - don't check it here
require Foswiki::UI::Passwords;
Foswiki::UI::Passwords::resetpasswd($session);
# unaffected user, accessible by username.$verificationCode
}
my $b1 = "\t* ";
my $b2 = "\t$b1";
=begin TML
---++ StaticMethod bulkRegister($session)
Called by ManageCgiScript::bulkRegister (requires authentication) with
topic = the page with the entries on it.
NB. bulkRegister is invoked from ManageCgiScript. Why? Who knows.
Query parameters applying to all registrations:
* =LogTopic=: Name of the topic that is created / replaced with the results.
* =redirectto=: Topic displayed after registration is complete. (Defaults to !LogTopic).
* =templatetopic=: Default New user topic template name, defaults to NewUserTemplate. This topic name must exist either in %USERSWEB% or %SYSTEMWEB%
Note that the templatetopic can be set per user, but because the template topic is likely to have different fields
in it's respective form definition, and would require different table columns.
=cut
sub bulkRegister {
my $session = shift;
my $user = $session->{user};
my $topic = $session->{topicName};
my $web = $session->{webName};
my $userweb = $Foswiki::cfg{UsersWebName};
my $query = $session->{request};
# absolute URL context for email generation
$session->enterContext('absolute_urls');
my $settings = {};
unless ( $session->{users}->isAdmin($user) ) {
throw Foswiki::OopsException(
'accessdenied',
status => 403,
def => 'only_group',
web => $web,
topic => $topic,
params => [ $Foswiki::cfg{SuperAdminGroup} ]
);
}
# Validate
Foswiki::UI::checkValidationKey($session);
my $templateTopic = $query->param('templatetopic');
if ($templateTopic) {
$templateTopic = _validateTemplateTopic( $session, $templateTopic );
}
#-- Read the topic containing the table of people to be registered
my $meta = Foswiki::Meta->load( $session, $web, $topic );
unless ( $meta->getLoadedRev() ) {
throw Foswiki::OopsException(
'register',
def => 'bulk_reg_topic_missing',
web => $web,
topic => $topic,
params => ["!$web.$topic"]
);
}
my @fields;
my @data;
my $gotHdr = 0;
foreach my $line ( split( /\r?\n/, $meta->text() ) ) {
# unchecked implicit untaint OK - this function is for admins only
if ( $line =~ m/^\s*\|\s*(.*?)\s*\|\s*$/ ) {
if ($gotHdr) {
my $i = 0;
my %row = map { $fields[ $i++ ] => $_ } split( /\s*\|\s*/, $1 );
$row{templatetopic} = $templateTopic
unless ( $row{templatetopic} );
push( @data, \%row );
}
else {
foreach my $field ( split( /\s*\|\s*/, $1 ) ) {
$field =~ s/^[\s*]*(.*?)[\s*]*$/$1/;
$field =~ s/<.*?>//g; #strip any html markup from heading
$field = Foswiki::Form::fieldTitle2FieldName($field);
push( @fields, $field );
}
$gotHdr = 1;
}
}
}
my $log = "---+ Report for Bulk Register\n%TOC%\n";
# TODO: should check that the header row actually contains the
# required fields.
# TODO: and consider using MAKETEXT to enable translated tables.
my $genReset; # Flag set if any rows don't have a password
#-- Process each row, generate a log as we go
for ( my $n = 0 ; $n < scalar(@data) ; $n++ ) {
my $row = $data[$n];
$row->{errors} = '';
$row->{webName} = $userweb;
unless ( $row->{WikiName} ) {
$row->{WikiName} |= '';
$row->{errors} .= " Not registered: WikiName not entered.";
$row->{FAIL} = 1;
$log .= "---++ Failed to register user on row $n: no !WikiName\n";
next;
}
# If password column is empty, just delete them to avoid errors in validation.
# Passwords are generally sent as a bulk reset after registration.
unless ( defined $row->{Password} && length( $row->{Password} ) > 0 ) {
delete $row->{Password};
delete $row->{Confirm};
}
# If a password is provided but no Confirm column, just
# set Confirm to the password. Confirmation really doesn't make sense here,
unless ( exists $row->{Password} && exists $row->{Confirm} ) {
if ( exists $row->{Password} ) {
$row->{Confirm} = $row->{Password};
}
}
$log .= _registerSingleBulkUser( $session, \@fields, $row, $settings );
$genReset = 1 unless ( $row->{Password} || $row->{FAIL} );
}
my $tmpl = $session->templates->readTemplate('registermessages');
$log .= $session->templates->expandTemplate('bulkreg_report');
$log .= $session->templates->expandTemplate('bulkreg_summary_head');
my $rowtmpl = $session->templates->expandTemplate('bulkreg_summary_row');
foreach my $row (@data) {
my $ifield = $rowtmpl;
my $icon =
( $row->{FAIL} ? '%X%' : ( $row->{WARN} ? '%ICON{alert}%' : '%Y%' ) );
my $state =
( $row->{FAIL} ) ? 'disabled' : ( $row->{Password} ) ? '' : 'checked';
$ifield =~ s/\$state/$state/;
$ifield =~ s/\$flag/$icon/;
$ifield =~ s/\$wikiname/$row->{WikiName}/g;
$ifield =~ s/\$errors/$row->{errors}/;
$log .= $ifield;
}
$log .= $session->templates->expandTemplate('bulkreg_summary_foot');
my $logWeb;
my $logTopic = Foswiki::Sandbox::untaint(
scalar( $query->param('LogTopic') ),
\&Foswiki::Sandbox::validateTopicName
) || $topic . 'Result';
( $logWeb, $logTopic ) = $session->normalizeWebTopicName( '', $logTopic );
#-- Save the LogFile as designated, link back to the source topic
my $lmeta = Foswiki::Meta->new( $session, $logWeb, $logTopic, $log );
unless ( $lmeta->haveAccess('CHANGE') ) {
throw Foswiki::AccessControlException( 'CHANGE', $session->{user},
$logWeb, $logTopic, $Foswiki::Meta::reason );
}
$lmeta->put( 'TOPICPARENT', { name => $web . '.' . $topic } );
$lmeta->save();
$session->leaveContext('absolute_urls');
# Use Foswiki::redirectto to validate redirectto query param
# and fall back to the $logTopic if the param is not provided.
my $redirecturl = $session->redirectto($logTopic);
$session->redirect($redirecturl);
}
# Register a single user during a bulk registration process
sub _registerSingleBulkUser {
my ( $session, $fieldNames, $row, $settings ) = @_;
ASSERT($row) if DEBUG;
my $log = "---++ Registering $row->{WikiName}\n";
#-- Ensure every required field exists
# NB. LoginName is OPTIONAL
if ( _missingElements( $fieldNames, \@requiredFields ) ) {
$row->{errors} .= " Rejected: missing fields: "
. join( ' ', map { $_ . ' : ' . $row->{$_} } @$fieldNames );
$row->{FAIL} = 1;
$log .=
$b1
. join( ' ', map { $_ . ' : ' . $row->{$_} } @$fieldNames )
. ' does not contain the full set of required fields '
. join( ' ', @requiredFields ) . "\n";
return ( undef, $log );
}
my $tryError = '';
try {
#SMELL: Field Validations
# foreach my $field ( %$row ) {
# - validate with Users::validateRegistrationField( $field, $row->{$field} );
# - catch any errors to log
# Note, do this HERE and not in _validateRegistration.
# CGI registration validates earlier in _getDataFromQuery()
_validateRegistration( $session, $row, 0 );
}
catch Foswiki::OopsException with {
my $e = shift;
$row->{errors} .= "Validation failed: " . $e->{def};
$row->{FAIL} = 1;
$log .= '<blockquote>' . $e->stringify($session) . "</blockquote>\n";
$tryError = "$b1 Registration failed\n";
};
return $log . $tryError if ($tryError);
#-- Generation of the page is done from the {form} subhash,
# so align the two
$row->{form} = _makeFormFieldOrderMatch( $fieldNames, $row );
my $users = $session->{users};
my $cUID;
try {
# Add the user to the user management system. May throw an exception
$cUID = $users->addUser(
$row->{LoginName},
$row->{WikiName},
$session->inContext("passwords_modifyable")
? $row->{Password}
: undef,
$row->{Email}
);
$log .=
"$b1 $row->{WikiName} has been added to the password and user mapping managers\n";
if ( !$session->topicExists( $row->{webName}, $row->{WikiName} ) ) {
$log .= _createUserTopic( $session, $row );
}
else {
$log .= "$b1 Not writing user topic $row->{WikiName}\n";
$row->{errors} .= " User topic not written!";
$row->{WARN} = 1;
}
$users->setEmails( $cUID, $row->{Email} );
my $loginName = '';
$loginName = ' (' . $row->{LoginName} . ')'
if ( $Foswiki::cfg{Register}{AllowLoginName} );
$session->logger->log(
{
level => 'info',
action => 'bulkregister',
webTopic => $row->{webName} . '.' . $row->{WikiName},
extra => $row->{Email} . $loginName,
user => $row->{WikiName}
}
);
}
catch Error with {
my $e = shift;
$row->{errors} =
" Failed to create user topic! " . ( $e->{def} || 'unknown error' );
$row->{FAIL} = 1;
$log .= "$b1 Failed to add user: " . $e->stringify() . "\n";
};
if ( $cUID && $row->{AddToGroups} && !$row->{FAIL} ) {
my @addedTo;
foreach my $groupName ( split( /\s*,\s*/, $row->{AddToGroups} ) ) {
try {
$users->addUserToGroup( $cUID, $groupName );
push @addedTo, $groupName;
}
catch Error with {
my $e = shift;
my $err = $e->{'-text'} || '';
$session->logger->log( 'warning',
"Registration: Failure adding $cUID to $groupName in BulkRegister"
);
$log .= " * Failed to add $cUID to $groupName: $err\n";
$row->{errors} .= " Failed to add $cUID to $groupName: $err";
$row->{WARN} = 1;
};
}
if ( scalar @addedTo ) {
$log .= " * $row->{WikiName} added to groups: "
. join( ', ', @addedTo ) . "\n";
}
}
#if ($Foswiki::cfg{EmailUserDetails}) {
# If you want it, write it.
# _sendEmail($session, 'registernotifybulk', $data );
# $log .= $b1.' Password email disabled\n';
#}
return $log;
}
# ensures all named fields exist in hash
# returns array containing any that are missing
sub _missingElements {
my ( $presentArrRef, $requiredArrRef ) = @_;
my %present;
my @missing;
$present{$_} = 1 for @$presentArrRef;
foreach my $required (@$requiredArrRef) {
if ( !$present{$required} ) {
push @missing, $required;
}
}
return @missing;
}
# rearranges the fields in $data so that they match settings
# returns a new ordered form
sub _makeFormFieldOrderMatch {
my ( $fieldNames, $data ) = @_;
my @form = ();
foreach my $field (@$fieldNames) {
push @form, { name => $field, value => $data->{$field} };
}
return \@form;
}
# Get registration data from the CGI query and validate it
sub _innerRegister {
my ($session) = @_;
my $query = $session->{request};
my $data = _getDataFromQuery( $session->{users}, $query );
$data->{webName} = $session->{webName};
my $oldName = $data->{WikiName};
$oldName = 'undef' unless defined $oldName;
$data->{WikiName} =
Foswiki::Sandbox::untaint( $data->{WikiName},
\&Foswiki::Sandbox::validateTopicName );
unless ( $data->{WikiName} ) {
$session->logger->log( 'warning',
"Registration rejected: validateTopicName failed for $oldName" );
throw Foswiki::OopsException(
'register',
def => 'bad_wikiname',
web => $data->{webName},
topic => $session->{topicName},
params => [$oldName]
);
}
_validateRegistration( $session, $data, 1 );
}
# Send email requesting confirmation. Supports verification and approval.
# The recipient of the mail is passed $approvers, which is then written to
# {EmailAddress} for each recipient. $approvers can be one or more email
# addresses and/or wikinames.
sub _requireConfirmation {
my ( $session, $data, $type, $template, $approvers ) = @_;
my $topic = $session->{topicName};
my $web = $session->{webName};
my $oldName = $data->{WikiName};
$data->{WikiName} =
Foswiki::Sandbox::untaint( $data->{WikiName},
\&Foswiki::Sandbox::validateTopicName );
unless ( $data->{WikiName} ) {
$session->logger->log( 'warning',
"$type rejected: validateTopicName failed for $oldName" );
throw Foswiki::OopsException(
'register',
def => 'bad_wikiname',
web => $data->{webName},
topic => $session->{topicName},
params => [$oldName]
);
}
$data->{LoginName} ||= $data->{WikiName};
$data->{webName} = $web;
$data->{"${type}Code"} = $data->{WikiName} . '.' . int( rand(99999999) );
# SMELL: used for Register unit tests
$session->{DebugVerificationCode} = $data->{"${type}Code"};
my $file = _codeFile( $data->{"${type}Code"} );
store( $data, $file );
$session->logger->log(
{
level => 'info',
action => 'regstart',
webTopic => $Foswiki::cfg{UsersWebName} . '.' . $data->{WikiName},
extra => $data->{Email},
user => $data->{WikiName},
}
);
if ( $Foswiki::cfg{EnableEmail} ) {
my @referees = split( /,\s*/, $approvers );
my $app;
$data->{EmailAddress} = '';
while ( $app = pop @referees ) {
unless ( $app =~ m/\@/ ) {
$data->{Referee} = $app;
my $cUID = $session->{users}->getCanonicalUserID($app);
if ($cUID) {
push( @referees,
map { "$app <$_>" }
$session->{users}->getEmails($cUID) );
}
next;
}
$data->{EmailAddress} = $app; # recipient
my $err = _sendEmail( $session, "register$template", $data );
if ($err) {
$session->logger->log( 'warning',
"Registration rejected: registration_mail_failed - Email: $data->{EmailAddress}, Error $err"
);
throw Foswiki::OopsException(
'register',
def => 'registration_mail_failed',
web => $data->{webName},
topic => $topic,
params => [ $data->{EmailAddress}, $err ]
);
}
}
}
else {
my $err = $session->i18n->maketext(
'Registration cannot be completed: Email has been disabled for this Foswiki installation'
);
throw Foswiki::OopsException(
'attention',
def => 'send_mail_error',
web => $data->{webName},
topic => $topic,
params => [ 'all', $err ]
);
}
throw Foswiki::OopsException(
'register',
status => 200,
def => $template, # confirm or approve
web => $data->{webName},
topic => $topic,
params => [ $data->{EmailAddress} ]
);
}
=begin TML
---++ StaticMethod deleteUser($session)
CGI function that deletes the current user
Renames the *current* user's topic (with renaming all links) and
removes user entry from passwords.
NB. deleteUser is invoked from the =manage= script.
=cut
sub deleteUser {
my $session = shift;
my $webName = $session->{webName};
my $topic = $session->{topicName};
my $query = $session->{request};
my $cUID = $session->{user};
my $user = $query->param('user');
my $topicPrefix = $query->param('topicPrefix');
# Check that the method was POST
if ( $query
&& $query->method()
&& uc( $query->method() ) ne 'POST' )
{
throw Foswiki::OopsException(
'attention',
web => $session->{webName},
topic => $session->{topicName},
def => 'post_method_only',
params => ['remove']
);
}
unless ( $query->param('user') ) {
throw Foswiki::OopsException(
'register',
web => $session->{webName},
topic => $session->{topicName},
def => 'user_param_required',
);
}
my $myWikiName = $session->{users}->getWikiName($cUID);
my $userWikiName = $session->{users}->getWikiName($user);
Foswiki::UI::checkValidationKey($session);
# Default behavior is to leave the user topic in place. Checkbox parameters
# are not submitted unless checked.
my $removeTopic =
( defined $query->param('removeTopic') )
? $query->param('removeTopic')
: 0;
# This is the old behavior - remove the current logged in user. For safety
# Make sure the requested user = current user.
unless ( Foswiki::Func::isAnAdmin() ) {
if ( ( $user ne $cUID ) && ( $myWikiName ne $userWikiName ) ) {
throw Foswiki::OopsException(
'register',
web => $webName,
topic => $topic,
def => 'not_self',
params => [$userWikiName]
);
}
# check if user entry exists
my $users = $session->{users};
if ( !$users->userExists($cUID) ) {
throw Foswiki::OopsException(
'register',
web => $webName,
topic => $topic,
def => 'not_a_user',
params => [$userWikiName]
);
}
my $password = $query->param('password');
unless (
$users->checkPassword(
$session->{users}->getLoginName($cUID), $password
)
)
{
throw Foswiki::OopsException(
'register',
web => $webName,
topic => $topic,
def => 'wrong_password'
);
}
}
if ( $removeTopic && $query->param('topicPrefix') ) {
$topicPrefix = Foswiki::Sandbox::untaint(
scalar( $query->param('topicPrefix') ),
\&Foswiki::Sandbox::validateTopicName
);
throw Foswiki::OopsException(
'register',
web => $webName,
topic => $topic,
def => 'bad_prefix'
) unless ($topicPrefix);
}
$topicPrefix ||= 'DeletedUser';
my ( $m, $lm ) =
_processDeleteUser(
{ cuid => $user, removeTopic => $removeTopic, prefix => $topicPrefix }
);
Foswiki::Func::writeWarning("$cUID: $lm");
throw Foswiki::OopsException(
'register',
status => 200,
def => 'remove_user_done',
web => $webName,
topic => $topic,
params => [ $userWikiName, $m ]
);
}
=begin TML
---++ StaticMethod addUserToGroup($session)
adds users to a group
* groupname parameter must a a single groupname (group does not
have to exist)
* username can be a single login/wikiname/(!cuid?), a URLParam
list, or a comma separated list.
NB. Invoked from the =manage= script
=cut
sub addUserToGroup {
my $session = shift;
my $query = $session->{request};
my $topic = $session->{topicName};
my $web = $session->{webName};
my $user = $session->{user};
my @userNames = $query->multi_param('username');
my $groupName = $query->param('groupname');
my $create = Foswiki::isTrue( scalar( $query->param('create') ), 0 );
if ( !$groupName or $groupName eq '' ) {
my $userNames = scalar(@userNames) ? join( ',', @userNames ) : '';
throw Foswiki::OopsException(
'register',
def => 'no_group_specified_for_add_to_group',
web => $web,
topic => $topic,
params => [$userNames]
);
}
Foswiki::UI::checkValidationKey($session);
if ( ( $#userNames < 0 )
or ( $userNames[0] eq '' ) )
{
# if $create is set, and there are no users in the
# list, and the group exists
# then we're trying to upgrade the user topic.
# I'm not sure what other mappers might make of this..
if ( $create and Foswiki::Func::isGroup($groupName) ) {
try {
$session->{users}->addUserToGroup( undef, $groupName, $create );
}
catch Error with {
my $e = shift;
# Log the error
$session->logger->log( 'warning',
"catch: Failed to upgrade $groupName " . $e->stringify() );
};