summaryrefslogtreecommitdiff
path: root/demos/time-tracker/protected/App_Code/TrackerAuthManager.php
blob: ea6b5aabed079ddf7327fc1945be187581d42f84 (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
<?php
/**
 * Custom Authentication manager permits authentication using
 * a string token saved in the cookie.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id$
 * @package Demos
 * @since 3.1
 */
class TrackerAuthManager extends TAuthManager
{
	/**
	 * @const string signon token cookie name.
	 */
	const SignonCookieName = 'time-tracker-signon';
	
	/**
	 * Performs the real authentication work. Overrides and calls parent
	 * implementation. Trys to authenticate using token saved in cookie. 
	 * @param mixed parameter to be passed to OnAuthenticate event
	 */
	public function onAuthenticate($param)
	{
		parent::onAuthenticate($param);
		$currentUser = $this->Application->User; 
		if(!$currentUser || $currentUser->IsGuest)
			$this->authenticateFromCookie($param);
	}
	
	/**
	 * If the user is not set or is still a guest, try to authenticate the user
	 * using a string token saved in the cookie if any.
	 * @param mixed parameter to be passed to OnAuthenticate event 
	 */
	protected function authenticateFromCookie($param)
	{
		$cookie = $this->Request->Cookies[self::SignonCookieName];
		if(!is_null($cookie))
		{
			$daos = $this->getApplication()->getModule('daos');
			$userDao = $daos->getDao('UserDao');
			$user = $userDao->validateSignon($cookie->Value);
			if($user instanceof TimeTrackerUser)
				$this->updateCredential($user);
		}
	}
	
	/**
	 * Changes the user credentials.
	 * @param TUser new user details.
	 */
	public function updateCredential($user)
	{
		$user->IsGuest = false;
		$this->updateSessionUser($user);
		$this->Application->User = $user;		
	}
	
	/**
	 * Generate a token to be saved in the cookie for later authentication.
	 * @param TimeTrackerUser user details.
	 */
	public function rememberSignon($user)
	{
		$daos = $this->getApplication()->getModule('daos');
		$userDao = $daos->getDao('UserDao');
		$token = $userDao->createSignonToken($user);
		$cookie = new THttpCookie(self::SignonCookieName, $token);
		$cookie->Expire = strtotime('+1 month');
		$this->Response->Cookies[] = $cookie;
	}
	
	/**
	 * Logs out the user and delete the token from cookie.
	 */
	public function logout()
	{
		parent::logout();
		$cookie = new THttpCookie(self::SignonCookieName,'');
		$this->Response->Cookies[] = $cookie;
	}
}

?>