Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Controller.php « Login « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 022c47bf013bde2e2013017a35c7900b6fc0942c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html Gpl v3 or later
 * @version $Id$
 *
 * @category Piwik_Plugins
 * @package Piwik_Login
 */

/**
 *
 * @package Piwik_Login
 */
class Piwik_Login_Controller extends Piwik_Controller
{
	/**
	 * Default action
	 */
	function index()
	{
		$this->login();
	}

	/**
	 * Login form
	 */
	function login()
	{
		$messageNoAccess = null;
		$form = new Piwik_Login_Form();

		$currentUrl = Piwik_Url::getReferer();
		$urlToRedirect = Piwik_Common::getRequestVar('form_url', $currentUrl, 'string');
		$urlToRedirect = htmlspecialchars_decode($urlToRedirect);

		if($form->validate())
		{
			// if the current url to redirect contains module=Login or Installation we instead redirect to the doc root
			if(preg_match('/module=(Login|Installation)/', $urlToRedirect))
			{
				$urlToRedirect = 'index.php';
			}

			$login = $form->getSubmitValue('form_login');
			$password = $form->getSubmitValue('form_password');
			$md5Password = md5($password);
			$messageNoAccess = $this->authenticateAndRedirect($login, $md5Password, $urlToRedirect);
		}

		$view = Piwik_View::factory('login');
		// make navigation login form -> reset password -> login form remember your first url
		$view->urlToRedirect = $urlToRedirect;
		$view->AccessErrorString = $messageNoAccess;
		$view->linkTitle = Piwik::getRandomTitle();
		$view->addForm( $form );
		$view->subTemplate = 'genericForm.tpl';
		echo $view->render();
	}

	/**
	 * Form-less login
	 */
	function logme()
	{
		$login = Piwik_Common::getRequestVar('login', null, 'string');
		$password = Piwik_Common::getRequestVar('password', null, 'string');
		$currentUrl = 'index.php';
		$urlToRedirect = Piwik_Common::getRequestVar('url', $currentUrl, 'string');
		$urlToRedirect = htmlspecialchars_decode($urlToRedirect);

		if(strlen($password) != 32)
		{
			throw new Exception("The password parameter is expected to be a MD5 hash of the password.");
		}
		if($login == Zend_Registry::get('config')->superuser->login)
		{
			throw new Exception("The Super User cannot be authenticated using this URL.");
		}
		$authenticated = $this->authenticateAndRedirect($login, $password, $urlToRedirect);
		if($authenticated === false)
		{
			echo Piwik_Translate('Login_LoginPasswordNotCorrect');
		}
	}

	/**
	 * Authenticate user and password.  Redirect if successful.
	 *
	 * @param string $login (user name)
	 * @param string $md5Password (md5 hash of password)
	 * @param string $urlToRedirect (URL to redirect to, if successfully authenticated)
	 * @return string (failure message if unable to authenticate)
	 */
	protected function authenticateAndRedirect($login, $md5Password, $urlToRedirect)
	{
		$tokenAuth = Piwik_UsersManager_API::getTokenAuth($login, $md5Password);

		$auth = Zend_Registry::get('auth');
		$auth->setLogin($login);
		$auth->setTokenAuth($tokenAuth);

		$authResult = $auth->authenticate();
		if(!$authResult->isValid())
		{
			return Piwik_Translate('Login_LoginPasswordNotCorrect');
		}

		$authCookieName = Zend_Registry::get('config')->General->login_cookie_name;
		$authCookieExpiry = time() + Zend_Registry::get('config')->General->login_cookie_expire;
		$cookie = new Piwik_Cookie($authCookieName, $authCookieExpiry);
		$cookie->set('login', $login);
		$cookie->set('token_auth', $authResult->getTokenAuth());
		$cookie->save();

		Zend_Session::regenerateId();

		Piwik_Url::redirectToUrl($urlToRedirect);
	}

