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