lib/Rapi/Blog/Controller/Remote.pm untested

filter: Statementstmt 0.0% 0 / 239 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 133 MC/DCmcdc 0.0% 0 / 68 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 538 CC 31 SCAR 41.3
CC
31
Cov
0%
signup
210.0
_redirect_local_info
30.0
add_comment
12.0
CRAP 62.3
1 package Rapi::Blog::Controller::Remote;
2 use Moose;
3 use namespace::autoclean;
4  
5 BEGIN { extends 'Catalyst::Controller'; }
6  
7 use strict;
8 use warnings;
9  
10 use RapidApp::Util ':all';
11 use Rapi::Blog::Util;
12 use URI;
13 use Email::Valid;
14  
15 # This is the general-purpse controller for handing domain-specific
16 # custom-code endpoint requests outside/separate of RapidApp
17  
18  
19 sub comment :Local :Args(1) {
20 my ($self, $c, $arg) = @_;
21
22 return $self->add_comment($c) if ($arg eq 'add');
23
24
25 $self->error_response($c,"bad comment argument '$arg'");
26 }
27  
28 sub add_comment {
29 my ($self, $c) = @_;
30
31 # Ignore via generic redirect if its not a POST
32 $c->req->method eq 'POST' or return $c->res->redirect( $c->mount_url.'/', 307 );
33
34 my $User = Rapi::Blog::Util->get_User or return $self->error_response($c,
35 "Not logged in or unable to find current user"
36 );
37
38 $User->can_comment or return $self->error_response($c,
39 "Add comment: permission denied"
40 );
41
42 my $raw_body = $c->req->params->{body} or return $self->error_response($c,"missing param 'body'");
43 my $body = Rapi::Blog::Util->sanitize_input( $raw_body );
44
45 my %data;
46 my $Post;
47
48 if(my $parent_id = $c->req->params->{parent_id}) {
49 my $pComment = $c->model('DB::Comment')->search_rs({ 'me.id' => $parent_id })->first
50 or return $self->error_response($c,"Comment '$parent_id' does not exist or permission denied");
51
52 $Post = $pComment->post;
53 $data{parent_id} = $pComment->id;
54 }
55 elsif(my $post_id = $c->req->params->{post_id}) {
56 $Post = $c->model('DB::Post')->search_rs({ 'me.id' => $post_id })->first
57 or return $self->error_response($c,"Post '$post_id' does not exist or permission denied");
58 }
59 else {
60 return $self->error_response($c,"Must supply either 'post_id' or 'parent_id'");
61 }
62
63 %data = ( %data,
64 post_id => $Post->id,
65 user_id => $User->id,
66 body => $body
67 );
68
69 my $Comment = $Post->comments->create(\%data)
70 or return $self->error_response($c,"Unable to add comment - unknown error");
71
72 my $url = join('#',$Post->public_url,$Comment->html_id);
73
74 return $c->res->redirect( $url, 303 );
75 }
76  
77  
78  
79 sub email_login :Local :Args(0) {
80 my ($self, $c) = @_;
81
82 ####### comment this out to test
83 #die "email_login is experimental and this die line must be commented out in order to try it.";
84 ################################
85
86
87 # Non-posts silently redirect to the home page:
88 $c->req->method eq 'POST' or return $c->res->redirect( $c->mount_url );
89
90 Rapi::Blog::Util->opportunistic_recaptcha_verify or return $self->error_response($c,
91 "reCAPTCHA verification required"
92 );
93
94 $c->ra_builder->enable_email_login or return $self->error_response($c,
95 "Permission denied - email login is not enabled."
96 );
97
98 Rapi::Blog::Util->get_User and return $self->error_response($c,
99 "Not allowing E-Mail login for already logged in user"
100 );
101
102 # Only continue if we're properly using the 'local_info' API:
103 $self->_using_local_info or return $self->error_response($c,
104 "Invalid or malformed request - failed one or more 'local_info' API requirements"
105 );
106
107 my $email = $c->req->params->{email} or return $self->error_response($c,
108 "Must supply an E-Mail address associated with an account"
109 );
110
111 my $Rs = $c->model('DB::User')->enabled;
112
113
114 my @or_list = ({'me.username' => $email},{'me.username' => lc($email)});
115 if($email =~ /\@/) {
116 # Don't bother searching by e-mail if we already know it cant be an e-mail
117 push @or_list, {'me.email' => $email},{'me.email' => lc($email)};
118 }
119
120 my $User = $Rs->search_rs({ -or => \@or_list })
121 ->first or return $self->error_response($c,
122 "No valid account with username or E-Mail address '$email'"
123 );
124
125 $User->email or return $self->error_response($c,
126 "That account has no E-Mail address on file."
127 );
128
129 my $uid = $User->get_column('id');
130
131  
132 my $paRs = $c->model('DB::PreauthAction');
133
134 my $key = $paRs->create_auth_key('login', $uid, {
135 ttl => 5*60, # 5 minutes
136 }) or return $self->error_response($c,join ' ',
137 "Failed to create Pre-Authorization",'–',
138 "an unknown error occured.",
139 "Please contact your system administrator"
140 );
141
142 my $Preauth = $paRs->lookup_key($key) or return $self->error_response($c,join ' ',
143 "Unknown error occured while creating Pre-Authorization",'–',
144 "please contact your system administrator"
145 );
146
147 # WTF. HTTP_ORIGIN has suddenly vanished.
148 my ($url_base, $host_port);
149 if (my $ref = $c->req->env->{HTTP_REFERER}) {
150 my ($proto,$remaining) = split(/\:\/\//,$ref,2);
151 ($host_port) = split(/\//,$remaining);
152 $url_base = join('://',$proto,$host_port);
153 }
154
155 # This is almost the same as $c->req->uri->host, but it includes the port if present:
156 #my $host_friendly = (split(/\:\/\//,$c->req->env->{HTTP_ORIGIN},2))[1];
157 my $host_friendly = $host_port;
158  
159 my $link_url = join('/',
160 #$c->req->env->{HTTP_ORIGIN},
161 $url_base,
162 $c->mount_url||(),'remote', 'preauth_action', $key
163 );
164
165 my $title = try{Rapi::Blog::Util->get_scaffold_cfg->title} || $host_friendly;
166
167 $c->model('Mailer')->send_mail({
168 to => $User,
169 from => "$title <no-reply@".$c->req->uri->host.'>',
170 #from => '"Rapi::Blog ('.$c->req->env->{HTTP_ORIGIN}.')" <no-reply@'.$c->req->uri->host.'>',
171 subject => "One-time login link ($host_friendly)",
172 body => join("",
173 "Here is your one-time, direct login link. This will log you into your $host_friendly ",
174 "account without having to enter your username and password.\n\n",
175 "This can only be used once and will expire in ",
176 $Preauth->ttl_minutes," minutes.\n\n$link_url\n\n",
177 "(if you did not request this link, you may disregard this message)"
178 )
179 });
180  
181 return $self->redirect_local_info_success($c, join ' ',
182  
183 "A one-time, direct login link has been sent to the e-mail address on file for your account.",
184 "Please check your e-mail.",
185 "<br><br>",
186 "This link will allow you to log into your account without entering your password.",
187 "Once logged in, you can change your password, or anything else your account has access to do.",
188 "<br><br>",
189 "For security, the login link can only be used one time and will only be valid for the next",
190 $Preauth->ttl_minutes,"minutes",
191  
192 )
193
194
195  
196 }
197  
198  
199  
200  
201  
202 sub password_reset :Local :Args(0) {
203 my ($self, $c) = @_;
204
205 ###########
206 # phase 2:
207 # handle the preauthed reset after the user clicked the link from phase 1
208 #
209 $c->req->params->{key} and return $self->_password_reset_by_key($c);
210
211
212 ###########
213 # phase 1:
214 # fresh request to start an preauth to reset a password
215 #
216
217 # Non-posts silently redirect to the home page:
218 $c->req->method eq 'POST' or return $c->res->redirect( $c->mount_url );
219
220 $c->ra_builder->enable_password_reset or return $self->error_response($c,
221 "Permission denied - password reset is not enabled."
222 );
223
224 Rapi::Blog::Util->get_User and return $self->error_response($c,
225 "Not allowing password reset for already logged in user"
226 );
227
228 # Only continue if we're properly using the 'local_info' API:
229 $self->_using_local_info or return $self->error_response($c,
230 "Invalid or malformed request - failed one or more 'local_info' API requirements"
231 );
232
233
234 my $supplied = $c->req->params->{username} or return $self->error_response($c,
235 "Must supply a username or E-Mail address"
236 );
237
238 my $Rs = $c->model('DB::User')->enabled;
239
240 my $uid;
241 if($supplied =~ /\@/) {
242 my $User = $Rs->search_rs({ -or => [{'me.email' => $supplied},{'me.email' => lc($supplied)}]})
243 ->first or return $self->error_response($c,
244 "No valid account with E-Mail address '$supplied'"
245 );
246 $uid = $User->get_column('id')
247 }
248 else {
249 my $User = $Rs->search_rs({ -or => [{'me.username' => $supplied},{'me.username' => lc($supplied)}]})
250 ->first or return $self->error_response($c,
251 "No valid account with username '$supplied'"
252 );
253 $uid = $User->get_column('id')
254 }
255  
256 my $paRs = $c->model('DB::PreauthAction');
257
258 my $key = $paRs->create_auth_key('password_reset', $uid, {
259 ttl => 15*60, # 15 minutes
260 action_data => {
261 origin_referer => $c->req->referer # come back to us
262 }
263 }) or return $self->error_response($c,join ' ',
264 "Failed to create Pre-Authorization",'&ndash;',
265 "an unknown error occured.",
266 "Please contact your system administrator"
267 );
268
269 my $Preauth = $paRs->lookup_key($key) or return $self->error_response($c,join ' ',
270 "Unknown error occured while creating Pre-Authorization",'&ndash;',
271 "please contact your system administrator"
272 );
273
274
275 # Real logic (send actual e-mail) goes here
276 # ...
277
278  
279 my $link_url = do {
280 my $uri = $c->req->uri->clone;
281 $uri->query_form( $uri->query_form, key => $key );
282 $uri->as_string;
283 };
284
285
286
287  
288 return $self->redirect_local_info_success($c, join ' ',
289
290  
291 "Password reset initiated",'&ndash;',
292 "a password reset link has been E-Mailed to you.",
293 "For security, the reset link will only be valid for the next", $Preauth->ttl_minutes,"minutes",
294
295 "<br><br><br>\n","<a href='$link_url'>$link_url</a>",
296
297 "<br><br><br>","TEMP DEBUG DATA:","<br><br>",
298 "<pre>",join("\n ",'',
299 "key: $key",
300 "ttl: " . $Preauth->ttl, '',
301 "now_ts: ".Rapi::Blog::Util->dt_to_ts(Rapi::Blog::Util->now_dt),
302
303
304 "columns: ". Dumper({ $Preauth->get_columns }),'','',
305 "action_data: ". Dumper($Preauth->action_data),'','',
306
307 ),"</pre>"
308 )
309
310
311  
312 }
313  
314  
315  
316 # password reset phase 2:
317 sub _password_reset_by_key {
318 my $self = shift;
319 my $c = shift || RapidApp->active_request_context or return 0;
320
321 my $key = $c->req->params->{key} or die "no key param supplied";
322
323 my $Actor = $c
324 ->model('DB::PreauthAction')
325 ->request_Actor($c,$key);
326
327 if($Actor->is_error) {
328 die $Actor;
329 #my $referer = '/forgot_password';
330 #return $self->_local_info_dispatch($c,$referer,{ error_only => $Actor->info });
331 }
332
333
334 # phase 3
335 if($c->req->params->{new_password}) {
336 $Actor->call_execute and return $self->_redirect_local_info($c, { finished => 1 });
337
338 # TODO:
339 return $self->_redirect_local_info($c, { finished => 1, failed => 1 });
340 }
341 else {
342 # phase 2:
343 my $referer = $Actor->PreauthAction->action_data_get('origin_referer') or die "Missing origin_referer";
344 return $self->_local_info_dispatch($c,$referer,{ key => $key });
345 }
346
347 }
348  
349  
350 sub _using_local_info {
351 my $self = shift;
352 my $c = shift || RapidApp->active_request_context or return 0;
353
354 $c->stash->{_using_local_info} //=
355 $c->req->params->{using}||'' eq 'local_info' && do {
356
357 my $uri = $c->req->uri;
358 my $ruri = $c->req->referer ? URI->new( $c->req->referer ) : undef;
359
360 # Require referer to be one of our local pages - not really hard security,
361 # but since we do not expect to ever be accessed via direct browse or
362 # linked to from an external site, don't allow it:
363 $uri && $ruri && $uri->host_port eq $ruri->host_port
364 }
365 }
366  
367  
368  
369  
370  
371  
372  
373  
374 sub signup :Local :Args(0) {
375 my $self = shift;
376 my $c = shift || RapidApp->active_request_context or return 0;
377
378 $c->session->{local_info} and delete $c->session->{local_info};
379
380 # Non-posts silently redirect to the home page:
381 $c->req->method eq 'POST' or return $c->res->redirect( $c->mount_url );
382
383 my @errs = ();
384
385 my $uRs = $c->model('DB::User');
386 my $p = $c->req->params;
387 my $field_errs = {};
388
389 if (my $username = $p->{username}) {
390 if ($username =~ /^[a-zA-Z0-9\.\-\_]+$/) {
391 if ($self->_username_taken($c,$username)) {
392 $field_errs->{username}++;
393 push @errs, "Username already taken";
394 }
395 }
396 else {
397 push @errs, "usernames may only contain alpha characters and (-_.)";
398 $field_errs->{username}++;
399 }
400 }
401 else {
402 push @errs, "Must supply a username";
403 $field_errs->{username}++;
404 }
405
406 if (my $email = $p->{email}) {
407 if (Email::Valid->address($email)) {
408 if ($uRs->search_rs({ 'me.email' => $p->{email} })->count > 0) {
409 push @errs, "E-Mail already in use";
410 $field_errs->{email}++;
411 }
412 }
413 else {
414 push @errs, "Supplied E-Mail address is not valid";
415 $field_errs->{email}++;
416 }
417 }
418 else {
419 push @errs, "Must supply an E-Mail address";
420 $field_errs->{email}++;
421 }
422
423 if (!$p->{full_name} || ($p->{full_name} =~ /^\s*$/)) {
424 $field_errs->{full_name}++;
425 push @errs, "Full Name cannot be blank";
426 }
427 elsif (($p->{full_name} =~ /^\s+/) || ($p->{full_name} =~ /\s+$/)) {
428 $field_errs->{full_name}++;
429 push @errs, "Full Name cannot start or end with whitespace";
430 }
431 elsif ($self->_full_name_taken($c,$p->{full_name})) {
432 $field_errs->{full_name}++;
433 push @errs, "Supplied Full Name is already in use";
434 }
435
436 my ($p1,$p2) = ($p->{password},$p->{confirm_password});
437 if(length($p1) < 6) {
438 $field_errs->{password}++;
439 push @errs, "Passwords must be at least 6 characters long";
440 }
441 unless("$p1" eq "$p2") {
442 $field_errs->{confirm_password}++;
443 push @errs, "Passworrds do not match";
444 }
445
446 unless(Rapi::Blog::Util->opportunistic_recaptcha_verify) {
447 $field_errs->{'recaptcha'}++;
448 push @errs, "reCAPTCHA verification required";
449 }
450
451 my $extra = { field_vals => $p, field_errs => $field_errs };
452
453 if(scalar(@errs) > 0) {
454 my $error_msg = join("\n",
455 '<ul style="list-style-type:disc;padding-left:20px;font-size:.9em;">',
456 (map { join('','<li>',$_,'</li>') } @errs),
457 '</ul>'
458 );
459
460 $self->error_response($c,(join ' ',
461 '<div style="padding-left:75px;margin-top:-25px;margin-bottom:-20px;text-align:left;">',
462 '<div style="font-size:1.8em;padding-bottom:10px;">Errors:</div>',"\n",$error_msg,
463 '</div>'),$extra
464 );
465
466 }
467 else {
468 my $NewUser = $c->model('DB::User')->create({
469 username => $p->{username},
470 set_pw => $p->{password},
471 full_name => $p->{full_name},
472 email => $p->{email},
473 disabled => 0,
474 comment => 1
475 }) or die "unknown error creating new user";
476
477 return $c->forward('/auth/login');
478 }
479 }
480  
481  
482  
483  
484  
485 # For good measure we test both databases just in case:
486 sub _username_taken {
487 my ($self, $c, $username) = @_;
488 my @RS = ($c->model('DB::User'),$c->model('RapidApp::CoreSchema::User'));
489 for my $Rs (@RS) {
490 return 1 if ($Rs->search_rs({ 'me.username' => $username })->count > 0);
491 }
492 return 0
493 }
494  
495 sub _full_name_taken {
496 my ($self, $c, $fn) = @_;
497 my @RS = ($c->model('DB::User'),$c->model('RapidApp::CoreSchema::User'));
498 for my $Rs (@RS) {
499 return 1 if ($Rs->search_rs({ 'me.full_name' => $fn })->count > 0);
500 }
501 return 0
502 }
503  
504  
505  
506  
507  
508  
509  
510  
511  
512  
513 sub redirect_local_info_error {
514 my ($self, $c, $msg, $extra) = @_;
515 $self->_redirect_local_info($c, $msg, 0, $extra)
516 }
517  
518 sub redirect_local_info_success {
519 my ($self, $c, $msg,$extra) = @_;
520 $self->_redirect_local_info($c, $msg, 1, $extra)
521 }
522  
523 sub _redirect_local_info {
524 my ($self, $c, $info, $result, $extra) = @_;
525
526 unless((ref($info)||'') eq 'HASH') {
527 $info = { message => $info };
528 %$info = (%$info,%$extra) if (ref($extra)||'' eq 'HASH');
529 }
530 my $msg = $info->{message} || '';
531  
532 my $uri = $c->req->uri;
533 my $ruri = URI->new( $c->req->referer );
534
535 # If this isn't a local referer just throw hard error:
536 $ruri && $uri->host eq $ruri->host or return $self->error_response($c,
537 "Error, bad referer - message: '$msg'"
538 );
539
540 if(defined $result) {
541 $result ? $info->{success} = 1 : $info->{error} = 1
542 }
543
544 # otherwise set the local_info and redirect back to the referer, trusting that
545 # it is a properly written template that knows to look for and use the local_info:
546 return $self->_local_info_dispatch($c,$ruri,$info)
547 }
548  
549  
550  
551 sub _local_info_dispatch {
552 my ($self, $c, $target, $info) = @_;
553
554 # we don't currently want any local info to hang around at all, even for
555 # other paths. Maybe this will be changed later, but right now I can't envision
556 # any use cases besides tight 2-request round trips
557 $c->session->{local_info} and delete $c->session->{local_info};
558
559 my $uri = blessed($target) && $target->isa('URI') ? $target : do {
560 my $u = URI->new($target, $c->req->uri->scheme);
561 $u->host_port( $c->req->uri->host_port );
562 $u
563 };
564
565 my $path = $uri->path;
566
567 $c->session->{local_info}{$uri->path} = $info;
568 return $c->res->redirect( $uri->path_query );
569 }
570  
571  
572  
573  
574 # placeholder for later
575 sub error_response {
576 my ($self, $c, $err, $extra) = @_;
577
578 local $self->{_error_response_recurse} = $self->{_error_response_recurse} || 0;
579
580 return $self->redirect_local_info_error($c,$err,$extra) if (
581 $self->{_error_response_recurse}++ < 1
582 && $self->_using_local_info($c)
583 );
584
585 # hard errors make sure no leftover local_info:
586 $c->session->{local_info} and delete $c->session->{local_info};
587
588 die $err
589 }
590  
591  
592  
593 __PACKAGE__->meta->make_immutable;
594  
595 1;
596  
597 __END__