Auth.pm 11.2 KB
Newer Older
Benjamin Rokseth's avatar
Benjamin Rokseth committed
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
package Deichman::Auth;

use strict;
use warnings;

use Data::Dumper;
use parent "Deichman::Main";
use Try::Tiny;

use C4::Context;

use Deichman::Auth::Simple;
use Deichman::Auth::LDAP;
use Deichman::Auth::CAS;

use Deichman::Exception;
use Deichman::Patron;
use Deichman::Library;

=head

Top level auth class to delegate authentication (and permissions)
session object stored in DB or memory with auth object to handle permissions:
{ auth =>
  { user => { userid => "x", username => "xx"},
    permissions => { superlibrarian => 1, borrowers => 1 ...},
  }
}

=cut

sub new {
    my ( $class, $session, $req ) = @_;
    my $self = $class->SUPER::new();
    $self = { %$self,
        session => $session,
        req     => $req,
    };
    bless $self, $class;
    return $self;
}

# Top level Auth method
sub Auth {
    my ($self) = @_;
    warn "AUTH CALLED";
    my $session = $self->{session};
    my $req     = $self->{req};

    $session or Deichman::Exception::Auth::InvalidSession->throw();
    $req     or Deichman::Exception::Auth::InvalidQuery->throw();

53
54
    C4::Context->_new_userenv( $session->id );

Benjamin Rokseth's avatar
Benjamin Rokseth committed
55
    if ($req->param("logout.x") ) {
56
        $self->LogOut();
Benjamin Rokseth's avatar
Benjamin Rokseth committed
57
58
59
60
    }
    # validate session
    my $auth = $session->get("auth");
    if ($auth) {
61
        warn "GOT AUTHENTICATED SESSION";
Benjamin Rokseth's avatar
Benjamin Rokseth committed
62
63
        return;
    } else {
64
        warn "NO AUTH SESSION - TRYING TO CREATE ONE";
Benjamin Rokseth's avatar
Benjamin Rokseth committed
65
66
        # Run all auth methods
        my $auth = $self->checkAuthMethods();
67
        $auth or Deichman::Exception::Auth::InvalidSession->throw();
Benjamin Rokseth's avatar
Benjamin Rokseth committed
68
69
        $session->put(auth => $auth);
    }
70
    use Data::Dumper; warn Dumper($session);
Benjamin Rokseth's avatar
Benjamin Rokseth committed
71
72
73
74
75
    # decorate session with library, etc.
    if ( my $userid = $session->param("userid") // $session->param("id") ) { # 'id' will be set for admin user as well
        my $branchcode = $req->param("branch") || $auth->{branchcode};
        try {
            my $lib = Deichman::Library->new()->Get($branchcode)->{library};
76
            $session->param(branch => $lib->{branchcode});
Benjamin Rokseth's avatar
Benjamin Rokseth committed
77
78
79
            $session->param(branchname => $lib->{branchname});
        } catch {
            warn $_->description;
80
            $session->param(branch => "NO_LIBRARY_SET");
Benjamin Rokseth's avatar
Benjamin Rokseth committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
            $session->param(branchname => "NO_LIBRARY_SET");
        };

        # Set C4::Context user env
        C4::Context->set_userenv(
            $session->param("number"),
            $userid,
            map { $session->param($_); } qw/
                cardnumber firstname surname branch branchname
                flags emailaddress branchprinter shibbolet/,
        );
        # No idea what this is? Virtualshelves?
        C4::Context::set_shelves_userenv( "bar", $session->param("barshelves") );
        C4::Context::set_shelves_userenv( "pub", $session->param("pubshelves") );
        C4::Context::set_shelves_userenv( "tot", $session->param("totshelves") );
    }
97
    # Should Auth return something?
Benjamin Rokseth's avatar
Benjamin Rokseth committed
98
99
100
    return;
}

101
102
103
104
105
106
107
sub LogOut {
    my ($self) = @_;
    warn "LOGOUT CALLED";
    $self->{session}->clear();
    return $self;
}

Benjamin Rokseth's avatar
Benjamin Rokseth committed
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
# Try various Auth methods in given sequence
sub checkAuthMethods {
    my ($self) = @_;
    my $session = $self->{session};
    my $req     = $self->{req};

    my $auth;
    for my $class (qw/
        Deichman::Auth::Simple
        Deichman::Auth::LDAP
        Deichman::Auth::CAS
    /) {
        try {
            warn $class;
            $auth = $class->new()->DoAuth($session, $req);
        } catch {
            warn $_->description;
        };
        $auth->{auth} and return $auth->{auth};
    }
}

