aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Fripost/Panel/Login.pm
blob: 1fca602d80a16f8a2705815ce01e787e742d1fba (plain)
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
package Fripost::Panel::Login;

use 5.010_000;
use strict;
use warnings;
use utf8;

=head1 NAME

Login.pm - Authentication subroutines for the Web Interface.

=cut

use parent 'CGI::Application';
use CGI::Application::Plugin::AutoRunmode;
use CGI::Application::Plugin::Session;
use CGI::Application::Plugin::Authentication;
use CGI::Application::Plugin::Redirect;
use CGI::Application::Plugin::ConfigAuto 'cfg';

use Fripost::Schema;

use HTML::Entities 'encode_entities';
use URI::Escape::XS 'decodeURIComponent';
use Encode ();

# This method is called right before the 'setup' method below. It
# initializes the session and authentication configurations.
sub cgiapp_init {
    my $self = shift;

    my %CFG = $self->cfg;

    $self->session_config(
        CGI_SESSION_OPTIONS => [ 'driver:DB_File;serializer:freezethaw'
                               , $self->query
                               , { FileName => $CFG{session_db_filename},
                                   UMask => 0600 }
                               , { name => $CFG{session_authname} }
                               ],
        DEFAULT_EXPIRY      => $CFG{session_expire},
        COOKIE_PARAMS       => { -name     => $CFG{session_authname}
                               , -path     => $CFG{'cgi-bin'}
                               # Expires when the browser quits
                               , -expires  => -1
                               ,'-max-age' => -1
                               , -secure   => $CFG{secure_cookie}
                               # We are not using JavaScript in this framework
                               , -httponly => 1
                               },
       SEND_COOKIE          => 1,
    );

    # Configure authentication parameters
    $self->authen->config(
        DRIVER                => [ 'Generic', sub {
            my ($u,$p) = @_;
            unless ($u =~ /\@/) {
                $CFG{default_realm} // return 0;
                $u .= '@'.$CFG{default_realm};
            }
            my $fp = Fripost::Schema::->auth($u, $p, \%CFG, -error => undef)
                         // return 0;
            $fp->done;
            return $u;
        } ],
        STORE                 => 'Session',
        LOGIN_RUNMODE         => 'login',
        RENDER_LOGIN          => \&login_box,
        LOGIN_SESSION_TIMEOUT => { IDLE_FOR => $CFG{timeout} },
        LOGOUT_RUNMODE        => 'logout',
    );

    # The run modes that require authentication
    $self->authen->protected_runmodes( qw/okay error_rm/ );
}


# This method is called by the inherited new() constructor method.
# It defines the path for templates and chooses the Run Mode depending
# on the URL and query string.
sub setup {
    my $self = shift;
    $self->header_props( -charset=>'utf-8' );

    $self->tmpl_path( $self->cfg('tmpl_path') );

    $self->mode_param( sub {
        my $self = shift;
        my $q = $self->query;

        # The user just logged in
        return 'okay' if defined $q->param('login');
        my $a = $q->param('a');

        return 'login' if defined $a and $a eq 'login';
        return 'logout' if defined $a and $a eq 'logout';

        # /domain/{user,alias,list}/?query_url
        my ($null,$domain,$local,$crap) = $self->split_path;

        return 'ListDomains' if $null;

        unless ($domain) {
            if (defined $a) {
                return 'AddDomain' if $a eq 'add';
            }
            return 'ListDomains';
        }

        unless ($local) {
            if (defined $a) {
                return 'EditDomain' if $a eq 'edit';
                return 'AddLocal' if $a eq 'add';
            }
            return 'ListLocals';
        }

        return 'EditLocal';
    });
}


# This Run Mode redirects the freshly logged in user to the URL s/he
# wanted to visit.
sub okay : Runmode {
    my $self = shift;
    my $redirect = $self->query->param('redirect') // $self->query->url;
    return $self->redirect($redirect);
}


# This is the login Run Mode.
sub login : Runmode {
    my $self = shift;

    # A logged user has no reason to ask for a relogin, so s/he is seen as
    # an intruder
    $self->authen->logout if $self->authen->is_authenticated;

    # Do not come back here on the next Run Mode
    $self->query->delete('a') if defined $self->query->param('a') and
                                 $self->query->param('a') eq 'login';

    # Where the users wants to go
    $self->query->param( redirect => $self->query->self_url)
        unless defined $self->query->param('redirect');

    return $self->login_box;
}


# This method loads the login form.
sub login_box {
    my $self = shift;

    my $template = $self->load_tmpl( 'login.html', cache => 1 );
    $template->param( error => $self->authen->login_attempts );
    $template->param( redirect => $self->query->param('redirect') );

    return $template->output;
}


# This is the logout Run Mode.
sub logout : Runmode {
    my $self = shift;

    if ($self->authen->is_authenticated) {
        # Log out the user, delete the session and flush it off the disk
        $self->authen->logout;
        $self->session->delete;
        $self->session->flush;
    }

    # Do not come back here on the next Run Mode
    $self->query->delete('a') if defined $self->query->param('a') and
                                 $self->query->param('a') eq 'logout';

    return $self->redirect( ($ENV{SCRIPT_NAME} // $self->query->url).'/' );
}

# This is the error Run Mode.
sub error_rm : ErrorRunmode {
    my $self = shift;
    my $error = shift;

    if ($error =~ /^4\d+$/) {
        # HTTP client error.
        chomp $error;
        $self->header_props ( -status => $error );
        my $template = $self->load_tmpl( 'error_http.html', cache => 1 );
        my $mesg;
        if ($error eq '403' ) {
            $mesg = 'Forbidden'
        }
        elsif ($error eq '404' ) {
            $mesg = 'Not Found'
        }
        $template->param( code => $error );
        $template->param( message => encode_entities ($mesg) );
        return $template->output;
    }

    else {
        # Users are not supposed to see that unless the CGI crashes :P
        my $template = $self->load_tmpl( 'error.html', cache => 1 );
        $template->param( email => $self->cfg('report_email') );
        $template->param( message => encode_entities ($error) );
        $template->param( url => $self->query->url . '/');
        return $template->output;
    }
}

# Split the URI; give the list of its components.
# The facing CGI script and trailing query are not considered.
sub split_path {
    my $self = shift;
    my %options = @_;

    my $script = $ENV{SCRIPT_NAME} // $self->cfg->{'cgi-bin'} // '';
    $script =~ s@/$@@s; # Strip the trailing '/' off the script name

    my $uri = $self->query->request_uri;
    $uri =~ s/^\Q$script\E\b//s; # Strip the facing CGI script name
    $uri =~ s/\?.*//s;           # Strip the query

    map { my $x = decodeURIComponent($_); Encode::_utf8_on($x); $x }
        (split '/', $uri);
}


=head1 AUTHOR

Guilhem Moulin C<< <guilhem at fripost.org> >>

=head1 COPYRIGHT

Copyright 2012,2013 Guilhem Moulin.

=head1 LICENSE

This program is free software; you can redistribute it and/or modify it
under the same terms as perl itself.

=cut

1;

__END__