This commit was manufactured by cvs2svn to create branch
[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   #awful kludge to skip setting htpasswd for fs_* users
137   return '' if $self->username =~ /^fs_/;
138
139   unshift @_, '-c' unless -e $htpasswd_file;
140   if ( 
141        system('htpasswd', '-b', @_,
142                           $htpasswd_file,
143                           $self->username,
144                           $self->_password,
145              ) == 0
146      )
147   {
148     return '';
149   } else {
150     return 'htpasswd exited unsucessfully';
151   }
152 }
153
154 =item delete
155
156 Delete this record from the database.
157
158 =cut
159
160 sub delete {
161   my $self = shift;
162
163   local $SIG{HUP} = 'IGNORE';
164   local $SIG{INT} = 'IGNORE';
165   local $SIG{QUIT} = 'IGNORE';
166   local $SIG{TERM} = 'IGNORE';
167   local $SIG{TSTP} = 'IGNORE';
168   local $SIG{PIPE} = 'IGNORE';
169
170   my $oldAutoCommit = $FS::UID::AutoCommit;
171   local $FS::UID::AutoCommit = 0;
172   my $dbh = dbh;
173
174   my $error =
175        $self->SUPER::delete(@_)
176     || $self->htpasswd_kludge('-D')
177   ;
178
179   if ( $error ) {
180     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
181     return $error;
182   } else {
183     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
184     '';
185   }
186
187 }
188
189 =item replace OLD_RECORD
190
191 Replaces the OLD_RECORD with this one in the database.  If there is an error,
192 returns the error, otherwise returns false.
193
194 =cut
195
196 sub replace {
197   my $new = shift;
198
199   my $old = ( ref($_[0]) eq ref($new) )
200               ? shift
201               : $new->replace_old;
202
203   local $SIG{HUP} = 'IGNORE';
204   local $SIG{INT} = 'IGNORE';
205   local $SIG{QUIT} = 'IGNORE';
206   local $SIG{TERM} = 'IGNORE';
207   local $SIG{TSTP} = 'IGNORE';
208   local $SIG{PIPE} = 'IGNORE';
209
210   my $oldAutoCommit = $FS::UID::AutoCommit;
211   local $FS::UID::AutoCommit = 0;
212   my $dbh = dbh;
213
214   if ( $new->_password ne $old->_password ) {
215     my $error = $new->htpasswd_kludge();
216     if ( $error ) {
217       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
218       return $error;
219     }
220   } elsif ( $old->disabled && !$new->disabled
221               && $new->_password =~ /changeme/i ) {
222     return "Must change password when enabling this account";
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_foreign_keyn('user_custnum', 'cust_main', 'custnum')
258     || $self->ut_enum('disabled', [ '', 'Y' ] )
259   ;
260   return $error if $error;
261
262   $self->SUPER::check;
263 }
264
265 =item name
266
267 Returns a name string for this user: "Last, First".
268
269 =cut
270
271 sub name {
272   my $self = shift;
273   $self->get('last'). ', '. $self->first;
274 }
275
276 =item user_cust_main
277
278 Returns the FS::cust_main object (see L<FS::cust_main>), if any, for this
279 user.
280
281 =cut
282
283 sub user_cust_main {
284   my $self = shift;
285   qsearchs( 'cust_main', { 'custnum' => $self->user_custnum } );
286 }
287
288 =item access_usergroup
289
290 Returns links to the the groups this user is a part of, as FS::access_usergroup
291 objects (see L<FS::access_usergroup>).
292
293 =cut
294
295 sub access_usergroup {
296   my $self = shift;
297   qsearch( 'access_usergroup', { 'usernum' => $self->usernum } );
298 }
299
300 #=item access_groups
301 #
302 #=cut
303 #
304 #sub access_groups {
305 #
306 #}
307 #
308 #=item access_groupnames
309 #
310 #=cut
311 #
312 #sub access_groupnames {
313 #
314 #}
315
316 =item agentnums 
317
318 Returns a list of agentnums this user can view (via group membership).
319
320 =cut
321
322 sub agentnums {
323   my $self = shift;
324   my $sth = dbh->prepare(
325     "SELECT DISTINCT agentnum FROM access_usergroup
326                               JOIN access_groupagent USING ( groupnum )
327        WHERE usernum = ?"
328   ) or die dbh->errstr;
329   $sth->execute($self->usernum) or die $sth->errstr;
330   map { $_->[0] } @{ $sth->fetchall_arrayref };
331 }
332
333 =item agentnums_href
334
335 Returns a hashref of agentnums this user can view.
336
337 =cut
338
339 sub agentnums_href {
340   my $self = shift;
341   scalar( { map { $_ => 1 } $self->agentnums } );
342 }
343
344 =item agentnums_sql [ HASHREF | OPTION => VALUE ... ]
345
346 Returns an sql fragement to select only agentnums this user can view.
347
348 Options are passed as a hashref or a list.  Available options are:
349
350 =over 4
351
352 =item null
353
354 The frament will also allow the selection of null agentnums.
355
356 =item null_right
357
358 The fragment will also allow the selection of null agentnums if the current
359 user has the provided access right
360
361 =item table
362
363 Optional table name in which agentnum is being checked.  Sometimes required to
364 resolve 'column reference "agentnum" is ambiguous' errors.
365
366 =item viewall_right
367
368 All agents will be viewable if the current user has the provided access right.
369 Defaults to 'View customers of all agents'.
370
371 =back
372
373 =cut
374
375 sub agentnums_sql {
376   my( $self ) = shift;
377   my %opt = ref($_[0]) ? %{$_[0]} : @_;
378
379   my $agentnum = $opt{'table'} ? $opt{'table'}.'.agentnum' : 'agentnum';
380
381   my @or = ();
382
383   my $viewall_right = $opt{'viewall_right'} || 'View customers of all agents';
384   if ( $self->access_right($viewall_right) ) {
385     push @or, "$agentnum IS NOT NULL";
386   } else {
387     push @or, "$agentnum IN (". join(',', $self->agentnums). ')';
388   }
389
390   push @or, "$agentnum IS NULL"
391     if $opt{'null'}
392     || ( $opt{'null_right'} && $self->access_right($opt{'null_right'}) );
393
394   return ' 1 = 0 ' unless scalar(@or);
395   '( '. join( ' OR ', @or ). ' )';
396
397 }
398
399 =item agentnum
400
401 Returns true if the user can view the specified agent.
402
403 =cut
404
405 sub agentnum {
406   my( $self, $agentnum ) = @_;
407   my $sth = dbh->prepare(
408     "SELECT COUNT(*) FROM access_usergroup
409                      JOIN access_groupagent USING ( groupnum )
410        WHERE usernum = ? AND agentnum = ?"
411   ) or die dbh->errstr;
412   $sth->execute($self->usernum, $agentnum) or die $sth->errstr;
413   $sth->fetchrow_arrayref->[0];
414 }
415
416 =item agents [ HASHREF | OPTION => VALUE ... ]
417
418 Returns the list of agents this user can view (via group membership), as
419 FS::agent objects.  Accepts the same options as the agentnums_sql method.
420
421 =cut
422
423 sub agents {
424   my $self = shift;
425   qsearch({
426     'table'     => 'agent',
427     'hashref'   => { disabled=>'' },
428     'extra_sql' => ' AND '. $self->agentnums_sql(@_),
429   });
430 }
431
432 =item access_right RIGHTNAME | LISTREF
433
434 Given a right name or a list reference of right names, returns true if this
435 user has this right, or, for a list, one of the rights (currently via group
436 membership, eventually also via user overrides).
437
438 =cut
439
440 sub access_right {
441   my( $self, $rightname ) = @_;
442
443   $rightname = [ $rightname ] unless ref($rightname);
444
445   warn "$me access_right called on ". join(', ', @$rightname). "\n"
446     if $DEBUG;
447
448   #some caching of ACL requests for low-hanging fruit perf improvement
449   #since we get a new $CurrentUser object each page view there shouldn't be any
450   #issues with stickiness
451   if ( $self->{_ACLcache} ) {
452
453     unless ( grep !exists($self->{_ACLcache}{$_}), @$rightname ) {
454       warn "$me ACL cache hit for ". join(', ', @$rightname). "\n"
455         if $DEBUG;
456       return grep $self->{_ACLcache}{$_}, @$rightname
457     }
458
459     warn "$me ACL cache miss for ". join(', ', @$rightname). "\n"
460       if $DEBUG;
461
462   } else {
463
464     warn "initializing ACL cache\n"
465       if $DEBUG;
466     $self->{_ACLcache} = {};
467
468   }
469
470   my $has_right = ' rightname IN ('. join(',', map '?', @$rightname ). ') ';
471
472   my $sth = dbh->prepare("
473     SELECT groupnum FROM access_usergroup
474                     LEFT JOIN access_group USING ( groupnum )
475                     LEFT JOIN access_right
476                          ON ( access_group.groupnum = access_right.rightobjnum )
477       WHERE usernum = ?
478         AND righttype = 'FS::access_group'
479         AND $has_right
480       LIMIT 1
481   ") or die dbh->errstr;
482   $sth->execute($self->usernum, @$rightname) or die $sth->errstr;
483   my $row = $sth->fetchrow_arrayref;
484
485   my $return = $row ? $row->[0] : '';
486
487   #just caching the single-rightname hits should be enough of a win for now
488   if ( scalar(@$rightname) == 1 ) {
489     $self->{_ACLcache}{${$rightname}[0]} = $return;
490   }
491
492   $return;
493
494 }
495
496 =item default_customer_view
497
498 Returns the default customer view for this user, from the 
499 "default_customer_view" user preference, the "cust_main-default_view" config,
500 or the hardcoded default, "jumbo" (may change to "basics" in the near future).
501
502 =cut
503
504 sub default_customer_view {
505   my $self = shift;
506
507   $self->option('default_customer_view')
508     || $conf->config('cust_main-default_view')
509     || 'jumbo'; #'basics' in 1.9.1?
510
511 }
512
513 =back
514
515 =head1 BUGS
516
517 =head1 SEE ALSO
518
519 L<FS::Record>, schema.html from the base documentation.
520
521 =cut
522
523 1;
524