# used by C4 modules, like Language
sub param {
    my ($self, $key, @val) = @_;
    $self->{session}->param($key, @val);
}

# used by C4 modules, like Language
sub cookie {
    my ($self, $name, @value) = @_;
    #print STDERR Dumper($self, "cookie($name)", @value);
    $self->{req}->cookies->{$name};
}

# Differ from C4/Auth, it returns empty hashes for modules without submodules
sub getAllPermissions {
    my ($self) = @_;
    my $dbh = $self->dbh;
    my $sth = $dbh->prepare( "SELECT flag, code FROM userflags LEFT JOIN permissions ON (module_bit = bit)" );
    $sth->execute();

    my $all_perms = {};
    while ( my $row = $sth->fetchrow_hashref ) {
        my $flag = $row->{flag};
        my $code = $row->{code};
        my $module = $all_perms->{$flag} //= {};
        $module->{$code} = 1 if $code;
    }
    return $all_perms;
}

# this is where CGI scripts ask for permissions
sub templateAndPermissions {
    my ($self, $in) = @_;
    warn "TEMPLATE_AND_PERMISSIONS";
    my $name = $in->{template_name} or Deichman::Exception::Auth::MissingTemplate->throw();
    $name =~ m{^[a-zA-Z0-9_\-\/]+.tt$} or Deichman::Exception::Auth::InvalidTemplate->throw($name);

    # Use new auth object
    my $auth   = $self->{session}->get("auth");
169
170
    my $branch = $self->{session}->param("branchname") || $auth->{user}->{branchcode}; # session param overrides stored branch
    my $userid = $self->{session}->param("userid")     || $auth->{user}->{userid};     # session param overrides stored userid
Benjamin Rokseth's avatar
Benjamin Rokseth committed
171
172
    my $flags = $in->{flagsrequired};

173
    #use Data::Dumper; warn Dumper($auth);
Benjamin Rokseth's avatar
Benjamin Rokseth committed
174
175
    my $info = {};

176
177
178
179
    # no session - present login page
    if (not $userid) {
        my $template = C4::Templates::gettemplate( "auth.tt", $in->{type}, $self);
        $template->param( loginprompt => 1, error => $self->{session}->get("error") );
Benjamin Rokseth's avatar
Benjamin Rokseth committed
180
181
182
        return $template;
    }

Benjamin Rokseth's avatar
Benjamin Rokseth committed
183
    my $template = C4::Templates::gettemplate( $name, $in->{type}, $self, $in->{is_plugin} ); # this is weird...
Benjamin Rokseth's avatar
Benjamin Rokseth committed
184
185
186
187
188
189
190
191
192
193

    #if ( $in->{'template_name'} !~ m/maintenance/ ) {
    #    ( $user, $cookie, $sessionID, $flags ) = checkauth(
    #            $in->{'query'},
    #            $in->{'authnotrequired'},
    #            $in->{'flagsrequired'},
    #            $in->{'type'}
    #    );
    #}

Benjamin Rokseth's avatar
Benjamin Rokseth committed
194
    $self->setTemplatePermissions( $template, $auth, $branch );
195
    $self->setCustomTemplateParams( $template ); # Various overrides from previous C4::Auth::get_template_and_user
Benjamin Rokseth's avatar
Benjamin Rokseth committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    return $template;
}

# set template permissions from auth object
sub setTemplatePermissions {
    my ($self, $template, $auth, $branch) = @_;

    $template->param( LoginBranchname => $branch );
    my $id = $self->{session}->param("id");
    if ($self->{session}->param("admin")) {
        # Admin user login should be removed!
        warn "TEMPLATE CALLED WITH ADMINUSER - BETTER REMOVE THIS";
        $auth->{permissions} = { superlibrarian => 1 };
        $template->param(loggedinusername => $id);
210
        $template->param(adminWarning => 1);
Benjamin Rokseth's avatar
Benjamin Rokseth committed
211
212
213
214
215
    } else {
        $template->param("USER_INFO" => $auth->{user});
        $template->param(loggedinusername => $auth->{user}->{userid});
        $template->param(loggedinusernumber => $auth->{user}->{borrowernumber}); # for legacy?
    }
Benjamin Rokseth's avatar
Benjamin Rokseth committed
216
217
218
219
220
221
222
223
224
225
226
227

    my $all_perms = $self->getAllPermissions();
    for my $name (keys %$all_perms ) {
        my $value = $auth->{permissions}->{superlibrarian} ? 1 : $auth->{permissions}->{$name};
        $value //= 0;
        #warn "$name => $value";
        next unless $value;

        # expand a true value to a list of submodules;
        $value = $all_perms->{$name} unless ref $value;

        $template->param( "CAN_user_${name}" => 1 );
Benjamin Rokseth's avatar
Benjamin Rokseth committed
228
        # subpermissions
Benjamin Rokseth's avatar
Benjamin Rokseth committed
229
230
231
        for my $subname ( keys %$value ) {
            $template->param( "CAN_user_${name}_${subname}" => 1 );
        }
Benjamin Rokseth's avatar
Benjamin Rokseth committed
232
233
234
        # deviations
        $template->param( "CAN_user_management" => 1 ) if $name eq "parameters";
        $template->param( "CAN_user_catalogue" => 1 ) if $name eq "editcatalogue";
Benjamin Rokseth's avatar
Benjamin Rokseth committed
235
236
237
    }
    return $template;
}
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

