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