fix pod
[freeside.git] / FS / FS / access_user.pm
1 package FS::access_user;
2
3 use strict;
4 use vars qw( @ISA $DEBUG $me $conf $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   $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
48 inherits from 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 Returns links to the the groups this user is a part of, as FS::access_usergroup
278 objects (see L<FS::access_usergroup>).
279
280 =cut
281
282 sub access_usergroup {
283   my $self = shift;
284   qsearch( 'access_usergroup', { 'usernum' => $self->usernum } );
285 }
286
287 #=item access_groups
288 #
289 #=cut
290 #
291 #sub access_groups {
292 #
293 #}
294 #
295 #=item access_groupnames
296 #
297 #=cut
298 #
299 #sub access_groupnames {
300 #
301 #}
302
303 =item agentnums 
304
305 Returns a list of agentnums this user can view (via group membership).
306
307 =cut
308
309 sub agentnums {
310   my $self = shift;
311   my $sth = dbh->prepare(
312     "SELECT DISTINCT agentnum FROM access_usergroup
313                               JOIN access_groupagent USING ( groupnum )
314        WHERE usernum = ?"
315   ) or die dbh->errstr;
316   $sth->execute($self->usernum) or die $sth->errstr;
317   map { $_->[0] } @{ $sth->fetchall_arrayref };
318 }
319
320 =item agentnums_href
321
322 Returns a hashref of agentnums this user can view.
323
324 =cut
325
326 sub agentnums_href {
327   my $self = shift;
328   scalar( { map { $_ => 1 } $self->agentnums } );
329 }
330
331 =item agentnums_sql [ HASHREF | OPTION => VALUE ... ]
332
333 Returns an sql fragement to select only agentnums this user can view.
334
335 Options are passed as a hashref or a list.  Available options are:
336
337 =over 4
338
339 =item null
340
341 The frament will also allow the selection of null agentnums.
342
343 =item null_right
344
345 The fragment will also allow the selection of null agentnums if the current
346 user has the provided access right
347
348 =item table
349
350 Optional table name in which agentnum is being checked.  Sometimes required to
351 resolve 'column reference "agentnum" is ambiguous' errors.
352
353 =back
354
355 =cut
356
357 sub agentnums_sql {
358   my( $self ) = shift;
359   my %opt = ref($_[0]) ? %{$_[0]} : @_;
360
361   my $agentnum = $opt{'table'} ? $opt{'table'}.'.agentnum' : 'agentnum';
362
363 #  my @agentnums = map { "$agentnum = $_" } $self->agentnums;
364   my @agentnums = ();
365   push @agentnums, "$agentnum IN (". join(',', $self->agentnums). ')';
366
367   push @agentnums, "$agentnum IS NULL"
368     if $opt{'null'}
369     || ( $opt{'null_right'} && $self->access_right($opt{'null_right'}) );
370
371   return ' 1 = 0 ' unless scalar(@agentnums);
372   '( '. join( ' OR ', @agentnums ). ' )';
373
374 }
375
376 =item agentnum
377
378 Returns true if the user can view the specified agent.
379
380 =cut
381
382 sub agentnum {
383   my( $self, $agentnum ) = @_;
384   my $sth = dbh->prepare(
385     "SELECT COUNT(*) FROM access_usergroup
386                      JOIN access_groupagent USING ( groupnum )
387        WHERE usernum = ? AND agentnum = ?"
388   ) or die dbh->errstr;
389   $sth->execute($self->usernum, $agentnum) or die $sth->errstr;
390   $sth->fetchrow_arrayref->[0];
391 }
392
393 =item agents
394
395 Returns the list of agents this user can view (via group membership), as
396 FS::agent objects.
397
398 =cut
399
400 sub agents {
401   my $self = shift;
402   qsearch({
403     'table'     => 'agent',
404     'hashref'   => { disabled=>'' },
405     'extra_sql' => ' AND '. $self->agentnums_sql,
406   });
407 }
408
409 =item access_right RIGHTNAME | LISTREF
410
411 Given a right name or a list reference of right names, returns true if this
412 user has this right, or, for a list, one of the rights (currently via group
413 membership, eventually also via user overrides).
414
415 =cut
416
417 sub access_right {
418   my( $self, $rightname ) = @_;
419
420   $rightname = [ $rightname ] unless ref($rightname);
421
422   warn "$me access_right called on ". join(', ', @$rightname). "\n"
423     if $DEBUG;
424
425   #some caching of ACL requests for low-hanging fruit perf improvement
426   #since we get a new $CurrentUser object each page view there shouldn't be any
427   #issues with stickiness
428   if ( $self->{_ACLcache} ) {
429
430     unless ( grep !exists($self->{_ACLcache}{$_}), @$rightname ) {
431       warn "$me ACL cache hit for ". join(', ', @$rightname). "\n"
432         if $DEBUG;
433       return grep $self->{_ACLcache}{$_}, @$rightname
434     }
435
436     warn "$me ACL cache miss for ". join(', ', @$rightname). "\n"
437       if $DEBUG;
438
439   } else {
440
441     warn "initializing ACL cache\n"
442       if $DEBUG;
443     $self->{_ACLcache} = {};
444
445   }
446
447   my $has_right = ' rightname IN ('. join(',', map '?', @$rightname ). ') ';
448
449   my $sth = dbh->prepare("
450     SELECT groupnum FROM access_usergroup
451                     LEFT JOIN access_group USING ( groupnum )
452                     LEFT JOIN access_right
453                          ON ( access_group.groupnum = access_right.rightobjnum )
454       WHERE usernum = ?
455         AND righttype = 'FS::access_group'
456         AND $has_right
457       LIMIT 1
458   ") or die dbh->errstr;
459   $sth->execute($self->usernum, @$rightname) or die $sth->errstr;
460   my $row = $sth->fetchrow_arrayref;
461
462   my $return = $row ? $row->[0] : '';
463
464   #just caching the single-rightname hits should be enough of a win for now
465   if ( scalar(@$rightname) == 1 ) {
466     $self->{_ACLcache}{${$rightname}[0]} = $return;
467   }
468
469   $return;
470
471 }
472
473 =item default_customer_view
474
475 Returns the default customer view for this user, from the 
476 "default_customer_view" user preference, the "cust_main-default_view" config,
477 or the hardcoded default, "jumbo" (may change to "basics" in the near future).
478
479 =cut
480
481 sub default_customer_view {
482   my $self = shift;
483
484   $self->option('default_customer_view')
485     || $conf->config('cust_main-default_view')
486     || 'jumbo'; #'basics' in 1.9.1?
487
488 }
489
490 =back
491
492 =head1 BUGS
493
494 =head1 SEE ALSO
495
496 L<FS::Record>, schema.html from the base documentation.
497
498 =cut
499
500 1;
501