NG auth: pw changes, RT#21563
[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::Auth;
8 use FS::Conf;
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::access_user_pref;
11 use FS::access_usergroup;
12 use FS::agent;
13 use FS::cust_main;
14
15 $DEBUG = 0;
16 $me = '[FS::access_user]';
17
18 #kludge htpasswd for now (i hope this bootstraps okay)
19 FS::UID->install_callback( sub {
20   $conf = new FS::Conf;
21   $htpasswd_file = $conf->base_dir. '/htpasswd';
22 } );
23
24 =head1 NAME
25
26 FS::access_user - Object methods for access_user records
27
28 =head1 SYNOPSIS
29
30   use FS::access_user;
31
32   $record = new FS::access_user \%hash;
33   $record = new FS::access_user { 'column' => 'value' };
34
35   $error = $record->insert;
36
37   $error = $new_record->replace($old_record);
38
39   $error = $record->delete;
40
41   $error = $record->check;
42
43 =head1 DESCRIPTION
44
45 An FS::access_user object represents an internal access user.  FS::access_user
46 inherits from FS::Record.  The following fields are currently supported:
47
48 =over 4
49
50 =item usernum - primary key
51
52 =item username - 
53
54 =item _password - 
55
56 =item last -
57
58 =item first -
59
60 =item disabled - empty or 'Y'
61
62 =back
63
64 =head1 METHODS
65
66 =over 4
67
68 =item new HASHREF
69
70 Creates a new internal access user.  To add the user to the database, see L<"insert">.
71
72 Note that this stores the hash reference, not a distinct copy of the hash it
73 points to.  You can ask the object for a copy with the I<hash> method.
74
75 =cut
76
77 # the new method can be inherited from FS::Record, if a table method is defined
78
79 sub table { 'access_user'; }
80
81 sub _option_table    { 'access_user_pref'; }
82 sub _option_namecol  { 'prefname'; }
83 sub _option_valuecol { 'prefvalue'; }
84
85 =item insert
86
87 Adds this record to the database.  If there is an error, returns the error,
88 otherwise returns false.
89
90 =cut
91
92 sub insert {
93   my $self = shift;
94
95   my $error = $self->check;
96   return $error if $error;
97
98   local $SIG{HUP} = 'IGNORE';
99   local $SIG{INT} = 'IGNORE';
100   local $SIG{QUIT} = 'IGNORE';
101   local $SIG{TERM} = 'IGNORE';
102   local $SIG{TSTP} = 'IGNORE';
103   local $SIG{PIPE} = 'IGNORE';
104
105   my $oldAutoCommit = $FS::UID::AutoCommit;
106   local $FS::UID::AutoCommit = 0;
107   my $dbh = dbh;
108
109   $error = $self->htpasswd_kludge();
110   if ( $error ) {
111     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
112     return $error;
113   }
114
115   $error = $self->SUPER::insert(@_);
116
117   if ( $error ) {
118     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
119
120     #make sure it isn't a dup username?  or you could nuke people's passwords
121     #blah.  really just should do our own login w/cookies
122     #and auth out of the db in the first place
123     #my $hterror = $self->htpasswd_kludge('-D');
124     #$error .= " - additionally received error cleaning up htpasswd file: $hterror"
125     return $error;
126
127   } else {
128     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
129     '';
130   }
131
132 }
133
134 sub htpasswd_kludge {
135   my $self = shift;
136
137   return '' if $self->is_system_user;
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   return $self->username
274     if $self->get('last') eq 'Lastname' && $self->first eq 'Firstname';
275   return $self->get('last'). ', '. $self->first;
276 }
277
278 =item user_cust_main
279
280 Returns the FS::cust_main object (see L<FS::cust_main>), if any, for this
281 user.
282
283 =cut
284
285 sub user_cust_main {
286   my $self = shift;
287   qsearchs( 'cust_main', { 'custnum' => $self->user_custnum } );
288 }
289
290 =item access_usergroup
291
292 Returns links to the the groups this user is a part of, as FS::access_usergroup
293 objects (see L<FS::access_usergroup>).
294
295 =cut
296
297 sub access_usergroup {
298   my $self = shift;
299   qsearch( 'access_usergroup', { 'usernum' => $self->usernum } );
300 }
301
302 #=item access_groups
303 #
304 #=cut
305 #
306 #sub access_groups {
307 #
308 #}
309 #
310 #=item access_groupnames
311 #
312 #=cut
313 #
314 #sub access_groupnames {
315 #
316 #}
317
318 =item agentnums 
319
320 Returns a list of agentnums this user can view (via group membership).
321
322 =cut
323
324 sub agentnums {
325   my $self = shift;
326   my $sth = dbh->prepare(
327     "SELECT DISTINCT agentnum FROM access_usergroup
328                               JOIN access_groupagent USING ( groupnum )
329        WHERE usernum = ?"
330   ) or die dbh->errstr;
331   $sth->execute($self->usernum) or die $sth->errstr;
332   map { $_->[0] } @{ $sth->fetchall_arrayref };
333 }
334
335 =item agentnums_href
336
337 Returns a hashref of agentnums this user can view.
338
339 =cut
340
341 sub agentnums_href {
342   my $self = shift;
343   scalar( { map { $_ => 1 } $self->agentnums } );
344 }
345
346 =item agentnums_sql [ HASHREF | OPTION => VALUE ... ]
347
348 Returns an sql fragement to select only agentnums this user can view.
349
350 Options are passed as a hashref or a list.  Available options are:
351
352 =over 4
353
354 =item null
355
356 The frament will also allow the selection of null agentnums.
357
358 =item null_right
359
360 The fragment will also allow the selection of null agentnums if the current
361 user has the provided access right
362
363 =item table
364
365 Optional table name in which agentnum is being checked.  Sometimes required to
366 resolve 'column reference "agentnum" is ambiguous' errors.
367
368 =item viewall_right
369
370 All agents will be viewable if the current user has the provided access right.
371 Defaults to 'View customers of all agents'.
372
373 =back
374
375 =cut
376
377 sub agentnums_sql {
378   my( $self ) = shift;
379   my %opt = ref($_[0]) ? %{$_[0]} : @_;
380
381   my $agentnum = $opt{'table'} ? $opt{'table'}.'.agentnum' : 'agentnum';
382
383   my @or = ();
384
385   my $viewall_right = $opt{'viewall_right'} || 'View customers of all agents';
386   if ( $self->access_right($viewall_right) ) {
387     push @or, "$agentnum IS NOT NULL";
388   } else {
389     push @or, "$agentnum IN (". join(',', $self->agentnums). ')';
390   }
391
392   push @or, "$agentnum IS NULL"
393     if $opt{'null'}
394     || ( $opt{'null_right'} && $self->access_right($opt{'null_right'}) );
395
396   return ' 1 = 0 ' unless scalar(@or);
397   '( '. join( ' OR ', @or ). ' )';
398
399 }
400
401 =item agentnum
402
403 Returns true if the user can view the specified agent.
404
405 =cut
406
407 sub agentnum {
408   my( $self, $agentnum ) = @_;
409   my $sth = dbh->prepare(
410     "SELECT COUNT(*) FROM access_usergroup
411                      JOIN access_groupagent USING ( groupnum )
412        WHERE usernum = ? AND agentnum = ?"
413   ) or die dbh->errstr;
414   $sth->execute($self->usernum, $agentnum) or die $sth->errstr;
415   $sth->fetchrow_arrayref->[0];
416 }
417
418 =item agents [ HASHREF | OPTION => VALUE ... ]
419
420 Returns the list of agents this user can view (via group membership), as
421 FS::agent objects.  Accepts the same options as the agentnums_sql method.
422
423 =cut
424
425 sub agents {
426   my $self = shift;
427   qsearch({
428     'table'     => 'agent',
429     'hashref'   => { disabled=>'' },
430     'extra_sql' => ' AND '. $self->agentnums_sql(@_),
431   });
432 }
433
434 =item access_right RIGHTNAME | LISTREF
435
436 Given a right name or a list reference of right names, returns true if this
437 user has this right, or, for a list, one of the rights (currently via group
438 membership, eventually also via user overrides).
439
440 =cut
441
442 sub access_right {
443   my( $self, $rightname ) = @_;
444
445   $rightname = [ $rightname ] unless ref($rightname);
446
447   warn "$me access_right called on ". join(', ', @$rightname). "\n"
448     if $DEBUG;
449
450   #some caching of ACL requests for low-hanging fruit perf improvement
451   #since we get a new $CurrentUser object each page view there shouldn't be any
452   #issues with stickiness
453   if ( $self->{_ACLcache} ) {
454
455     unless ( grep !exists($self->{_ACLcache}{$_}), @$rightname ) {
456       warn "$me ACL cache hit for ". join(', ', @$rightname). "\n"
457         if $DEBUG;
458       return grep $self->{_ACLcache}{$_}, @$rightname
459     }
460
461     warn "$me ACL cache miss for ". join(', ', @$rightname). "\n"
462       if $DEBUG;
463
464   } else {
465
466     warn "initializing ACL cache\n"
467       if $DEBUG;
468     $self->{_ACLcache} = {};
469
470   }
471
472   my $has_right = ' rightname IN ('. join(',', map '?', @$rightname ). ') ';
473
474   my $sth = dbh->prepare("
475     SELECT groupnum FROM access_usergroup
476                     LEFT JOIN access_group USING ( groupnum )
477                     LEFT JOIN access_right
478                          ON ( access_group.groupnum = access_right.rightobjnum )
479       WHERE usernum = ?
480         AND righttype = 'FS::access_group'
481         AND $has_right
482       LIMIT 1
483   ") or die dbh->errstr;
484   $sth->execute($self->usernum, @$rightname) or die $sth->errstr;
485   my $row = $sth->fetchrow_arrayref;
486
487   my $return = $row ? $row->[0] : '';
488
489   #just caching the single-rightname hits should be enough of a win for now
490   if ( scalar(@$rightname) == 1 ) {
491     $self->{_ACLcache}{${$rightname}[0]} = $return;
492   }
493
494   $return;
495
496 }
497
498 =item default_customer_view
499
500 Returns the default customer view for this user, from the 
501 "default_customer_view" user preference, the "cust_main-default_view" config,
502 or the hardcoded default, "basics" (formerly "jumbo" prior to 3.0).
503
504 =cut
505
506 sub default_customer_view {
507   my $self = shift;
508
509   $self->option('default_customer_view')
510     || $conf->config('cust_main-default_view')
511     || 'basics'; #s/jumbo/basics/ starting with 3.0
512
513 }
514
515 =item spreadsheet_format [ OVERRIDE ]
516
517 Returns a hashref of this user's Excel spreadsheet download settings:
518 'extension' (xls or xlsx), 'class' (Spreadsheet::WriteExcel or
519 Excel::Writer::XLSX), and 'mime_type'.  If OVERRIDE is 'XLS' or 'XLSX',
520 use that instead of the user's setting.
521
522 =cut
523
524 # is there a better place to put this?
525 my %formats = (
526   XLS => {
527     extension => '.xls',
528     class => 'Spreadsheet::WriteExcel',
529     mime_type => 'application/vnd.ms-excel',
530   },
531   XLSX => {
532     extension => '.xlsx',
533     class => 'Excel::Writer::XLSX',
534     mime_type => # it's on wikipedia, it must be true
535       'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
536   }
537 );
538
539 sub spreadsheet_format {
540   my $self = shift;
541   my $override = shift;
542
543   my $f =  $override
544         || $self->option('spreadsheet_format') 
545         || $conf->config('spreadsheet_format')
546         || 'XLS';
547
548   $formats{$f};
549 }
550
551 =item is_system_user
552
553 Returns true if this user has the name of a known system account.  These 
554 users will not appear in the htpasswd file and can't have passwords set.
555
556 =cut
557
558 sub is_system_user {
559   my $self = shift;
560   return grep { $_ eq $self->username } ( qw(
561     fs_queue
562     fs_daily
563     fs_selfservice
564     fs_signup
565     fs_bootstrap
566     fs_selfserv
567   ) );
568 }
569
570 =item change_password NEW_PASSWORD
571
572 =cut
573
574 sub change_password {
575   #my( $self, $password ) = @_;
576   #FS::Auth->auth_class->change_password( $self, $password );
577   FS::Auth->auth_class->change_password( @_ );
578 }
579
580 =item change_password_fields NEW_PASSWORD
581
582 =cut
583
584 sub change_password_fields {
585   #my( $self, $password ) = @_;
586   #FS::Auth->auth_class->change_password_fields( $self, $password );
587   FS::Auth->auth_class->change_password_fields( @_ );
588 }
589
590 =back
591
592 =head1 BUGS
593
594 =head1 SEE ALSO
595
596 L<FS::Record>, schema.html from the base documentation.
597
598 =cut
599
600 1;
601