c2d9446dbbacd6fb14e6b90f8f26280a93637fcb
[piwik-CASLogin.git] / Auth.php
1 <?php
2 /**
3  * Piwik - Open source web analytics
4  * 
5  * @link http://piwik.org
6  * @license http://www.gnu.org/licenses/gpl-3.0.html Gpl v3 or later
7  * @version $Id:$
8  * 
9  * @category Piwik_Plugins
10  * @package CASLogin
11  */
12
13 namespace Piwik\Plugins\CASLogin;
14
15 use Piwik\AuthResult;
16 use Piwik\Common;
17 use Piwik\Config;
18 use Piwik\Db;
19 use Piwik\Piwik;
20 use Piwik\Plugins\UsersManager\API;
21
22 /**
23  * Class that implements an authentication mechanism via CAS (Central Authentication Services)
24  *
25  * @package Piwik_CASLogin
26  */
27 class Auth implements \Piwik\Auth
28 {
29         protected $login = null;
30         protected $token_auth = null;
31         private static $phpcas_client_called = false;
32
33         public function getName()
34         {
35                 return 'CASLogin';
36         }
37
38         public function initSession($login, $md5Password, $rememberMe) {}
39
40         public function authenticate()
41         {
42                 $user = '';
43
44                 require_once PIWIK_INCLUDE_PATH . '/plugins/CASLogin/CAS/CAS.php';
45
46                 // initialize phpCAS
47
48                 // What happens here: in some piwik functionality, some additional API-style calls are
49                 // made from a controller action, where the authenticate() method will be called *again*.
50                 // This happens for instance when an admin changes some permissions in Settings->Users.
51                 // The first authenticate() is from the page, and the second is due to an API call.
52                 // This checks if there was already a phpcas instance already initialized, otherwize
53                 // phpCAS::client() would fail.
54                 if (!self::$phpcas_client_called) {
55                         \phpCAS::client(
56                                 constant( Config::getInstance()->caslogin['protocol'] ),
57                                 Config::getInstance()->caslogin['host'],
58                                 (integer) Config::getInstance()->caslogin['port'],
59                 '',
60                 false
61                         );
62                         self::$phpcas_client_called = true;
63                 }
64
65                 // no SSL validation for the CAS server
66                 \phpCAS::setNoCasServerValidation();
67
68                 // Handle single signout requests from CAS server
69                 \phpCAS::handleLogoutRequests();
70
71                 // force CAS authentication only if it has been requested by action argument
72                 $action = Piwik::getAction();
73                 
74                 $auth = \phpCAS::checkAuthentication();
75                 if(!$auth) {
76                         if($action == 'redirectToCAS') {
77                                 phpCAS::forceAuthentication();
78                         }
79
80                         if($action != 'login' && Piwik::getModule() != 'CoreUpdater') {
81                                 Piwik::redirectToModule('CASLogin', 'login');
82                                 return;
83                         } elseif($action == 'redirectToCAS') {
84                                 phpCAS::forceAuthentication();
85                         } else {
86                                 return new AuthResult( AuthResult::FAILURE, $user, NULL );
87                         }
88                 }
89
90                 // Additional Attributes
91                 // For future retrieval of attributes; they _might_ be of some use, but are highly
92                 // dependable on a specific installation. CAS|piwik hackers can do some magic
93                 // here with SAML attributes etc.
94                 /*
95                 foreach (\phpCAS::getAttributes() as $key => $value) {
96                         // syslog(LOG_DEBUG, "attribute: $key - ". print_r($value, true));
97                 }
98                  */
99
100                 if (isset($_SESSION['phpCAS']) && isset($_SESSION['phpCAS']['user'])) {
101                         $user = $_SESSION['phpCAS']['user'];
102                 }
103
104                 if($user) {
105                         $db_user = Db::fetchRow('SELECT login, superuser_access FROM '.Common::prefixTable('user').' WHERE login = ?',
106                                         array($user)
107                         );
108                         if($db_user === null) {
109                                 // ***User Autocreate***
110                                 // We can either add the authenticated but not-yet-authorized user to the piwik users
111                                 // database, or ignore that.
112                                 // TODO: make this a config option
113                                 $this->_populateDb($user);
114                                 $login = $user;
115                                 $superuser = false;
116                         }
117                         else {
118                                 $login = $db_user['login'];
119                                 $superuser = $db_user['superuser_access'];
120                         }
121                         if($login == $user)
122                         {
123                                 if ($superuser)
124                                         $code = AuthResult::SUCCESS_SUPERUSER_AUTH_CODE;
125                                 else $code = AuthResult::SUCCESS; 
126                                 return new AuthResult($code, $login, NULL );
127                         }
128                 }
129
130                 return new AuthResult( AuthResult::FAILURE, $user, NULL );
131         }
132
133         public function setLogin($login)
134         {
135                 $this->login = $login;
136         }
137         
138     public function setTokenAuth($token_auth)
139         {
140                 $this->token_auth = $token_auth;
141         }
142
143         /**
144          * This method is used to inject user into Piwik's tables.
145          * @todo Alias could be the 'cn' returned from CAS attributes.
146          */
147         private function _populateDb($user)
148         {
149                 $result = null;
150                 $dummy = md5('abcd1234');
151                 if ($this->_helper_userExists($user)) {
152                         $this->_helper_updateUser($user, $dummy, '', $user);
153                 } else {
154                         $this->_helper_addUser($user, $dummy, '', $user);
155                 }
156         }
157
158
159         ///// The following methods are taken from Piwik's UserManager, but in order to inject data into piwik's user and access tables, we need
160         ///// to make sure we don't wreck things. The UserManager API uses authenticate() to check if we're eligable to look this up,
161         ///// soi we can't use it - we need superuser permissions anyway.
162         //
163         ///// Warning - these methods are of course under Piwik's license.
164         private function _helper_userExists($name)
165         {
166                 $count = Db::fetchOne("SELECT count(*)
167                                                                         FROM ".Common::prefixTable("user"). "
168                                                                         WHERE login = ?", $name);
169                 return $count > 0;
170         }
171
172         private function _helper_updateUser( $userLogin, $password = false, $email = false, $alias = false ) 
173         {
174                 $token_auth = API::getTokenAuth($userLogin, $password);
175
176                 Db::get()->update( Common::prefixTable("user"),
177                                         array(
178                                                 'password' => $password,
179                                                 'alias' => $alias,
180                                                 'email' => $email,
181                                                 'token_auth' => $token_auth,
182                                                 ),
183                                         "login = '$userLogin'"
184                         );
185         }
186
187         private function _helper_addUser( $userLogin, $password, $email, $alias = false )
188         {               
189                 $token_auth = API::getTokenAuth($userLogin, $password);
190
191                 Db::get()->insert( Common::prefixTable("user"), array(
192                                                                         'login' => $userLogin,
193                                                                         'password' => $password,
194                                                                         'alias' => $alias,
195                                                                         'email' => $email,
196                                                                         'token_auth' => $token_auth,
197                                                                         )
198                 );
199         }
200     
201 }
202