	/**
	 * Lost password form.  Email password reset information.
	 */
	function lostPassword()
	{
		$messageNoAccess = null;
		$form = new Piwik_Login_PasswordForm();
		$currentUrl = 'index.php';
		$urlToRedirect = Piwik_Common::getRequestVar('form_url', $currentUrl, 'string');
		$urlToRedirect = htmlspecialchars_decode($urlToRedirect);

		if($form->validate())
		{
			$loginMail = $form->getSubmitValue('form_login');
			$messageNoAccess = $this->lostPasswordFormValidated($loginMail, $urlToRedirect);
		}

		$view = Piwik_View::factory('lostPassword');
		$view->AccessErrorString = $messageNoAccess;
		// make navigation login form -> reset password -> login form remember your first url
		$view->urlToRedirect = $urlToRedirect;
		$view->linkTitle = Piwik::getRandomTitle();
		$view->addForm( $form );
		$view->subTemplate = 'genericForm.tpl';
		echo $view->render();
	}

	/**
	 * Validate user (by username or email address).
	 *
	 * @param string $loginMail (user name or email address)
	 * @param string $urlToRedirect (URL to redirect to, if successfully validated)
	 * @return string (failure message if unable to validate)
	 */
	protected function lostPasswordFormValidated($loginMail, $urlToRedirect)
	{
		$user = self::getUserInformation($loginMail);
		if( $user === null )
		{
			return Piwik_Translate('Login_InvalidUsernameEmail');
		}

		$view = Piwik_View::factory('passwordsent');

		$login = $user['login'];
		$email = $user['email'];

		// construct a password reset token from user information
		$resetToken = self::generatePasswordResetToken($user);

		$ip = Piwik_Common::getIpString();
		$url = Piwik_Url::getCurrentUrlWithoutQueryString() . "?module=Login&action=resetPassword&token=$resetToken";

		// send email with new password
		try
		{
			$mail = new Piwik_Mail();
			$mail->addTo($email, $login);
			$mail->setSubject(Piwik_Translate('Login_MailTopicPasswordRecovery'));
			$mail->setBodyText(
				str_replace(
					'\n',
					"\n",
					sprintf(Piwik_Translate('Login_MailPasswordRecoveryBody'), $login, $ip, $url, $resetToken)
				)
			);

			$piwikHost = $_SERVER['HTTP_HOST'];
			if(strlen($piwikHost) == 0)
			{
				$piwikHost = 'piwik.org';
			}

			$fromEmailName = Zend_Registry::get('config')->General->login_password_recovery_email_name;
			$fromEmailAddress = Zend_Registry::get('config')->General->login_password_recovery_email_address;
			$fromEmailAddress = str_replace('{DOMAIN}', $piwikHost, $fromEmailAddress);
			$mail->setFrom($fromEmailAddress, $fromEmailName);
			@$mail->send();
		}
		catch(Exception $e)
		{
			$view->ErrorString = $e->getMessage();
		}

		$view->linkTitle = Piwik::getRandomTitle();
		$view->urlToRedirect = $urlToRedirect;
		echo $view->render();

		exit;
	}

	/**
	 * Reset password form.  Enter new password here.
	 */
	function resetPassword()
	{
		$messageNoAccess = null;

		$form = new Piwik_Login_ResetPasswordForm();
		$currentUrl = 'index.php';
		$urlToRedirect = Piwik_Common::getRequestVar('form_url', $currentUrl, 'string');
		$urlToRedirect = htmlspecialchars_decode($urlToRedirect);

		if($form->validate())
		{
			$loginMail = $form->getSubmitValue('form_login');
			$token = $form->getSubmitValue('form_token');
			$password = $form->getSubmitValue('form_password');
			$messageNoAccess = $this->resetPasswordFormValidated($loginMail, $token, $password, $urlToRedirect);
		}

		$view = Piwik_View::factory('resetPassword');
		$view->AccessErrorString = $messageNoAccess;
		// make navigation login form -> reset password -> login form remember your first url
		$view->urlToRedirect = $urlToRedirect;
		$view->linkTitle = Piwik::getRandomTitle();
		$view->addForm( $form );
		$view->subTemplate = 'genericForm.tpl';
		echo $view->render();
	}

