Example #1
0
 public function isUserAuthenticated($auth_required = true)
 {
     // Cached Result... (if checked before, return the result)
     if ($this->authentication != self::AUTH_UNKNOWN) {
         return $this->authentication == self::AUTH_PASSED;
     }
     // Check Token Validity -- Avoid DB Overhead
     if (self::isSessionIDValid($this->id)) {
         $db = Database::getConnection();
         $query = $db->query("SELECT user_id, update_timestamp, persistent FROM " . self::TABLE_NAME . " WHERE (id=:id) AND (expiry_timestamp > :now)", array(":id" => $this->id, ":now" => Carbon::now()));
     } else {
         if (!$auth_required) {
             return false;
         }
     }
     // Check Query Result (and that it was executed)
     if (isset($query) && $query && $query->rowCount()) {
         $db_row = $query->fetch(PDO::FETCH_ASSOC);
         $this->user_id = $db_row['user_id'];
         // only set here, force people to call this function first before being allowed to look at the ID
         // We need to renew sessions on a regular basis in order for us to determine when sessions become inactive...
         if (Carbon::parse($db_row['update_timestamp'])->diffInSeconds(Carbon::now()) > self::SESSION_RENEWAL_PERIOD_SECONDS) {
             $this->create($db_row['user_id'], isTrue($db_row['persistent']));
         }
         // renew
         $this->authentication = self::AUTH_PASSED;
         return true;
     } else {
         if ($auth_required) {
             // Determine the Current Target/Action
             $request = RequestModel::currentRequest();
             $router = RouteController::getController();
             $route = $router->findRouteForURL($request->url());
             // Add Query Params?
             $url = $router->urlForAction($route->action(), $route->extractArgs($request->url()));
             if (count($request->queryArgArray())) {
                 $url = addQueryParams($url, $request->queryArgArray());
             }
             // Request a Login
             AppController::requestUserLogin($url);
             // we need to extract and re-inject any args or we lose context...
         } else {
             $this->authentication = self::AUTH_FAILED;
             return false;
         }
     }
 }