Packages

  • Nette
    • Application
    • Caching
    • Collections
    • Config
    • Forms
    • IO
    • Loaders
    • Mail
    • Reflection
    • Security
    • Templates
    • Web
  • None
  • PHP

Classes

  • NFtp
  • NHtml
  • NHttpContext
  • NHttpRequest
  • NHttpResponse
  • NHttpUploadedFile
  • NSession
  • NSessionNamespace
  • NUri
  • NUriScript
  • NUser

Interfaces

  • IHttpRequest
  • IHttpResponse
  • IUser

Exceptions

  • NFtpException
  • Overview
  • Package
  • Class
  • Tree
  • Other releases
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  *
  6:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  7:  *
  8:  * For the full copyright and license information, please view
  9:  * the file license.txt that was distributed with this source code.
 10:  * @package Nette\Web
 11:  */
 12: 
 13: 
 14: 
 15: /**
 16:  * User authentication and authorization.
 17:  *
 18:  * @author     David Grudl
 19:  *
 20:  * @property-read IIdentity $identity
 21:  * @property   IAuthenticator $authenticationHandler
 22:  * @property   IAuthorizator $authorizationHandler
 23:  * @property-read int $logoutReason
 24:  * @property-read array $roles
 25:  * @property-read bool $authenticated
 26:  * @package Nette\Web
 27:  */
 28: class NUser extends NObject implements IUser
 29: {
 30:     /**#@+ log-out reason {@link NUser::getLogoutReason()} */
 31:     const MANUAL = 1;
 32:     const INACTIVITY = 2;
 33:     const BROWSER_CLOSED = 3;
 34:     /**#@-*/
 35: 
 36:     /** @var string  default role for unauthenticated user */
 37:     public $guestRole = 'guest';
 38: 
 39:     /** @var string  default role for authenticated user without own identity */
 40:     public $authenticatedRole = 'authenticated';
 41: 
 42:     /** @var array of function(User $sender); Occurs when the user is successfully logged in */
 43:     public $onLoggedIn;
 44: 
 45:     /** @var array of function(User $sender); Occurs when the user is logged out */
 46:     public $onLoggedOut;
 47: 
 48:     /** @deprecated */
 49:     public $onAuthenticated;
 50: 
 51:     /** @deprecated */
 52:     public $onSignedOut;
 53: 
 54:     /** @var IAuthenticator */
 55:     private $authenticationHandler;
 56: 
 57:     /** @var IAuthorizator */
 58:     private $authorizationHandler;
 59: 
 60:     /** @var string */
 61:     private $namespace = '';
 62: 
 63:     /** @var NSessionNamespace */
 64:     private $session;
 65: 
 66: 
 67: 
 68:     public function __construct()
 69:     {
 70:         // back compatiblity
 71:         $this->onLoggedIn = & $this->onAuthenticated;
 72:         $this->onLoggedOut = & $this->onSignedOut;
 73:     }
 74: 
 75: 
 76: 
 77:     /********************* Authentication ****************d*g**/
 78: 
 79: 
 80: 
 81:     /**
 82:      * Conducts the authentication process.
 83:      * @param  string
 84:      * @param  string
 85:      * @param  mixed
 86:      * @return void
 87:      * @throws NAuthenticationException if authentication was not successful
 88:      */
 89:     public function login($username, $password, $extra = NULL)
 90:     {
 91:         $handler = $this->getAuthenticationHandler();
 92:         if ($handler === NULL) {
 93:             throw new InvalidStateException('Authentication handler has not been set.');
 94:         }
 95: 
 96:         $this->logout(TRUE);
 97: 
 98:         $credentials = array(
 99:             IAuthenticator::USERNAME => $username,
100:             IAuthenticator::PASSWORD => $password,
101:             'extra' => $extra,
102:         );
103: 
104:         $this->setIdentity($handler->authenticate($credentials));
105:         $this->setAuthenticated(TRUE);
106:         $this->onLoggedIn($this);
107:     }
108: 
109: 
110: 
111:     /**
112:      * Logs out the user from the current session.
113:      * @param  bool  clear the identity from persistent storage?
114:      * @return void
115:      */
116:     final public function logout($clearIdentity = FALSE)
117:     {
118:         if ($this->isLoggedIn()) {
119:             $this->setAuthenticated(FALSE);
120:             $this->onLoggedOut($this);
121:         }
122: 
123:         if ($clearIdentity) {
124:             $this->setIdentity(NULL);
125:         }
126:     }
127: 
128: 
129: 
130:     /**
131:      * Is this user authenticated?
132:      * @return bool
133:      */
134:     final public function isLoggedIn()
135:     {
136:         $session = $this->getSessionNamespace(FALSE);
137:         return $session && $session->authenticated;
138:     }
139: 
140: 
141: 
142:     /**
143:      * Returns current user identity, if any.
144:      * @return IIdentity
145:      */
146:     final public function getIdentity()
147:     {
148:         $session = $this->getSessionNamespace(FALSE);
149:         return $session ? $session->identity : NULL;
150:     }
151: 
152: 
153: 
154:     /**
155:      * Sets authentication handler.
156:      * @param  IAuthenticator
157:      * @return NUser  provides a fluent interface
158:      */
159:     public function setAuthenticationHandler(IAuthenticator $handler)
160:     {
161:         $this->authenticationHandler = $handler;
162:         return $this;
163:     }
164: 
165: 
166: 
167:     /**
168:      * Returns authentication handler.
169:      * @return IAuthenticator
170:      */
171:     final public function getAuthenticationHandler()
172:     {
173:         if ($this->authenticationHandler === NULL) {
174:             $this->authenticationHandler = NEnvironment::getService('Nette\\Security\\IAuthenticator');
175:         }
176:         return $this->authenticationHandler;
177:     }
178: 
179: 
180: 
181:     /**
182:      * Changes namespace; allows more users to share a session.
183:      * @param  string
184:      * @return NUser  provides a fluent interface
185:      */
186:     public function setNamespace($namespace)
187:     {
188:         if ($this->namespace !== $namespace) {
189:             $this->namespace = (string) $namespace;
190:             $this->session = NULL;
191:         }
192:         return $this;
193:     }
194: 
195: 
196: 
197:     /**
198:      * Returns current namespace.
199:      * @return string
200:      */
201:     final public function getNamespace()
202:     {
203:         return $this->namespace;
204:     }
205: 
206: 
207: 
208:     /**
209:      * Enables log out after inactivity.
210:      * @param  string|int|DateTime number of seconds or timestamp
211:      * @param  bool  log out when the browser is closed?
212:      * @param  bool  clear the identity from persistent storage?
213:      * @return NUser  provides a fluent interface
214:      */
215:     public function setExpiration($time, $whenBrowserIsClosed = TRUE, $clearIdentity = FALSE)
216:     {
217:         $session = $this->getSessionNamespace(TRUE);
218:         if ($time) {
219:             $time = NDateTime53::from($time)->format('U');
220:             $session->expireTime = $time;
221:             $session->expireDelta = $time - time();
222: 
223:         } else {
224:             unset($session->expireTime, $session->expireDelta);
225:         }
226: 
227:         $session->expireIdentity = (bool) $clearIdentity;
228:         $session->expireBrowser = (bool) $whenBrowserIsClosed;
229:         $session->browserCheck = TRUE;
230:         $session->setExpiration(0, 'browserCheck');
231:         return $this;
232:     }
233: 
234: 
235: 
236:     /**
237:      * Why was user logged out?
238:      * @return int
239:      */
240:     final public function getLogoutReason()
241:     {
242:         $session = $this->getSessionNamespace(FALSE);
243:         return $session ? $session->reason : NULL;
244:     }
245: 
246: 
247: 
248:     /**
249:      * Returns and initializes $this->session.
250:      * @return NSessionNamespace
251:      */
252:     protected function getSessionNamespace($need)
253:     {
254:         if ($this->session !== NULL) {
255:             return $this->session;
256:         }
257: 
258:         $sessionHandler = $this->getSession();
259:         if (!$need && !$sessionHandler->exists()) {
260:             return NULL;
261:         }
262: 
263:         $this->session = $session = $sessionHandler->getNamespace('Nette.Web.User/' . $this->namespace);
264: 
265:         if (!($session->identity instanceof IIdentity) || !is_bool($session->authenticated)) {
266:             $session->remove();
267:         }
268: 
269:         if ($session->authenticated && $session->expireBrowser && !$session->browserCheck) { // check if browser was closed?
270:             $session->reason = self::BROWSER_CLOSED;
271:             $session->authenticated = FALSE;
272:             $this->onLoggedOut($this);
273:             if ($session->expireIdentity) {
274:                 unset($session->identity);
275:             }
276:         }
277: 
278:         if ($session->authenticated && $session->expireDelta > 0) { // check time expiration
279:             if ($session->expireTime < time()) {
280:                 $session->reason = self::INACTIVITY;
281:                 $session->authenticated = FALSE;
282:                 $this->onLoggedOut($this);
283:                 if ($session->expireIdentity) {
284:                     unset($session->identity);
285:                 }
286:             }
287:             $session->expireTime = time() + $session->expireDelta; // sliding expiration
288:         }
289: 
290:         if (!$session->authenticated) {
291:             unset($session->expireTime, $session->expireDelta, $session->expireIdentity,
292:                 $session->expireBrowser, $session->browserCheck, $session->authTime);
293:         }
294: 
295:         return $this->session;
296:     }
297: 
298: 
299: 
300:     /**
301:      * Sets the authenticated status of this user.
302:      * @param  bool  flag indicating the authenticated status of user
303:      * @return NUser  provides a fluent interface
304:      */
305:     protected function setAuthenticated($state)
306:     {
307:         $session = $this->getSessionNamespace(TRUE);
308:         $session->authenticated = (bool) $state;
309: 
310:         // Session Fixation defence
311:         $this->getSession()->regenerateId();
312: 
313:         if ($state) {
314:             $session->reason = NULL;
315:             $session->authTime = time(); // informative value
316: 
317:         } else {
318:             $session->reason = self::MANUAL;
319:             $session->authTime = NULL;
320:         }
321:         return $this;
322:     }
323: 
324: 
325: 
326:     /**
327:      * Sets the user identity.
328:      * @param  IIdentity
329:      * @return NUser  provides a fluent interface
330:      */
331:     protected function setIdentity(IIdentity $identity = NULL)
332:     {
333:         $this->getSessionNamespace(TRUE)->identity = $identity;
334:         return $this;
335:     }
336: 
337: 
338: 
339:     /********************* Authorization ****************d*g**/
340: 
341: 
342: 
343:     /**
344:      * Returns a list of effective roles that a user has been granted.
345:      * @return array
346:      */
347:     public function getRoles()
348:     {
349:         if (!$this->isLoggedIn()) {
350:             return array($this->guestRole);
351:         }
352: 
353:         $identity = $this->getIdentity();
354:         return $identity ? $identity->getRoles() : array($this->authenticatedRole);
355:     }
356: 
357: 
358: 
359:     /**
360:      * Is a user in the specified effective role?
361:      * @param  string
362:      * @return bool
363:      */
364:     final public function isInRole($role)
365:     {
366:         return in_array($role, $this->getRoles(), TRUE);
367:     }
368: 
369: 
370: 
371:     /**
372:      * Has a user effective access to the Resource?
373:      * If $resource is NULL, then the query applies to all resources.
374:      * @param  string  resource
375:      * @param  string  privilege
376:      * @return bool
377:      */
378:     public function isAllowed($resource = IAuthorizator::ALL, $privilege = IAuthorizator::ALL)
379:     {
380:         $handler = $this->getAuthorizationHandler();
381:         if (!$handler) {
382:             throw new InvalidStateException("Authorization handler has not been set.");
383:         }
384: 
385:         foreach ($this->getRoles() as $role) {
386:             if ($handler->isAllowed($role, $resource, $privilege)) return TRUE;
387:         }
388: 
389:         return FALSE;
390:     }
391: 
392: 
393: 
394:     /**
395:      * Sets authorization handler.
396:      * @param  IAuthorizator
397:      * @return NUser  provides a fluent interface
398:      */
399:     public function setAuthorizationHandler(IAuthorizator $handler)
400:     {
401:         $this->authorizationHandler = $handler;
402:         return $this;
403:     }
404: 
405: 
406: 
407:     /**
408:      * Returns current authorization handler.
409:      * @return IAuthorizator
410:      */
411:     final public function getAuthorizationHandler()
412:     {
413:         if ($this->authorizationHandler === NULL) {
414:             $this->authorizationHandler = NEnvironment::getService('Nette\\Security\\IAuthorizator');
415:         }
416:         return $this->authorizationHandler;
417:     }
418: 
419: 
420: 
421:     /********************* backend ****************d*g**/
422: 
423: 
424: 
425:     /**
426:      * Returns session handler.
427:      * @return NSession
428:      */
429:     protected function getSession()
430:     {
431:         return NEnvironment::getSession();
432:     }
433: 
434: 
435: 
436:     /**#@+ @deprecated */
437:     function authenticate($username, $password, $extra = NULL)
438:     {
439:         trigger_error(__METHOD__ . '() is deprecated; use login() instead.', E_USER_WARNING);
440:         return $this->login($username, $password, $extra);
441:     }
442: 
443:     function signOut($clearIdentity = FALSE)
444:     {
445:         trigger_error(__METHOD__ . '() is deprecated; use logout() instead.', E_USER_WARNING);
446:         return $this->logout($clearIdentity);
447:     }
448: 
449:     function isAuthenticated()
450:     {
451:         trigger_error(__METHOD__ . '() is deprecated; use isLoggedIn() instead.', E_USER_WARNING);
452:         return $this->isLoggedIn();
453:     }
454: 
455:     function getSignOutReason()
456:     {
457:         trigger_error(__METHOD__ . '() is deprecated; use getLogoutReason() instead.', E_USER_WARNING);
458:         return $this->getLogoutReason();
459:     }
460:     /**#@-*/
461: 
462: }
463: 
Nette Framework 0.9.7 (for PHP 5.2) API documentation generated by ApiGen 2.3.0