blib/lib/Slovo/Controller/Auth.pm

filter: Statementstmt 50.4% 58 / 115 Branchbran 30.4% 14 / 46 Conditioncond 5.0% 1 / 20 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 76.9% 10 / 13 Podpod 90.9% 10 / 11 totaltotal 43.2% 93 / 215 CC 30 SCAR 30.8
CC
30
Cov
40%
under_management
66.5
first_login_form
30.0
first_login
9.6
CRAP 21.7
↑ Summary blib/lib/Slovo/Plugin/CGI.pm »
1 package Slovo::Controller::Auth;
2 15 ▶use Mojo::Base 'Slovo::Controller', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 15 ▶use Mojo::Util qw(encode sha1_sum);
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # Returns the name of the geter for the current user.
7 # Needed by Mojolicious::Plugin::Authentication.
8 # See Slovo::_before_dispatch to understand how this function name is used.
9 14 ▶sub current_user_fn { return 'user' }
Subroutine current_user_fn: called CC=1 SCAR=0.0
Pod documented
10  
11 # Display the form for signing in.
12 # GET /in
13 10 ▶sub form ($c) {
Subroutine form: called CC=2 SCAR=7.1
Pod documented
14  
15 #TODO: remember where the user is comming from to redirect him back
16 #afterwards if the place he is comming from in the siame domain. If not,
17 #redirect him to the main page.
18 10 ▶ $c->is_user_authenticated && return $c->redirect_to('/');
Branch: 1 branch
BranchTrueFalseTotal
$c->is_user_authenticated and return $c->redirect_to("/") 0 10 10
19 10 $c->stash(sign_in_error => '');
20 10 return $c->render;
21 }
22  
23 # Sign in the user.
24 # POST /in
25 9 ▶sub sign_in ($c) {
Subroutine sign_in: called CC=6 SCAR=21.0
Pod documented
26  
27 #1. do basic validation first
28 9 my $v = $c->validation;
29 9 $v->required('login_name', 'trim')->like(qr/^[\p{IsAlnum}\.\-\$]{3,12}$/x);
30 9 $v->required('digest')->like(qr/[0-9a-f]{40}/i);
31 9 $c->stash(sign_in_error => '');
32  
33 9 ▶ if ($v->csrf_protect->has_error('csrf_token')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($v->csrf_protect->has_error('csrf_token')) { } 1 8 9
elsif ($v->has_error) { } 0 8 8
34 1 return $c->render(
35 sign_in_error => 'Bad CSRF token!',
36 status => 401,
37 template => 'auth/form'
38 );
39 }
40 elsif ($v->has_error) {
41 0 return $c->render(
42 sign_in_error => 'И двете полета са задължителни!..',
43 status => 401,
44 template => 'auth/form'
45 );
46 }
47  
48 8 my $o = $v->output;
49  
50 # TODO: Redirect to the page where user wanted to go or where he was before
51 8 ▶ if ($c->authenticate($o->{login_name}, $o->{digest}, $o)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->authenticate($o->{"login_name"}, $o->{"digest"}, $o)) 0 8 8
52 my $route
53 = ($c->stash('passw_login')
54 ? {'edit_users' => {id => $c->user->{id}}}
55 0 ▶ : 'home_upravlenie');
Branch: 1 branch
BranchTrueFalseTotal
$c->stash('passw_login') ? : 0 0 0
56 0 ▶ return $c->redirect_to(ref($route) ? %$route : $route);
Branch: 1 branch
BranchTrueFalseTotal
ref $route ? : 0 0 0
57 }
58 8 $c->stash(sign_in_error => 'Няма такъв потребител или ключът ви е грешен.');
59 8 return $c->render('auth/form');
60 }
61  
62 # GET /out
63 5 ▶sub sign_out ($c) {
Subroutine sign_out: called CC=1 SCAR=0.0
Pod undocumented
64 5 my $login_name = $c->user->{login_name};
65 5 $c->logout;
66 5 $c->app->log->info('$user ' . $login_name . ' logged out!');
67 5 return $c->redirect_to('authform');
68 }
69  
70 11 ▶sub under_management ($c) {
Subroutine under_management: called CC=9 SCAR=42.0
Pod documented
71 11 ▶ unless ($c->is_user_authenticated) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($c->is_user_authenticated) 11 0 11
72 11 $c->redirect_to('authform');
73 11 return 0;
74 }
75  
76 0 my $uid = $c->user->{id};
77 0 my $path = $c->req->url->path->to_string;
78 0 my $route = $c->current_route;
79  
80 0 ▶ return 1 if $c->groups->is_admin($uid);
Branch: 1 branch
BranchTrueFalseTotal
if $c->groups->is_admin($uid) 0 0 0
81  
82 # for now only admins can manage groups and domains
83 0 ▶ if ($route =~ /groups|domove$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($route =~ /groups|domove$/u) 0 0 0
84 0 $c->flash(message => 'Само управителите се грижат'
85 . ' за множествата от потребители и домейните.');
86 0 $c->redirect_to('home_upravlenie');
87 0 return 0;
88 }
89  
90 # only admins and users with id=created_by can change another's user account
91 0 my ($e_uid) = $path =~ m|/users/(\d+)|; #Id of the user being edited
92 0 ▶ my $e_user = $e_uid ? $c->users->find_where({id => $e_uid}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$e_uid ? : 0 0 0
93 0 ▶ if ( $route =~ /^(show|edit|update|remove)_users$/x
Branch: 1 branch
BranchTrueFalseTotal
if ($route =~ /^(show|edit|update|remove)_users$/ux and $e_user and ($e_user->{"created_by"} != $uid and $e_user->{"id"} != $uid)) 0 0 0
Condition0%0/9
$route =~ /^(show|edit|update|remove)_users$/ux and $e_user and ($e_user->{"created_by"} != $uid and $e_user->{"id"} != $uid)
!ll&&!rl&&r
000
$route =~ /^(show|edit|update|remove)_users$/ux and $e_user
!ll&&!rl&&r
000
$e_user->{"created_by"} != $uid and $e_user->{"id"} != $uid
!ll&&!rl&&r
000
MC/DC0%0/4
$route =~ /^(show|edit|update|remove)_users$/ux and $e_user and ($e_user->{"created_by"} != $uid and $e_user->{"id"} != $uid)
$route =~ /^(show|edit|update|remove)_users$/ux $e_user $e_user->{"created_by"} != $uid $e_user->{"id"} != $uid
Truth table0%0/5
A and B and C and D
A= $route =~ /^(show|edit|update|remove)_users$/uxB= $e_userC= $e_user->{"created_by"} != $uidD= $e_user->{"id"} != $uid
ABCDresult
0XXX0
10XX0
110X0
11100
11111
94 && $e_user
95 && ($e_user->{created_by} != $uid && $e_user->{id} != $uid))
96 {
97 0 $c->flash(
98 message => 'Само управителите на сметки могат да ' . 'променят чужда сметка.');
99 0 $c->redirect_to('home_upravlenie');
100 0 return 0;
101 }
102 0 return 1;
103 }
104  
105 # secure route /manage/minion.
106 # Allow access to only authenticated members of the admin group.
107 0 ▶sub under_minion ($c) {
Subroutine under_minion: not called CC=2 SCAR=17.9
Pod documented
108  
109 # TODO: make the group configurable
110 0 ▶ unless ($c->groups->is_admin($c->user->{id})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($c->groups->is_admin($c->user->{"id"})) 0 0 0
111 0 $c->flash(message => 'Само управителите могат да управляват задачите.');
112 0 $c->redirect_to('home_upravlenie');
113 0 return 0;
114 }
115 0 return 1;
116 }
117  
118 0 ▶sub load_user ($c, $uid) {
Subroutine load_user: not called CC=1 SCAR=6.9
Pod documented
119  
120 # TODO: implement some smarter caching (at least use Mojo::Cache).
121 # state $users ={};
122 # keys %$users >2000 && $users = {};#reset cached users.
123 # return $users->{$uid}//=$c->users->find($uid);
124 0 return $c->users->find($uid);
125 }
126  
127 # Used in $c->authenticate by Mojolicious::Plugin::Authentication
128 # returns the user id or nothing.
129 8 ▶sub validate_user ($c, $login_name, $csrf_digest, $dat) {
Subroutine validate_user: called CC=5 SCAR=19.9
Pod documented
130 8 state $app = $c->app;
131 8 state $log = $app->log;
132 8 my $u = $c->users->find_by_login_name($login_name);
133 8 ▶ if (!$u) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($u) 0 8 8
134 0 $log->error("Error signing in user [$login_name]: "
135 . "No such user or user disabled, or stop_date < now!");
136 0 return;
137 }
138 8 my $csrf_token = $c->csrf_token;
139 8 my $checksum = sha1_sum($csrf_token . $u->{login_password});
140 8 ▶ unless ($checksum eq $csrf_digest) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($checksum eq $csrf_digest) 8 0 8
141  
142 # try the passw_login
143 8 my $t = time;
144 my $row = $c->dbx->db->select(
145 passw_login => 'token',
146 8 {start_date => {'<=' => $t}, to_uid => $u->{id}, stop_date => {'>' => $t}},
147 {-desc => ['id']})->hash;
148 my $checksum2 = sha1_sum(
149 8 $csrf_token . sha1_sum(encode('UTF-8' => $u->{login_name} . $row->{token})));
150 8 ▶ if ($row && ($checksum2 eq $csrf_digest)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row and $checksum2 eq $csrf_digest) 0 8 8
Condition33%1/3
$row and $checksum2 eq $csrf_digest
!ll&&!rl&&r
080
MC/DC0%0/2
$row and $checksum2 eq $csrf_digest
$row $checksum2 eq $csrf_digest
Truth table33%1/3
A and B
A= $rowB= $checksum2 eq $csrf_digest
ABresult
0X0
100
111
151 0 $app->dbx->db->delete('passw_login' => {to_uid => $u->{id}});
152  
153 # also delete expired but not deleted (for any reason) login tokens.
154 0 $app->dbx->db->delete('passw_login' => {stop_date => {'<=' => $t}});
155 0 $log->info('$user ' . $u->{login_name} . ' logged in using passw_login!');
156 0 $c->flash(message => 'Задайте нов таен ключ!');
157 0 $c->stash(passw_login => 1);
158 0 return $u->{id};
159 }
160 8 $log->error("Error signing in user [$u->{login_name}]:"
161 . "\$csrf_token:$csrf_token|\$checksum:$checksum \$csrf_digest:$csrf_digest)");
162 8 $log->error('$checksum:sha1_sum($csrf_token . $u->{login_password}) ne $csrf_digest');
163 8 return;
164 }
165 0 $log->info('$user ' . $u->{login_name} . ' logged in!');
166  
167 0 return $u->{id};
168 }
169  
170 15 my $msg_expired_token = 'Връзката, която ви доведе тук, е с изтекла годност.' . '';
171  
172 # GET /first_login/<token:fl_token>
173 # GET /first_login/32e36608c72bc51c7c39a72fd7e71cba55f3e9ad
174 0 ▶sub first_login_form ($c) {
Subroutine first_login_form: not called CC=5 SCAR=34.0
Pod documented
175 0 ▶ $c->logout && $c->user($c->users->find_by_login_name('guest'))
Branch: 1 branch
BranchTrueFalseTotal
if $c->is_user_authenticated 0 0 0
Condition0%0/6
$c->is_user_authenticated && ($c->logout && $c->user($c->users->find_by_login_name('guest')))
!ll&&!rl&&r
000
$c->logout and $c->user($c->users->find_by_login_name("guest"))
!ll&&!rl&&r
000
MC/DC0%0/3
$c->is_user_authenticated && ($c->logout && $c->user($c->users->find_by_login_name('guest')))
$c->is_user_authenticated $c->logout $c->user($c->users->find_by_login_name("guest"))
Truth table0%0/4
A && B and C
A= $c->is_user_authenticatedB= $c->logoutC= $c->user($c->users->find_by_login_name("guest"))
ABCresult
0XX0
10X0
1100
1111
176 if $c->is_user_authenticated;
177 0 my $token = $c->param('token');
178 0 my $t = time;
179 0 my $row = $c->dbx->db->select(
180 first_login => '*',
181 {start_date => {'<=' => $t}, stop_date => {'>' => $t}, token => $token})->hash;
182 0 ▶ unless (defined $row) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $row) 0 0 0
183 0 $c->stash('error_message' => $msg_expired_token);
184 0 ▶ $c->app->log->error('Token for first_login_form was not found for user comming from '
Condition0%0/2
$c->req->headers->referrer || 'nowhere'
l!l
00
MC/DC0%0/1
$c->req->headers->referrer || 'nowhere'
$c->req->headers->referrer
Truth table0%0/2
A
A= $c->req->headers->referrer
Aresult
11
00
185 . ($c->req->headers->referrer || 'nowhere')
186 . '.');
187 }
188 0 return $c->render(row => $row);
189 }
190  
191 # POST /first_login
192 1 ▶sub first_login ($c) {
Subroutine first_login: called CC=4 SCAR=22.6
Pod documented
193 1 state $app = $c->app;
194 1 my $token = $c->param('token');
195 1 my $t = time;
196 1 my $row = $c->dbx->db->select(
197 first_login => '*',
198 {start_date => {'<=' => $t}, stop_date => {'>' => $t}, token => $token})->hash;
199 1 ▶ unless (defined $row) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $row) 1 0 1
200 1 $c->stash(error_message => $msg_expired_token);
201 1 return $c->render('auth/first_login_form');
202  
203 }
204 0 my $v = $c->validation;
205 0 $v->required('first_name', 'trim')->required('last_name', 'trim');
206 0 my $in = $v->output;
207 my $ok = (
208 sha1_sum(
209 $row->{start_date}
210 . encode('UTF-8' => $in->{first_name} . $in->{last_name})
211 . $row->{from_uid}
212 . $row->{to_uid}
213 0 ) eq $token
214 );
215 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
216 0 $c->stash(error_message => 'Моля, въведете имената на човека,'
217 . ' създал вашата сметка, както са изписани в'
218 . ' електроннто съобщение с препратката за първо влизане.');
219 0 return $c->render(template => 'auth/first_login_form', row => $row);
220 }
221 0 ▶ if ($INC{'Slovo/Task/SendOnboardingEmail.pm'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($INC{'Slovo/Task/SendOnboardingEmail.pm'}) { } 0 0 0
222 0 $app->minion->enqueue(delete_first_login => [$row->{to_uid}, $token]);
223 }
224 else {
225 0 $app->dbx->db->delete('first_login' => {token => $token, user_id => $row->{to_uid}});
226  
227 # also delete expired but not deleted (for any reason) login tokens.
228 0 $app->dbx->db->delete('first_login' => {stop_date => {'<=' => time}});
229 }
230 0 $c->users->save($row->{to_uid}, {disabled => 0});
231 0 $c->authenticate(undef, undef, {auto_validate => $row->{to_uid}});
232 0 return $c->redirect_to('edit_users' => {id => $row->{to_uid}});
233 }
234  
235 # GET /lost_password
236 2 ▶sub lost_password_form ($c) {
Subroutine lost_password_form: called CC=4 SCAR=14.2
Pod documented
237 2 ▶ if ($c->req->method eq 'POST') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->req->method eq "POST") 1 1 2
238 1 my $v = $c->validation;
239 1 $v->required('email', 'trim')->like(qr/^[\w\-\+\.]{1,154}\@[\w\-\+\.]{1,100}$/x);
240 1 my $in = $v->output;
241  
242 1 ▶ if ($INC{'Slovo/Task/SendPasswEmail.pm'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($INC{"Slovo/Task/SendPasswEmail.pm"}) 1 0 1
243  
244 # send email to the user to login with a temporary password and change his
245 # password.
246 1 ▶ if (my $user = $c->users->find_where({email => $in->{email}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $user = $c->users->find_where({'email', $in->{'email'}})) { } 0 1 1
247 0 my $job_id
248 = $c->minion->enqueue(mail_passw_login => [$user, $c->req->headers->host]);
249 }
250 else {
251 1 $c->app->log->warn('User not found by email to send temporary login password.');
252 }
253 }
254 }
255 2 return $c->render();
256  
257 }
258  
259 15 1;
260  
261 =encoding utf8
262  
263 =head1 NAME
264  
265 Slovo::Controller::Auth - и миръ Его не позна.
266  
267 =head1 DESCRIPTION
268  
269 L<Slovo::Controller::Auth> implements actions for authenticating users. It
270 depends on functionality, provided by L<Mojolicious::Plugin::Authentication>.
271 All the routes' paths mentioned below are easily modifiable because they are
272 described in C<lib/Slovo/resources/etc/routes.conf> thanks to
273 L<Mojolicious::Plugin::RoutesConfig>.
274  
275 =head1 ACTIONS
276  
277 Mojolicious::Plugin::Authentication implements the following actions.
278  
279 =head2 first_login_form
280  
281 Displays a form for confirmation of the names of the user who invited the new
282 user.
283  
284 GET /first_login/<token:fl_token>
285  
286 C<fl_token> is a route type matching C<qr/[a-f0-9]{40}/>.
287  
288 =head2 first_login
289  
290 Compares the entered names of the inviting user with the token and makes other
291 checks. Signs in the user for the first time.
292  
293 =head2 form
294  
295 Route: C<{get =E<gt> '/in', to =E<gt> 'auth#form', name =E<gt> 'authform'}>.
296  
297 Renders a login form. The password is never transmitted in plain text. A digest
298 is prepared in the browser using JavaScript (see
299 C<lib/Slovo/resources/templates/auth/form.html.ep>). The digest is sent and
300 compared on the server side. The digest is different in every POST request.
301  
302 =head2 lost_password_form
303  
304 Route:
305  
306 {
307 any => '/lost_password',
308 to => 'auth#lost_password_form',
309 name => 'lost_password_form'
310 },
311  
312 In case the request is not C<POST> C<$c-E<gt>url_for('lost_password_form')> displays a form
313 for entering email to which a temporary password to be send. If the request
314 method is C<POST>, enqueues L<Slovo::Task::SendPasswEmail/mail_passw_login>, if a
315 user with the given email is found in the database.
316  
317 =head2 sign_in
318  
319 Route: C<{post =E<gt> '/in', to =E<gt> 'auth#sign_in', name =E<gt> 'sign_in'}>.
320  
321 Finds and logs in a user locally. On success redirects the user to
322 L<home_upravlenie|Slovo::Cotroller::Upravlenie/index>. On failure redirects
323 again to the login page.
324  
325 =head2 under_management
326  
327 This is a callback when user tries to access a page I<under> C</manage>. If
328 user is authenticated returns true. If not, returns false and redirects to
329 L</form>.
330  
331 =head2 under_minion
332  
333  
334 Allow access to only authenticated members of the admin group. All routes
335 generated by L<Minion::Admin> are under this route.
336  
337 GET /manage/minion
338  
339  
340 =head2 METHODS
341  
342 L<Slovo::Controller::Auth> inherits all methods from L<Slovo::Controller> and
343 implements the following new ones.
344  
345 =head1 FUNCTIONS
346  
347 Slovo::Controller::Auth implements the following functions executed or used by
348 L<Mojolicious::Plugin::Authentication>.
349  
350 =head2 current_user_fn
351  
352 Returns the name of the helper used for getting the properties of the current
353 user. The name is C<user>. It is passed in configuration to
354 L<Mojolicious::Plugin::Authentication> to generate the helper with this name.
355 This value must not be changed. Otherwise you will get runtime errors all over
356 the place because C<$c-E<gt>user> is used a lot.
357  
358 =head2 load_user
359  
360 This function is passed to L<Mojolicious::Plugin::Authentication> as reference.
361 See L<Mojolicious::Plugin::Authentication/USER-LOADING>.
362  
363  
364 =head2 validate_user
365  
366 This function is passed to L<Mojolicious::Plugin::Authentication> as reference.
367 See L<Mojolicious::Plugin::Authentication/USER-VALIDATION>.
368  
369  
370 =head1 SEE ALSO
371  
372 L<Mojolicious::Plugin::Authentication>,
373 L<Slovo::Task::SendOnboardingEmail>
374  
375 =cut
↑ Summary blib/lib/Slovo/Plugin/CGI.pm »