| 1 | package Yukki::Web::Controller::Login; | ||
| 2 | { | ||
| 3 | $Yukki::Web::Controller::Login::VERSION = '0.140290'; | ||
| 4 | } | ||
| 5 | use 5.12.1; | ||
| 6 | use Moose; | ||
| 7 | |||
| 8 | with 'Yukki::Web::Controller'; | ||
| 9 | |||
| 10 | use Yukki::Error qw( http_throw ); | ||
| 11 | |||
| 12 | # ABSTRACT: shows the login page and handles login | ||
| 13 | |||
| 14 | |||
| 15 | sub fire { | ||
| 16 | my ($self, $ctx) = @_; | ||
| 17 | |||
| 18 | my $res; | ||
| 19 | given ($ctx->request->path_parameters->{action}) { | ||
| 20 | when ('page') { $self->show_login_page($ctx) } | ||
| 21 | when ('submit') { $self->check_login_submission($ctx) } | ||
| 22 | when ('exit') { $self->logout($ctx) } | ||
| 23 | default { http_throw('That login action does not exist.', { | ||
| 24 | status => 'NotFound', | ||
| 25 | }) } | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | |||
| 30 | sub show_login_page { | ||
| 31 | my ($self, $ctx) = @_; | ||
| 32 | |||
| 33 | $ctx->response->body( $self->view('Login')->page($ctx) ); | ||
| 34 | } | ||
| 35 | |||
| 36 | |||
| 37 | sub check_password { | ||
| 38 | my ($self, $user, $password) = @_; | ||
| 39 | |||
| 40 | return scalar $self->app->hasher->validate( | ||
| 41 | $user->{password}, | ||
| 42 | $password, | ||
| 43 | ); | ||
| 44 | } | ||
| 45 | |||
| 46 | |||
| 47 | sub check_login_submission { | ||
| 48 | my ($self, $ctx) = @_; | ||
| 49 | |||
| 50 | my $login_name = $ctx->request->body_parameters->{login_name}; | ||
| 51 | my $password = $ctx->request->body_parameters->{password}; | ||
| 52 | |||
| 53 | my $user = $self->model('User')->find(login_name => $login_name); | ||
| 54 | |||
| 55 | if (not ($user and $self->check_password($user, $password))) { | ||
| 56 | $ctx->add_errors('no such user or you typed your password incorrectly'); | ||
| 57 | } | ||
| 58 | |||
| 59 | if ($ctx->has_errors) { | ||
| 60 | $self->show_login_page($ctx); | ||
| 61 | return; | ||
| 62 | } | ||
| 63 | |||
| 64 | else { | ||
| 65 | $ctx->session->{user} = $user; | ||
| 66 | |||
| 67 | $ctx->response->redirect($ctx->rebase_url('page/view/main')); | ||
| 68 | return; | ||
| 69 | } | ||
| 70 | } | ||
| 71 | |||
| 72 | |||
| 73 | sub logout { | ||
| 74 | my ($self, $ctx) = @_; | ||
| 75 | |||
| 76 | $ctx->session_options->{expire} = 1; | ||
| 77 | $ctx->response->redirect($ctx->rebase_url('page/view/main')); | ||
| 78 | } | ||
| 79 | |||
| 80 | 1; | ||
| 81 | |||
| 82 | __END__ |