eea4870d7f43e7489301e3128be6dcbbc0bde415
[freeside.git] / FS / FS / Auth / internal.pm
1 package FS::Auth::internal;
2 #use base qw( FS::Auth );
3
4 use strict;
5 use Crypt::Eksblowfish::Bcrypt qw(bcrypt_hash en_base64 de_base64);
6 use FS::Record qw( qsearchs );
7 use FS::access_user;
8
9 sub authenticate {
10   my($self, $username, $check_password ) = @_;
11
12   my $access_user =
13     ref($username) ? $username
14                    : qsearchs('access_user', { 'username' => $username,
15                                                'disabled' => '',
16                                              }
17                              )
18     or return 0;
19
20   if ( $access_user->_password_encoding eq 'bcrypt' ) {
21
22     my( $cost, $salt, $hash ) = split(',', $access_user->_password);
23
24     my $check_hash = en_base64( bcrypt_hash( { key_nul => 1,
25                                                cost    => $cost,
26                                                salt    => de_base64($salt),
27                                              },
28                                              $check_password
29                                            )
30                               );
31
32     $hash eq $check_hash;
33
34   } else { 
35
36     return 0 if $access_user->_password eq 'notyet'
37              || $access_user->_password eq '';
38
39     $access_user->_password eq $check_password;
40
41   }
42
43 }
44
45 sub autocreate { 0; }
46
47 sub change_password {
48   my($self, $access_user, $new_password) = @_;
49
50   # do nothing if the password is unchanged
51   return if $self->authenticate( $access_user, $new_password );
52
53   $self->change_password_fields( $access_user, $new_password );
54
55   $access_user->replace;
56
57 }
58
59 sub change_password_fields {
60   my($self, $access_user, $new_password) = @_;
61
62   $access_user->_password_encoding('bcrypt');
63
64   my $cost = 8;
65
66   my $salt = pack( 'C*', map int(rand(256)), 1..16 );
67
68   my $hash = bcrypt_hash( { key_nul => 1,
69                             cost    => $cost,
70                             salt    => $salt,
71                           },
72                           $new_password,
73                         );
74
75   $access_user->_password(
76     join(',', $cost, en_base64($salt), en_base64($hash) )
77   );
78
79 }
80
81 1;