	/**
	 * Validate password reset request.  If successful, set new password and redirect.
	 *
	 * @param string $loginMail (user name or email address)
	 * @param string $token (password reset token)
	 * @param array of string $newPassword (new password)
	 * @param string $urlToRedirect (URL to redirect to, if successfully validated)
	 * @return string (failure message)
	 */
	protected function resetPasswordFormValidated($loginMail, $token, $password, $urlToRedirect)
	{
		$user = self::getUserInformation($loginMail);
		if( $user === null )
		{
			return Piwik_Translate('Login_InvalidUsernameEmail');
		}

		if(!self::isValidToken($token, $user))
		{
			return Piwik_Translate('Login_InvalidOrExpiredToken');
		}

		try
		{
			if( $user['email'] == Zend_Registry::get('config')->superuser->email )
			{
				$user['password'] = md5($password);
				Zend_Registry::get('config')->superuser = $user;
			}
			else
			{
				Piwik_UsersManager_API::updateUser($user['login'], $password);
			}
		}
		catch(Exception $e)
		{
			$view->ErrorString = $e->getMessage();
		}

		$view = Piwik_View::factory('passwordchanged');
		$view->linkTitle = Piwik::getRandomTitle();
		$view->urlToRedirect = $urlToRedirect;
		echo $view->render();

		exit;
	}

	/**
	 * Get user information
	 *
	 * @param string $loginMail (user login or email address)
	 * @return array ("login" => '...', "email" => '...', "password" => '...') or null, if user not found
	 */
	protected function getUserInformation($loginMail)
	{
		Piwik::setUserIsSuperUser();

		$user = null;
		if( $loginMail == Zend_Registry::get('config')->superuser->email
			|| $loginMail == Zend_Registry::get('config')->superuser->login )
		{
			$user = array(
					'login' => Zend_Registry::get('config')->superuser->login,
					'email' => Zend_Registry::get('config')->superuser->email,
					'password' => Zend_Registry::get('config')->superuser->password,
			);
		}
		else if( Piwik_UsersManager_API::userExists($loginMail) )
		{
			$user = Piwik_UsersManager_API::getUser($loginMail);
		}
		else if( Piwik_UsersManager_API::userEmailExists($loginMail) )
		{
			$user = Piwik_UsersManager_API::getUserByEmail($loginMail);
		}

		return $user;
	}

	/**
	 * Generate a password reset token.  Expires in (roughly) 24 hours.
	 *
	 * @param array (user information)
	 * @param int $timestamp (Unix timestamp)
	 * @return string (generated token)
	 */
	protected function generatePasswordResetToken($user, $timestamp = null)
	{
		/*
		 * Piwik does not stored the generated password reset token.
		 * This avoids a database schema change and SQL queries to store, retrieve, and purge (expired) tokens.
		 */
		if(!$timestamp)
		{
			$timestamp = time() + 24*60*60; /* +24 hrs */
		}

		$expiry = strftime('%Y%m%d%H', $timestamp); 
		$token = md5($expiry . $user['login'] . $user['email'] . $user['password']);
		return $token;
	}

	/**
	 * Validate token.
	 *
	 * @param string $token
	 * @param array $user (user information)
	 * @return bool (true if valid, false otherwise)
	 */
	protected function isValidToken($token, $user)
	{
		$now = time();

		// token valid for 24 hrs (give or take, due to the coarse granularity in our strftime format string)
		for($i = 0; $i <= 24; $i++)
		{
			$generatedToken = self::generatePasswordResetToken($user, $now + $i*60*60);
			if($generatedToken == $token)
			{
				return true;
			}
		}

		// fails if token is invalid, expired, password already changed, other user information has changed, ...
		return false;
	}

	/**
	 * Clear session information
	 */
	static public function clearSession()
	{
		$authCookieName = Zend_Registry::get('config')->General->login_cookie_name;
		$cookie = new Piwik_Cookie($authCookieName);
		$cookie->delete();

		Zend_Session::expireSessionCookie();
	}

	/**
	 * Logout current user
	 */
	public function logout()
	{
		self::clearSession();
		Piwik::redirectToModule('CoreHome');
	}
}