-
Notifications
You must be signed in to change notification settings - Fork 18
/
Controller.pm
1314 lines (1071 loc) · 39 KB
/
Controller.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
package PGXN::Manager::Controller;
use 5.10.0;
use utf8;
use PGXN::Manager;
use aliased 'PGXN::Manager::Request';
use PGXN::Manager::Locale;
use PGXN::Manager::Templates;
use aliased 'PGXN::Manager::Distribution';
use HTML::Entities;
use JSON::XS;
use Email::Address;
use Encode;
use File::Temp ();
use Data::Dump 'pp';
use Data::Validate::URI 'is_uri';
use Try::Tiny;
use SemVer;
use namespace::autoclean;
our $VERSION = v0.32.2;
Template::Declare->init( dispatch_to => ['PGXN::Manager::Templates'] );
my %message_for = (
success => q{Success},
badrequest => q{Bad request: no archive parameter.},
forbidden => q{Sorry, you do not have permission to access this resource.},
notfound => q{Resource not found.},
notallowed => q{The requested method is not allowed for the resource.},
conflict => q{There is a conflict in the current state of the resource.}, # Bleh
gone => q{The resource is no longer available.},
servererror => q{Internal server error.}
);
my %code_for = (
success => 200,
moved => 301,
redirect => 307,
seeother => 303,
badrequest => 400,
forbidden => 403,
notfound => 404,
notallowed => 405,
conflict => 409,
gone => 410,
servererror => 200, # Only handled by ErrorDocument, which keeps 500.
);
sub new { bless {} => shift }
sub render {
my ($self, $template, $p) = @_;
my $req = $p->{req} ||= Request->new($p->{env});
my $res = $req->new_response($p->{code} || 200);
my $body = encode 'UTF-8', Template::Declare->show($template, $p->{req}, $p->{vars});
$res->body($body);
$res->content_length(length $body);
$res->content_type($p->{type} || 'text/html; charset=UTF-8');
return $res->finalize;
}
sub move_to_auth {
my $self = shift;
my $req = Request->new(shift);
my $res = $req->new_response;
$res->redirect($req->path_info || '/', $code_for{moved});
return $res->finalize;
}
sub redirect {
my ($self, $uri, $req, $code) = @_;
my $res = $req->new_response;
$res->redirect($req->uri_for($uri), $code || $code_for{seeother});
return $res->finalize;
}
sub missing {
my ($self, $env, $data) = @_;
my $res = $self->respond_with(
$data->{code} == 404 ? 'notfound' : 'notallowed',
PGXN::Manager::Request->new($env),
);
push @{ $res->[1] }, @{ $data->{headers} };
return $res;
}
sub respond_with {
my ($self, $status, $req, $err) = @_;
my $code = $code_for{$status} or die qq{No error code for status "$status"};
return $self->render("/$status", {
req => $req,
code => $code,
vars => { maketext => $err }
}) unless $req->is_xhr;
my $l = PGXN::Manager::Locale->accept($req->env->{HTTP_ACCEPT_LANGUAGE});
my $msg = do {
if (ref $err) {
$l->maketext(@$err);
} else {
my $txt = $message_for{ $status } or die qq{No message for status "$status"};
$l->maketext($txt);
}
};
my $type;
no if $] >= 5.017011, warnings => 'experimental::smartmatch';
my $with = scalar $req->respond_with;
if ($with eq 'html') {
$msg = '<p class="error">' . encode('UTF-8', encode_entities($msg)) . '</p>';
$type = 'text/html; charset=UTF-8';
} elsif ($with eq 'json') {
$msg = encode_json { message => $msg };
$type = 'application/json';
} elsif ($with eq 'atom') {
# XXX WTF to do here?
$type = 'text/plain; charset=UTF-8';
$msg = encode 'UTF-8', $msg;
} else {
# Text is just text.
$type = 'text/plain';
$msg = encode 'UTF-8', $msg;
}
return [
$code,
['Content-Type' => $type, 'Content-Length' => length $msg],
[$msg]
];
}
sub home {
my $self = shift;
return $self->render('/home', { env => shift });
}
sub about {
my $self = shift;
return $self->render('/about', { env => shift });
}
sub contact {
my $self = shift;
return $self->render('/contact', { env => shift });
}
sub server_error {
my ($self, $env) = @_;
# Pull together the original request environment.
my $err_env = { map {
my $k = $_;
s/^psgix[.]errordocument[.]//
? /plack[.]stacktrace[.]/ ? () : ($_ => $env->{$k} )
: ();
} keys %{ $env } };
my $uri = Request->new($err_env)->uri_for($err_env->{PATH_INFO});
if (%{ $err_env }) {
# Recdact the auth header and extract the error message.
$err_env->{HTTP_AUTHORIZATION} = '[REDACTED]' if $err_env->{HTTP_AUTHORIZATION};
my ($err) = $env->{'plack.stacktrace.html'}
? decode_entities($env->{'plack.stacktrace.html'} =~ m{<title>([^>]+)</title>})
: ('None found.:-(');
# Send an email to the administrators.
my $pgxn = PGXN::Manager->instance;
my $config = $pgxn->config;
$pgxn->send_email({
from => $config->{admin_email},
to => $config->{alert_email},
subject => "PGXN Manager Internal Server Error",
body => "An error occurred during a request to $uri.\n\n"
. "Error: $err\n\n"
. "Trace:\n\n"
. ($env->{'plack.stacktrace.text'} || 'None found. :-(')
. "\n\nEnvironment:\n\n" . pp($err_env)
. "\n",
});
}
$self->respond_with('servererror', Request->new($env));
}
sub howto {
my $self = shift;
return $self->render('/howto', { env => shift });
}
sub request {
my $self = shift;
return $self->render('/request', { env => shift });
}
sub register {
my $self = shift;
my $req = Request->new(shift);
my $params = $req->body_parameters;
my $pgxn = PGXN::Manager->instance;
# Just bail if we have no nickname.
if (!$params->{nickname}) {
return $self->respond_with('badrequest', $req, $msg) if $req->is_xhr;
return $self->render('/request', { req => $req, code => $code_for{badrequest}, vars => {
%{ $params },
highlight => 'nickname',
error => [
'Sorry, the nickname “[_1]” is invalid. Your nickname must start with an ASCII letter (a-z), end with an ASCII letter or digit, and otherwise contain only ASCII letters, digits, or hyphen. Sorry to be so strict.',
'',
],
}});
}
if ($params->{email} && (!$params->{why} || $params->{why} !~ /\w+/ || length $params->{why} < 5)) {
delete $params->{why};
return $self->render('/request', { req => $req, code => $code_for{badrequest}, vars => {
%{ $params },
highlight => 'why',
error => [
q{You forgot to tell us why you want an account. Is it because you're such a rockin PostgreSQL developer that we just can't do without you? Don't be shy, toot your own horn!}
],
}});
}
$params->{why} //= '';
try {
$pgxn->conn->run(sub {
$params->{why} =~ s/\r?\n/\n/g;
$_->do(
q{SELECT insert_user(
nickname := ?,
password := rand_str_of_len(64),
full_name := ?,
email := ?,
why := ?,
twitter := ?,
uri := ?
);},
undef,
@{ $params }{qw(
nickname
full_name
email
why
twitter
uri
)}
);
# Success! Notify the admins.
my $host = $req->address;
my $name = $params->{full_name} ? " Name: $params->{full_name}\n" : '';
my $twit = $params->{twitter} ? " Twitter: https://twitter.com/$params->{twitter}\n" : '';
my $uri = $params->{uri} ? " URI: $params->{uri}\n" : '';
(my $why = $params->{why}) =~ s/^/> /gm;
$pgxn->send_email({
from => $pgxn->config->{admin_email},
to => $pgxn->config->{alert_email},
subject => "New User Request for $params->{nickname}",
body => "A new PGXN account has been requested from $host:\n\n"
. $name
. " Nickname: $params->{nickname}\n"
. " Email: $params->{email}\n"
. $uri
. $twit
. " Reason:\n\n$why\n\n"
. "Moderate at " . $req->uri_for('/admin/moderate') . ".\n"
});
return $self->respond_with('success', $req) if $req->is_xhr;
# XXX Consider returning 201 and URI to the user profile?
$req->session->{name} = $req->param('nickname');
return $self->redirect('/account/thanks', $req);
});
} catch {
# Failure!
my $err = shift;
my ($msg, $highlight, $status);
no if $] >= 5.017011, warnings => 'experimental::smartmatch';
my $state = try { $err->state };
if ($state eq '23505') {
# Unique constraint violation.
$status = 'conflict';
if ($err->errstr =~ /\busers_pkey\b/) {
$highlight = 'nickname';
$msg = [
'The Nickname “[_1]” is already taken. Sorry about that.',
delete $params->{nickname}
];
} else {
if ($req->respond_with eq 'html') {
$msg = [
'Looks like you might already have an account. Need to <a href="[_1]">reset your password</a>?',
$req->uri_for('/reset', email => delete $params->{email}),
];
} else {
$msg = ['Looks like you might already have an account. Need to reset your password?'];
delete $params->{email},
}
}
} elsif ($state eq '23514') {
# Domain label violation.
$status = 'badrequest';
my $errstr = $err->errstr;
if ($errstr =~ /\blabel_check\b/) {
$highlight = 'nickname';
$msg = [
'Sorry, the nickname “[_1]” is invalid. Your nickname must start with an ASCII letter (a-z), end with an ASCII letter or digit, and otherwise contain only ASCII letters, digits, or hyphen. Sorry to be so strict.',
encode_entities delete $params->{nickname},
];
} elsif ($errstr =~ /\bemail_check\b/) {
$highlight = 'email';
$msg = [
q{Hrm, “[_1]” doesn't look like an email address. Care to try again?},
encode_entities delete $params->{email},
];
} elsif ($errstr =~ /\buri_check\b/) {
$highlight = 'uri';
$msg = [
q{Hrm, “[_1]” doesn't look like a URI. Care to try again?},
encode_entities delete $params->{uri},
];
} else {
die $err;
}
} else {
die $err;
}
# Respond with error code for XHR request.
return $self->respond_with($status, $req, $msg) if $req->is_xhr;
$self->render('/request', { req => $req, code => $code_for{$status}, vars => {
%{ $params },
highlight => $highlight,
error => $msg,
}});
};
}
sub forgotten {
my $self = shift;
return $self->render('/forgotten', { env => shift });
}
sub send_reset {
my $self = shift;
my $req = Request->new(shift);
my $who = $req->body_parameters->{who};
my $pgxn = PGXN::Manager->instance;
unless ($who) {
return $self->respond_with('badrequest', $req, ['Bad request: no who parameter.'])
if $req->is_xhr;
return $self->render('/forgotten', {
req => $req,
code => $code_for{badrequest},
vars => { error => ['Oops! I think you forgot to to tell me who you are.'] }
})
}
my $token = try {
$pgxn->conn->run(sub {
my $sql = $who =~ /@/
? 'SELECT forgot_password(nickname) FROM users WHERE email = ?'
: 'SELECT forgot_password(?)';
shift->selectcol_arrayref($sql, undef, $who)->[0];
});
} catch {
# Ignore domain lable violation.
my $err = shift;
die $err if $err->state ne '23514';
};
if ($token) {
my $uri = $req->uri_for("/account/reset/$token->[0]");
# Create and send the email.
$pgxn->send_email({
from => $pgxn->config->{admin_email},
to => $token->[1],
subject => 'Reset Your Password',
body => "Click the link below to reset your PGXN password. But do it soon!\n"
. "This link will expire in 24 hours:\n\n"
. " $uri\n\n"
. "Best,\n\n"
. "PGXN Management\n"
});
}
# Simple response for XHR request.
return $self->respond_with('success', $req) if $req->is_xhr;
# Redirect for normal request.
$req->session->{reset_sent} = 1;
return $self->redirect('/', $req);
}
sub login {
my $self = shift;
my $req = Request->new(shift);
return $self->redirect('/distributions', $req, $code_for{redirect});
}
sub reset_form {
my $self = shift;
return $self->render('/reset_form', { env => shift });
}
sub reset_pass {
my $self = shift;
my $req = Request->new(shift);
my $token = shift->{tok};
my $new_pass = $req->body_parameters->{new_pass};
if ($new_pass ne $req->body_parameters->{verify}) {
return $self->render('/reset_form', { req => $req, vars => { nomatch => 1 } });
}
PGXN::Manager->conn->run(sub {
shift->selectcol_arrayref(
'SELECT reset_password(?, ?)',
undef, $token, $new_pass
)->[0];
}) or return $self->respond_with(
'gone',
$req,
['Sorry, but that password reset token has expired.']
);
# Simple response for XHR request.
return $self->respond_with('success', $req) if $req->is_xhr;
# Redirect for normal request.
return $self->redirect('/account/changed', $req);
}
sub pass_changed {
my $self = shift;
return $self->render('/pass_changed', { env => shift });
}
sub thanks {
my $self = shift;
my $req = Request->new(shift);
return $self->render('/thanks', {req => $req, vars => {
name => delete $req->session->{name}
}});
}
sub moderate {
my $self = shift;
my $req = Request->new(shift);
return $self->respond_with('forbidden', $req) unless $req->user_is_admin;
my $sth = PGXN::Manager->conn->run(sub {
shift->prepare(q{
SELECT nickname::text, full_name::text, email::text, uri::text, why
FROM users
WHERE status = 'new'
ORDER BY nickname
});
});
$sth->execute;
$self->render('/moderate', { req => $req, vars => { sth => $sth }});
}
sub set_status {
my $self = shift;
my $req = Request->new(shift);
return $self->respond_with('forbidden', $req) unless $req->user_is_admin;
my $params = shift;
my $status = $req->body_parameters->{status};
my $pgxn = PGXN::Manager->instance;
$pgxn->conn->run(sub {
shift->selectcol_arrayref(
'SELECT set_user_status(?, ?, ?)',
undef, $req->user, $params->{nick}, $status
)->[0];
}) or return $self->respond_with('notfound', $req);
my ($to, $subj, $body);
if ($status eq 'active') {
# Generate a password-changing token.
my $token = $pgxn->conn->run(sub {
my $dbh = shift;
$self->_update_user_json($dbh, $params->{nick});
$dbh->selectcol_arrayref(
'SELECT forgot_password(?)',
undef, $params->{nick}
)->[0];
});
# Update the user JSON.
my $uri = $req->uri_for("/account/reset/$token->[0]");
$to = $token->[1];
$subj = 'Welcome to PGXN!';
$body = "What up, $params->{nick}.\n\n"
. "Your PGXN account request has been approved. Ready to get started?\n"
. "Great! Just click this link to set your password and get going:\n\n"
. " $uri\n\n"
. "Best,\n\n"
. "PGXN Management\n";
} else {
# XXX Maybe require a note to be entered by the admin?
$to = $pgxn->conn->run(sub {
shift->selectcol_arrayref(
'SELECT email FROM users WHERE nickname = ?',
undef, $params->{nick}
)->[0];
});
$subj = 'Account Request Rejected';
$body = "I'm sorry to report that your request for a PGXN account has been\n"
. "rejected. If you think there has been an error, please reply to this\n"
. "message.\n\n"
. "Best,\n\n"
. "PGXN Management\n";
}
# Send the email.
$pgxn->send_email({
from => $pgxn->config->{admin_email},
to => Email::Address->new( $params->{nick}, $to ),
subject => $subj,
body => $body,
});
# Simple response for XHR request.
return $self->respond_with('success', $req) if $req->is_xhr;
# Redirect for normal request.
return $self->redirect('/admin/moderate', $req);
}
sub show_upload {
my $self = shift;
return $self->render('/show_upload', { env => shift });
}
sub upload {
my $self = shift;
my $req = Request->new(shift);
my $upload = do {
my $uploads = $req->uploads;
if ($uploads && $uploads->{archive}) {
$uploads->{archive};
} else {
# Error.
return $self->respond_with('badrequest', $req) if $req->is_xhr;
# Re-display the form.
return $self->render('/show_upload', {
req => $req,
code => $code_for{badrequest},
vars => { error => ['Oops! I think you forgot to select a file to upload.'] }
});
}
};
my $dist = Distribution->new(
archive => $upload->path,
basename => $upload->basename,
creator => $req->user,
);
if ($dist->process) {
# Success!
return $self->respond_with('success', $req) if $req->is_xhr;
$req->session->{success} = 1;
my $meta = $dist->distmeta;
return $self->redirect(
"/distributions/$meta->{name}/$meta->{version}",
$req
);
}
# Error.
return $self->respond_with(
'conflict', $req, scalar $dist->error
) if $req->is_xhr;
# Re-display the form.
return $self->render('/show_upload', {
req => $req,
code => $code_for{conflict},
vars => { error => scalar $dist->error }
});
}
sub distributions {
my $self = shift;
my $req = Request->new(shift);
my $sth = PGXN::Manager->conn->run(sub {
shift->prepare(q{
SELECT name, version, relstatus,
to_char(created_at, 'IYYY-MM-DD') AS date
FROM distributions
WHERE creator = ?
ORDER BY name, version ASC
});
});
$sth->execute($req->user);
$self->render('/distributions', { req => $req, vars => { sth => $sth }});
}
sub distribution {
my $self = shift;
my $req = Request->new(shift);
my $p = shift;
# Just bail if not a valid semantic version.
return $self->respond_with('notfound', $req)
unless try { SemVer->new($p->{version}) };
my $dist = PGXN::Manager->conn->run(sub {
shift->selectrow_hashref(q{
SELECT name::text, version, abstract, description, relstatus, creator,
sha1, meta, extensions, tags::text[], creator = ? AS is_owner
FROM distribution_details
WHERE name = ?
AND version = ?
}, undef, $req->user, $p->{dist}, $p->{version});
}) or return $self->respond_with('notfound', $req);
return $self->respond_with('forbidden', $req) unless $dist->{is_owner};
$self->render('/distribution', { req => $req, vars => { dist => $dist }});
}
sub show_account {
my $self = shift;
my $req = Request->new(shift);
my $user = PGXN::Manager->conn->run(sub {
shift->selectrow_hashref(q{
SELECT nickname::text, email::text, uri::text, full_name::text,
twitter::text
FROM users
WHERE nickname = ?
}, undef, $req->user);
});
return $self->render('/show_account', { req => $req, vars => $user });
}
sub _update_user_json {
my ($self, $dbh, $nick) = @_;
my $tmp = File::Temp->new;
binmode $tmp, ':utf8';
print $tmp $dbh->selectrow_array( 'SELECT user_json(?)', undef, $nick);
close $tmp;
my $pgxn = PGXN::Manager->instance;
my $tmpl = $pgxn->uri_templates->{user}
or die "No user template found in config\n";
my $uri = $tmpl->process( user => lc $nick );
PGXN::Manager->move_file($tmp->filename, File::Spec->catfile(
$pgxn->config->{mirror_root}, $uri->path_segments
));
}
sub update_account {
my $self = shift;
my $req = Request->new(shift);
my $params = $req->body_parameters;
try {
PGXN::Manager->conn->run(sub {
my $dbh = shift;
$dbh->do(
q{SELECT update_user(
nickname := ?,
full_name := ?,
email := ?,
twitter := ?,
uri := ?
);},
undef,
$req->user,
@{ $params }{qw(
full_name
email
twitter
uri
)}
);
# Update the user JSON.
$self->_update_user_json($dbh, $req->user);
# Success!
return $self->respond_with('success', $req) if $req->is_xhr;
$req->session->{updated} = 1;
return $self->redirect($req->path_info, $req);
});
} catch {
# Failure!
my $err = shift;
my ($msg, $highlight);
no if $] >= 5.017011, warnings => 'experimental::smartmatch';
my $state = $err->state;
if ($state eq '23505') {
# Unique constraint violation.
$msg = [
'Do you have two accounts? Because the email address “[_1]” is associated with another account.',
delete $params->{email}
];
$params->{email} = PGXN::Manager->conn->run(sub{
shift->selectcol_arrayref(
'SELECT email FROM users WHERE nickname = ?',
undef, $req->user
)->[0];
});
} elsif ($state eq '23514') {
# Domain label violation.
my $errstr = $err->errstr;
if ($errstr =~ /\bemail_check\b/) {
$highlight = 'email';
$msg = [
q{Hrm, “[_1]” doesn't look like an email address. Care to try again?},
encode_entities delete $params->{email},
];
} elsif ($errstr =~ /\buri_check\b/) {
$highlight = 'uri';
$msg = [
q{Hrm, “[_1]” doesn't look like a URI. Care to try again?},
encode_entities delete $params->{uri},
];
} else {
die $err;
}
} else {
die $err;
}
# Respond with error code for XHR request.
return $self->respond_with('conflict', $req, $msg) if $req->is_xhr;
$self->render('/show_account', { req => $req, code => $code_for{conflict}, vars => {
%{ $params },
highlight => $highlight,
error => $msg,
}});
};
}
sub show_password {
my $self = shift;
return $self->render('/show_password', { env => shift });
}
sub update_password {
my $self = shift;
my $req = Request->new(shift);
my $params = $req->body_parameters;
my $err;
if ($params->{new_pass} ne $params->{new_pass2}) {
$err = q{D'oh! The passwords you typed in don't match. Would you mind trying again? Thanks.};
} elsif (length $params->{new_pass} < 4) {
$err = q{So sorry! Passwords must be at least four characters long.};
}
if ($err) {
return $self->respond_with('conflict', $req, [$err]) if $req->is_xhr;
return $self->render('/show_password', {
req => $req,
code => $code_for{conflict},
vars => { error => [ $err ] }
});
}
my $ret = PGXN::Manager->conn->run(sub {
shift->selectcol_arrayref(
'SELECT change_password(?, ?, ?)',
undef, $req->user, $params->{old_pass}, $params->{new_pass}
)->[0];
});
if ($ret) {
# Simple response for XHR request.
return $self->respond_with('success', $req) if $req->is_xhr;
# Redirect for normal request.
$req->session->{password_reset} = 1;
return $self->redirect($req->path_info, $req);
}
# Failed.
$err = [
q{I don't think that was really your existing password. Care to try again?}
];
return $self->respond_with('conflict', $req, $err) if $req->is_xhr;
return $self->render('/show_password', {
req => $req,
code => $code_for{conflict},
vars => { error => $err }
});
}
sub show_perms {
my $self = shift;
return $self->render('/show_perms', { env => shift });
}
sub show_users {
my $self = shift;
return $self->render('/show_users', { env => shift });
}
sub show_mirrors {
my $self = shift;
my $req = Request->new(shift);
return $self->respond_with('forbidden', $req) unless $req->user_is_admin;
my $sth = PGXN::Manager->conn->run(sub {
shift->prepare(q{
SELECT uri, organization, frequency, email
FROM mirrors
ORDER BY uri
});
});
$sth->execute;
$self->render('/show_mirrors', { req => $req, vars => { sth => $sth }});
}
sub get_mirror {
my $self = shift;
my $req = Request->new(shift);
return $self->respond_with('forbidden', $req) unless $req->user_is_admin;
my $uri = shift->{splat}[0] or return $self->respond_with('notfound', $req);
my $mirror = PGXN::Manager->conn->run(sub {
shift->selectrow_hashref(q{
SELECT uri, organization, email, frequency, location, timezone,
bandwidth, src, rsync, notes
FROM mirrors
WHERE uri = ?
}, undef, $uri );
}) or return $self->respond_with('notfound', $req);
$mirror->{update} = 1;
$self->render('/show_mirror', { req => $req, vars => $mirror });
}
sub new_mirror {
my $self = shift;
my $req = Request->new(shift);
return $self->respond_with('forbidden', $req) unless $req->user_is_admin;
return $self->render('/show_mirror', { req => $req });
}
sub _do_mirror {
my $self = shift;
my $action = shift;
my $req = Request->new(shift);
my $params = $req->body_parameters;
my $update = $action eq 'update';
return $self->respond_with('forbidden', $req) unless $req->user_is_admin;
my @missing;
for my $key (qw(uri email frequency organization location timezone bandwidth src)) {
push @missing => $key if !$params->{$key} || $params->{$key} !~ /\w+/;
delete $params->{$key}if !$params->{$key} || $params->{$key} !~ /\w+/;
}
if (@missing) {
return $self->respond_with(
'conflict', $req, ['Missing values for [qlist,_1].', \@missing]
) if $req->is_xhr;
return $self->render('/show_mirror', { req => $req, code => $code_for{conflict}, vars => {
%{ $params },
highlight => \@missing,
error => [q{I think you left something out. Please fill in the missing data in the highlighted fields below.}],
update => $update,
}});
}
my $old_uri = shift->{splat}[0];
try {
PGXN::Manager->conn->run(sub {
my $ret = shift->selectcol_arrayref(
qq{SELECT $action\_mirror(
admin := ?,} . ($update ? "\n old_uri := ?," : '') . q{
uri := ?,
frequency := ?,
location := ?,
bandwidth := ?,
organization := ?,
timezone := ?,
email := ?,
src := ?,
rsync := ?,
notes := ?
)},
undef,
$req->user,
($update ? ($old_uri) : ()),
@{ $params }{qw(
uri
frequency
location
bandwidth
organization
timezone
email
src
rsync
notes
)}
)->[0];
if ($ret) {
# Success! Write out a new mirrors.json.
$self->_write_mirrors_meta;
return $self->respond_with('success', $req) if $req->is_xhr;
# XXX Consider returning 201 and URI to the mirror profile?
$req->session->{uri} = $req->param('uri');
return $self->redirect('/admin/mirrors', $req);
}
# Respond with error code for XHR request.
my $msg = ['Update failed; maybe someone deleted this mirror?'];
return $self->respond_with('notfound', $req, $msg)
if $req->is_xhr;
return $self->render('/show_mirror', {
req => $req,
code => $code_for{notfound},
vars => {
%{ $params },
error => $msg,
update => $update,
}
});
});
} catch {
# Failure!
my $err = shift;
my ($msg, $highlight);
no if $] >= 5.017011, warnings => 'experimental::smartmatch';
my $state = try { $err->state };
if ($state eq '23505') {
# Unique constraint violation.
$highlight = ['uri'];
$msg = [
'Looks like [_1] is already registered as a mirror.',
delete $params->{uri},
];
# Show the original URL for updates.
$params->{uri} = $old_uri if $update;
} elsif ($state eq '23514') {
# Domain label violation.
my $errstr = $err->errstr;
if ($errstr =~ /\btimezone\b/) {
$highlight = ['timezone'];
$msg = [
'Sorry, the time zone “[_1]” is invalid.',
delete $params->{timezone},
];
}
elsif ($errstr =~ /\bemail_check\b/) {
$highlight = ['email'];
$msg = [
q{Hrm, “[_1]” doesn't look like an email address. Care to try again?},
delete $params->{email},
];
} elsif ($errstr =~ /\buri_check\b/) {
my $field = !is_uri($params->{src}) ? 'src'
: !is_uri($params->{rsync}) ? 'rsync'
: 'uri';
$highlight = [$field];
$msg = [
q{Hrm, “[_1]” doesn't look like a URI. Care to try again?},
delete $params->{$field},
];
$params->{$field} = $old_uri if $update && $field eq 'uri';
} else {
die $err;
}
} else {
die $err;
}
# Respond with error code for XHR request.
return $self->respond_with('conflict', $req, $msg) if $req->is_xhr;
return $self->render('/show_mirror', { req => $req, code => $code_for{conflict}, vars => {