oops, adding multiple-rightname support broke ACL caching, bringing it back should...
[freeside.git] / FS / FS / access_user.pm
1 package FS::access_user;
2
3 use strict;
4 use vars qw( @ISA $DEBUG $me $htpasswd_file );
5 use FS::UID;
6 use FS::Conf;
7 use FS::Record qw( qsearch qsearchs dbh );
8 use FS::m2m_Common;
9 use FS::option_Common;
10 use FS::access_user_pref;
11 use FS::access_usergroup;
12 use FS::agent;
13
14 @ISA = qw( FS::m2m_Common FS::option_Common FS::Record );
15 #@ISA = qw( FS::m2m_Common FS::option_Common );
16
17 $DEBUG = 0;
18 $me = '[FS::access_user]';
19
20 #kludge htpasswd for now (i hope this bootstraps okay)
21 FS::UID->install_callback( sub {
22   my $conf = new FS::Conf;
23   $htpasswd_file = $conf->base_dir. '/htpasswd';
24 } );
25
26 =head1 NAME
27
28 FS::access_user - Object methods for access_user records
29
30 =head1 SYNOPSIS
31
32   use FS::access_user;
33
34   $record = new FS::access_user \%hash;
35   $record = new FS::access_user { 'column' => 'value' };
36
37   $error = $record->insert;
38
39   $error = $new_record->replace($old_record);
40
41   $error = $record->delete;
42
43   $error = $record->check;
44
45 =head1 DESCRIPTION
46
47 An FS::access_user object represents an internal access user.  FS::access_user inherits from
48 FS::Record.  The following fields are currently supported:
49
50 =over 4
51
52 =item usernum - primary key
53
54 =item username - 
55
56 =item _password - 
57
58 =item last -
59
60 =item first -
61
62 =item disabled - empty or 'Y'
63
64 =back
65
66 =head1 METHODS
67
68 =over 4
69
70 =item new HASHREF
71
72 Creates a new internal access user.  To add the user to the database, see L<"insert">.
73
74 Note that this stores the hash reference, not a distinct copy of the hash it
75 points to.  You can ask the object for a copy with the I<hash> method.
76
77 =cut
78
79 # the new method can be inherited from FS::Record, if a table method is defined
80
81 sub table { 'access_user'; }
82
83 sub _option_table    { 'access_user_pref'; }
84 sub _option_namecol  { 'prefname'; }
85 sub _option_valuecol { 'prefvalue'; }
86
87 =item insert
88
89 Adds this record to the database.  If there is an error, returns the error,
90 otherwise returns false.
91
92 =cut
93
94 sub insert {
95   my $self = shift;
96
97   my $error = $self->check;
98   return $error if $error;
99
100   local $SIG{HUP} = 'IGNORE';
101   local $SIG{INT} = 'IGNORE';
102   local $SIG{QUIT} = 'IGNORE';
103   local $SIG{TERM} = 'IGNORE';
104   local $SIG{TSTP} = 'IGNORE';
105   local $SIG{PIPE} = 'IGNORE';
106
107   my $oldAutoCommit = $FS::UID::AutoCommit;
108   local $FS::UID::AutoCommit = 0;
109   my $dbh = dbh;
110
111   $error = $self->htpasswd_kludge();
112   if ( $error ) {
113     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
114     return $error;
115   }
116
117   $error = $self->SUPER::insert(@_);
118
119   if ( $error ) {
120     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
121
122     #make sure it isn't a dup username?  or you could nuke people's passwords
123     #blah.  really just should do our own login w/cookies
124     #and auth out of the db in the first place
125     #my $hterror = $self->htpasswd_kludge('-D');
126     #$error .= " - additionally received error cleaning up htpasswd file: $hterror"
127     return $error;
128
129   } else {
130     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
131     '';
132   }
133
134 }
135
136 sub htpasswd_kludge {
137   my $self = shift;
138   
139   #awful kludge to skip setting htpasswd for fs_* users
140   return '' if $self->username =~ /^fs_/;
141
142   unshift @_, '-c' unless -e $htpasswd_file;
143   if ( 
144        system('htpasswd', '-b', @_,
145                           $htpasswd_file,
146                           $self->username,
147                           $self->_password,
148              ) == 0
149      )
150   {
151     return '';
152   } else {
153     return 'htpasswd exited unsucessfully';
154   }
155 }
156
157 =item delete
158
159 Delete this record from the database.
160
161 =cut
162
163 sub delete {
164   my $self = shift;
165
166   local $SIG{HUP} = 'IGNORE';
167   local $SIG{INT} = 'IGNORE';
168   local $SIG{QUIT} = 'IGNORE';
169   local $SIG{TERM} = 'IGNORE';
170   local $SIG{TSTP} = 'IGNORE';
171   local $SIG{PIPE} = 'IGNORE';
172
173   my $oldAutoCommit = $FS::UID::AutoCommit;
174   local $FS::UID::AutoCommit = 0;
175   my $dbh = dbh;
176
177   my $error =
178        $self->SUPER::delete(@_)
179     || $self->htpasswd_kludge('-D')
180   ;
181
182   if ( $error ) {
183     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
184     return $error;
185   } else {
186     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
187     '';
188   }
189
190 }
191
192 =item replace OLD_RECORD
193
194 Replaces the OLD_RECORD with this one in the database.  If there is an error,
195 returns the error, otherwise returns false.
196
197 =cut
198
199 sub replace {
200   my $new = shift;
201
202   my $old = ( ref($_[0]) eq ref($new) )
203               ? shift
204               : $new->replace_old;
205
206   local $SIG{HUP} = 'IGNORE';
207   local $SIG{INT} = 'IGNORE';
208   local $SIG{QUIT} = 'IGNORE';
209   local $SIG{TERM} = 'IGNORE';
210   local $SIG{TSTP} = 'IGNORE';
211   local $SIG{PIPE} = 'IGNORE';
212
213   my $oldAutoCommit = $FS::UID::AutoCommit;
214   local $FS::UID::AutoCommit = 0;
215   my $dbh = dbh;
216
217   if ( $new->_password ne $old->_password ) {
218     my $error = $new->htpasswd_kludge();
219     if ( $error ) {
220       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
221       return $error;
222     }
223   }
224
225   my $error = $new->SUPER::replace($old, @_);
226
227   if ( $error ) {
228     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
229     return $error;
230   } else {
231     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
232     '';
233   }
234
235 }
236
237 =item check
238
239 Checks all fields to make sure this is a valid internal access user.  If there is
240 an error, returns the error, otherwise returns false.  Called by the insert
241 and replace methods.
242
243 =cut
244
245 # the check method should currently be supplied - FS::Record contains some
246 # data checking routines
247
248 sub check {
249   my $self = shift;
250
251   my $error = 
252     $self->ut_numbern('usernum')
253     || $self->ut_alpha_lower('username')
254     || $self->ut_text('_password')
255     || $self->ut_text('last')
256     || $self->ut_text('first')
257     || $self->ut_enum('disabled', [ '', 'Y' ] )
258   ;
259   return $error if $error;
260
261   $self->SUPER::check;
262 }
263
264 =item name
265
266 Returns a name string for this user: "Last, First".
267
268 =cut
269
270 sub name {
271   my $self = shift;
272   $self->get('last'). ', '. $self->first;
273 }
274
275 =item access_usergroup
276
277 =cut
278
279 sub access_usergroup {
280   my $self = shift;
281   qsearch( 'access_usergroup', { 'usernum' => $self->usernum } );
282 }
283
284 #=item access_groups
285 #
286 #=cut
287 #
288 #sub access_groups {
289 #
290 #}
291 #
292 #=item access_groupnames
293 #
294 #=cut
295 #
296 #sub access_groupnames {
297 #
298 #}
299
300 =item agentnums 
301
302 Returns a list of agentnums this user can view (via group membership).
303
304 =cut
305
306 sub agentnums {
307   my $self = shift;
308   my $sth = dbh->prepare(
309     "SELECT DISTINCT agentnum FROM access_usergroup
310                               JOIN access_groupagent USING ( groupnum )
311        WHERE usernum = ?"
312   ) or die dbh->errstr;
313   $sth->execute($self->usernum) or die $sth->errstr;
314   map { $_->[0] } @{ $sth->fetchall_arrayref };
315 }
316
317 =item agentnums_href
318
319 Returns a hashref of agentnums this user can view.
320
321 =cut
322
323 sub agentnums_href {
324   my $self = shift;
325   scalar( { map { $_ => 1 } $self->agentnums } );
326 }
327
328 =item agentnums_sql [ HASHREF | OPTION => VALUE ... ]
329
330 Returns an sql fragement to select only agentnums this user can view.
331
332 Options are passed as a hashref or a list.  Available options are:
333
334 =over 4
335
336 =item null
337
338 The frament will also allow the selection of null agentnums.
339
340 =item null_right
341
342 The fragment will also allow the selection of null agentnums if the current
343 user has the provided access right
344
345 =item table
346
347 Optional table name in which agentnum is being checked.  Sometimes required to
348 resolve 'column reference "agentnum" is ambiguous' errors.
349
350 =back
351
352 =cut
353
354 sub agentnums_sql {
355   my( $self ) = shift;
356   my %opt = ref($_[0]) ? %{$_[0]} : @_;
357
358   my $agentnum = $opt{'table'} ? $opt{'table'}.'.agentnum' : 'agentnum';
359
360 #  my @agentnums = map { "$agentnum = $_" } $self->agentnums;
361   my @agentnums = ();
362   push @agentnums, "$agentnum IN (". join(',', $self->agentnums). ')';
363
364   push @agentnums, "$agentnum IS NULL"
365     if $opt{'null'}
366     || ( $opt{'null_right'} && $self->access_right($opt{'null_right'}) );
367
368   return ' 1 = 0 ' unless scalar(@agentnums);
369   '( '. join( ' OR ', @agentnums ). ' )';
370
371 }
372
373 =item agentnum
374
375 Returns true if the user can view the specified agent.
376
377 =cut
378
379 sub agentnum {
380   my( $self, $agentnum ) = @_;
381   my $sth = dbh->prepare(
382     "SELECT COUNT(*) FROM access_usergroup
383                      JOIN access_groupagent USING ( groupnum )
384        WHERE usernum = ? AND agentnum = ?"
385   ) or die dbh->errstr;
386   $sth->execute($self->usernum, $agentnum) or die $sth->errstr;
387   $sth->fetchrow_arrayref->[0];
388 }
389
390 =item agents
391
392 Returns the list of agents this user can view (via group membership), as
393 FS::agent objects.
394
395 =cut
396
397 sub agents {
398   my $self = shift;
399   qsearch({
400     'table'     => 'agent',
401     'hashref'   => { disabled=>'' },
402     'extra_sql' => ' AND '. $self->agentnums_sql,
403   });
404 }
405
406 =item access_right RIGHTNAME | LISTREF
407
408 Given a right name or a list reference of right names, returns true if this
409 user has this right, or, for a list, one of the rights (currently via group
410 membership, eventually also via user overrides).
411
412 =cut
413
414 sub access_right {
415   my( $self, $rightname ) = @_;
416
417   $rightname = [ $rightname ] unless ref($rightname);
418
419   warn "$me access_right called on ". join(', ', @$rightname). "\n"
420     if $DEBUG;
421
422   #some caching of ACL requests for low-hanging fruit perf improvement
423   #since we get a new $CurrentUser object each page view there shouldn't be any
424   #issues with stickiness
425   if ( $self->{_ACLcache} ) {
426
427     unless ( grep !exists($self->{_ACLcache}{$_}), @$rightname ) {
428       warn "$me ACL cache hit for ". join(', ', @$rightname). "\n"
429         if $DEBUG;
430       return grep $self->{_ACLcache}{$_}, @$rightname
431     }
432
433     warn "$me ACL cache miss for ". join(', ', @$rightname). "\n"
434       if $DEBUG;
435
436   } else {
437
438     warn "initializing ACL cache\n"
439       if $DEBUG;
440     $self->{_ACLcache} = {};
441
442   }
443
444   my $has_right = ' rightname IN ('. join(',', map '?', @$rightname ). ') ';
445
446   my $sth = dbh->prepare("
447     SELECT groupnum FROM access_usergroup
448                     LEFT JOIN access_group USING ( groupnum )
449                     LEFT JOIN access_right
450                          ON ( access_group.groupnum = access_right.rightobjnum )
451       WHERE usernum = ?
452         AND righttype = 'FS::access_group'
453         AND $has_right
454       LIMIT 1
455   ") or die dbh->errstr;
456   $sth->execute($self->usernum, @$rightname) or die $sth->errstr;
457   my $row = $sth->fetchrow_arrayref;
458
459   my $return = $row ? $row->[0] : '';
460
461   #just caching the single-rightname hits should be enough of a win for now
462   if ( scalar(@$rightname) == 1 ) {
463     $self->{_ACLcache}{${$rightname}[0]} = $return;
464   }
465
466   $return;
467
468 }
469
470 =back
471
472 =head1 BUGS
473
474 =head1 SEE ALSO
475
476 L<FS::Record>, schema.html from the base documentation.
477
478 =cut
479
480 1;
481