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