further work on agents editing own packages: allow them to see (but not edit) global...
[freeside.git] / FS / FS / access_user.pm
1 package FS::access_user;
2
3 use strict;
4 use vars qw( @ISA $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
14 @ISA = qw( FS::m2m_Common FS::option_Common FS::Record );
15 #@ISA = qw( FS::m2m_Common FS::option_Common );
16
17 #kludge htpasswd for now (i hope this bootstraps okay)
18 FS::UID->install_callback( sub {
19   my $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 inherits from
45 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   }
221
222   my $error = $new->SUPER::replace($old, @_);
223
224   if ( $error ) {
225     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
226     return $error;
227   } else {
228     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
229     '';
230   }
231
232 }
233
234 =item check
235
236 Checks all fields to make sure this is a valid internal access user.  If there is
237 an error, returns the error, otherwise returns false.  Called by the insert
238 and replace methods.
239
240 =cut
241
242 # the check method should currently be supplied - FS::Record contains some
243 # data checking routines
244
245 sub check {
246   my $self = shift;
247
248   my $error = 
249     $self->ut_numbern('usernum')
250     || $self->ut_alpha_lower('username')
251     || $self->ut_text('_password')
252     || $self->ut_text('last')
253     || $self->ut_text('first')
254     || $self->ut_enum('disabled', [ '', 'Y' ] )
255   ;
256   return $error if $error;
257
258   $self->SUPER::check;
259 }
260
261 =item name
262
263 Returns a name string for this user: "Last, First".
264
265 =cut
266
267 sub name {
268   my $self = shift;
269   $self->get('last'). ', '. $self->first;
270 }
271
272 =item access_usergroup
273
274 =cut
275
276 sub access_usergroup {
277   my $self = shift;
278   qsearch( 'access_usergroup', { 'usernum' => $self->usernum } );
279 }
280
281 #=item access_groups
282 #
283 #=cut
284 #
285 #sub access_groups {
286 #
287 #}
288 #
289 #=item access_groupnames
290 #
291 #=cut
292 #
293 #sub access_groupnames {
294 #
295 #}
296
297 =item agentnums 
298
299 Returns a list of agentnums this user can view (via group membership).
300
301 =cut
302
303 sub agentnums {
304   my $self = shift;
305   my $sth = dbh->prepare(
306     "SELECT DISTINCT agentnum FROM access_usergroup
307                               JOIN access_groupagent USING ( groupnum )
308        WHERE usernum = ?"
309   ) or die dbh->errstr;
310   $sth->execute($self->usernum) or die $sth->errstr;
311   map { $_->[0] } @{ $sth->fetchall_arrayref };
312 }
313
314 =item agentnums_href
315
316 Returns a hashref of agentnums this user can view.
317
318 =cut
319
320 sub agentnums_href {
321   my $self = shift;
322   scalar( { map { $_ => 1 } $self->agentnums } );
323 }
324
325 =item agentnums_sql [ HASHREF | OPTION => VALUE ... ]
326
327 Returns an sql fragement to select only agentnums this user can view.
328
329 Options are passed as a hashref or a list.  Available options are:
330
331 =over 4
332
333 =item null
334
335 The frament will also allow the selection of null agentnums.
336
337 =item null_right
338
339 The fragment will also allow the selection of null agentnums if the current
340 user has the provided access right
341
342 =item table
343
344 Optional table name in which agentnum is being checked.  Sometimes required to
345 resolve 'column reference "agentnum" is ambiguous' errors.
346
347 =back
348
349 =cut
350
351 sub agentnums_sql {
352   my( $self ) = shift;
353   my %opt = ref($_[0]) ? %{$_[0]} : @_;
354
355   my $agentnum = $opt{'table'} ? $opt{'table'}.'.agentnum' : 'agentnum';
356
357 #  my @agentnums = map { "$agentnum = $_" } $self->agentnums;
358   my @agentnums = ();
359   push @agentnums, "$agentnum IN (". join(',', $self->agentnums). ')';
360
361   push @agentnums, "$agentnum IS NULL"
362     if $opt{'null'}
363     || ( $opt{'null_right'} && $self->access_right($opt{'null_right'}) );
364
365   return ' 1 = 0 ' unless scalar(@agentnums);
366   '( '. join( ' OR ', @agentnums ). ' )';
367
368 }
369
370 =item agentnum
371
372 Returns true if the user can view the specified agent.
373
374 =cut
375
376 sub agentnum {
377   my( $self, $agentnum ) = @_;
378   my $sth = dbh->prepare(
379     "SELECT COUNT(*) FROM access_usergroup
380                      JOIN access_groupagent USING ( groupnum )
381        WHERE usernum = ? AND agentnum = ?"
382   ) or die dbh->errstr;
383   $sth->execute($self->usernum, $agentnum) or die $sth->errstr;
384   $sth->fetchrow_arrayref->[0];
385 }
386
387 =item agents
388
389 Returns the list of agents this user can view (via group membership), as
390 FS::agent objects.
391
392 =cut
393
394 sub agents {
395   my $self = shift;
396   qsearch({
397     'table'     => 'agent',
398     'hashref'   => { disabled=>'' },
399     'extra_sql' => ' AND '. $self->agentnums_sql,
400   });
401 }
402
403 =item access_right RIGHTNAME | LISTREF
404
405 Given a right name or a list reference of right names, returns true if this
406 user has this right, or, for a list, one of the rights (currently via group
407 membership, eventually also via user overrides).
408
409 =cut
410
411 sub access_right {
412   my( $self, $rightname ) = @_;
413
414   $rightname = [ $rightname ] unless ref($rightname);
415
416   #some caching of ACL requests for low-hanging fruit perf improvement
417   #since we get a new $CurrentUser object each page view there shouldn't be any
418   #issues with stickiness
419   if ( $self->{_ACLcache} ) {
420
421     return grep $self->{_ACLcache}{$_}, @$rightname
422       unless grep !exists($self->{_ACLcache}{$_}), @$rightname;
423
424   } else {
425     $self->{_ACLcache} = {};
426   }
427
428   my $has_right = ' ( '. join(' OR ',
429                                       map { 'rightname = '. dbh->quote($_) }
430                                           @$rightname
431                              ).
432                   ' ) ';
433
434   my $sth = dbh->prepare("
435     SELECT groupnum FROM access_usergroup
436                     LEFT JOIN access_group USING ( groupnum )
437                     LEFT JOIN access_right
438                          ON ( access_group.groupnum = access_right.rightobjnum )
439       WHERE usernum = ?
440         AND righttype = 'FS::access_group'
441         AND $has_right
442       LIMIT 1
443   ") or die dbh->errstr;
444   $sth->execute($self->usernum) or die $sth->errstr;
445   my $row = $sth->fetchrow_arrayref;
446
447   #$row ? $row->[0] : '';
448   $self->{_ACLcache}{$rightname} = ( $row ? $row->[0] : '' );
449
450 }
451
452 =back
453
454 =head1 BUGS
455
456 =head1 SEE ALSO
457
458 L<FS::Record>, schema.html from the base documentation.
459
460 =cut
461
462 1;
463