# TODO: this should be handled by core prefs module
# Various overrides from previous C4::Auth::get_template_and_user
sub setCustomTemplateParams {
    my ($self, $template) = @_;
    $template->param(
        dateformat => "dmydot", # dd.mm.yyyy
        minPasswordLength => "0",
        EnhancedMessagingPreferences => "1",
        KohaAdminEmailAddress => 'noreply@deichman.no',
        UseKohaPlugins => "1",

        # from Auth
        # LoginBranchcode => C4::Context->userenv->{"branch"},
        # LoginFirstname  => C4::Context->userenv->{"firstname"},
        # LoginSurname    => C4::Context->userenv->{"surname"},
        # emailaddress    => C4::Context->userenv->{"emailaddress"},

        # unused
        # TagsEnabled     => C4::Context->preference("TagsEnabled"),
        # hide_marc       => C4::Context->preference("hide_marc"),
        # item_level_itypes  => C4::Context->preference('item-level_itypes'),
        # XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
        # XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
        # using_https        => 0,
        # noItemTypeImages   => C4::Context->preference("noItemTypeImages"),
        # marcflavour        => C4::Context->preference("marcflavour"),
        # AmazonCoverImages               => C4::Context->preference("AmazonCoverImages"),
        # AutoLocation                    => C4::Context->preference("AutoLocation"),
        # CircAutocompl                   => C4::Context->preference("CircAutocompl"),
        # FRBRizeEditions                 => C4::Context->preference("FRBRizeEditions"),
        # IndependentBranches             => C4::Context->preference("IndependentBranches"),
        # IntranetNav                     => C4::Context->preference("IntranetNav"),
        # IntranetmainUserblock           => C4::Context->preference("IntranetmainUserblock"),
        # LibraryName                     => C4::Context->preference("LibraryName"),
        # LoginBranchname                 => ( C4::Context->userenv ? C4::Context->userenv->{"branchname"} : undef ),
        # advancedMARCEditor              => C4::Context->preference("advancedMARCEditor"),
        # canreservefromotherbranches     => C4::Context->preference('canreservefromotherbranches'),
        # intranetcolorstylesheet         => C4::Context->preference("intranetcolorstylesheet"),
        # IntranetFavicon                 => C4::Context->preference("IntranetFavicon"),
        # intranetreadinghistory          => C4::Context->preference("intranetreadinghistory"),
        # intranetstylesheet              => C4::Context->preference("intranetstylesheet"),
        # IntranetUserCSS                 => C4::Context->preference("IntranetUserCSS"),
        # IntranetUserJS                  => C4::Context->preference("IntranetUserJS"),
        # intranetbookbag                 => C4::Context->preference("intranetbookbag"),
        # suggestion                      => C4::Context->preference("suggestion"),
        # virtualshelves                  => C4::Context->preference("virtualshelves"),
        # StaffSerialIssueDisplayCount    => C4::Context->preference("StaffSerialIssueDisplayCount"),
        # EasyAnalyticalRecords           => C4::Context->preference('EasyAnalyticalRecords'),
        # LocalCoverImages                => C4::Context->preference('LocalCoverImages'),
        # OPACLocalCoverImages            => C4::Context->preference('OPACLocalCoverImages'),
        # AllowMultipleCovers             => C4::Context->preference('AllowMultipleCovers'),
        # EnableBorrowerFiles             => C4::Context->preference('EnableBorrowerFiles'),
        # UseCourseReserves               => C4::Context->preference("UseCourseReserves"),
        # useDischarge                    => C4::Context->preference('useDischarge'),
    );
}


Benjamin Rokseth's avatar
Benjamin Rokseth committed
297
1;