NG auth: use database session keys, RT#21563
[freeside.git] / FS / FS / CurrentUser.pm
1 package FS::CurrentUser;
2
3 use vars qw($CurrentUser $CurrentSession $upgrade_hack);
4
5 #not at compile-time, circular dependancey causes trouble
6 #use FS::Record qw(qsearchs);
7 #use FS::access_user;
8
9 $upgrade_hack = 0;
10
11 =head1 NAME
12
13 FS::CurrentUser - Package representing the current user (and session)
14
15 =head1 SYNOPSIS
16
17 =head1 DESCRIPTION
18
19 =head1 CLASS METHODS
20
21 =over 4
22
23 =item load_user USERNAME
24
25 Sets the current user to the provided username
26
27 =cut
28
29 sub load_user {
30   my( $class, $user ) = @_; #, $pass
31
32   if ( $upgrade_hack ) {
33     return $CurrentUser = new FS::CurrentUser::BootstrapUser;
34   }
35
36   #return "" if $user =~ /^fs_(queue|selfservice)$/;
37
38   #not the best thing in the world...
39   eval "use FS::Record qw(qsearchs);";
40   die $@ if $@;
41   eval "use FS::access_user;";
42   die $@ if $@;
43
44   $CurrentUser = qsearchs('access_user', {
45     'username' => $user,
46     #'_password' =>
47     'disabled' => '',
48   } );
49
50   die "unknown user: $user" unless $CurrentUser; # or bad password
51
52   $CurrentUser;
53 }
54
55 =item new_session
56
57 Creates a new session for the current user and returns the session key
58
59 =cut
60
61 use vars qw( @saltset );
62 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '+' , '/' );
63
64 sub new_session {
65   my( $class ) = @_;
66
67   #not the best thing in the world...
68   eval "use FS::access_user_session;";
69   die $@ if $@;
70
71   my $sessionkey = join('', map $saltset[int(rand(scalar @saltset))], 0..39);
72
73   my $access_user_session = new FS::access_user_session {
74     'sessionkey' => $sessionkey,
75     'usernum'    => $CurrentUser->usernum,
76     'start_date' => time,
77   };
78   my $error = $access_user_session->insert;
79   die $error if $error;
80
81   return $sessionkey;
82
83 }
84
85 =item load_user_session SESSION_KEY
86
87 Sets the current user via the provided session key
88
89 =cut
90
91 sub load_user_session {
92   my( $class, $sessionkey ) = @_;
93
94   #not the best thing in the world...
95   eval "use FS::Record qw(qsearchs);";
96   die $@ if $@;
97   eval "use FS::access_user_session;";
98   die $@ if $@;
99
100   $CurrentSession = qsearchs('access_user_session', {
101     'sessionkey' => $sessionkey,
102     #XXX check for timed out but not-yet deleted sessions here
103   }) or return '';
104
105   $CurrentSession->touch_last_date;
106
107   $CurrentUser = $CurrentSession->access_user;
108
109 }
110
111 =head1 BUGS
112
113 Minimal docs
114
115 =head1 SEE ALSO
116
117 =cut
118
119 package FS::CurrentUser::BootstrapUser;
120
121 sub new {
122   my $proto = shift;
123   my $class = ref($proto) || $proto;
124   my $self = {};
125   bless ($self, $class);
126 }
127
128 sub AUTOLOAD { 1 };
129
130 1;
131