Example of usage
use Bluz\Proxy\Session;
lazy session loading
Session::set('some key in session', 'value example');
Session::get('some key in session');
/** * Test Auth Identity clear * * @covers \Bluz\Auth\Auth::getIdentity * @covers \Bluz\Auth\Auth::clearIdentity */ public function testAuthClearIdentityWithWrongUserAgent() { $adminIdentity = new UserAdmin(); Session::set('auth:agent', 'agent:php'); Session::set('auth:identity', $adminIdentity); $_SERVER['HTTP_USER_AGENT'] = 'agent:cli'; $this->assertNull(Auth::getIdentity()); }
/** * updateOne * * @param array $data * @return integer */ public function updateOne($id, $data) { $id = (int) $id[0]; \Application\MusicianType\Table::getInstance()->updateTypes($data['types'], $id); if (Session::get('image') != '') { $data['image'] = Session::get('image'); } $result = parent::updateOne($id, $data); return $result; }
public function deleteOne($primary) { //get saved data $existFilesData = Session::get('files'); $files = unserialize($existFilesData); $fileId = reset($primary); $file = $files[$fileId]; if (is_file(PATH_PUBLIC . '/uploads/menu/' . $file->getName() . '.' . $file->getExtension())) { @unlink(PATH_PUBLIC . '/uploads/menu/' . $file->getName() . '.' . $file->getExtension()); } unset($files[$fileId]); Session::set('files', serialize($files)); }
/** * Denied access * @throws ForbiddenException * @return void */ public function denied() { // add messages make sense only if presentation is not json, xml, etc if (!$this->getResponse()->getPresentation()) { Messages::addError('You don\'t have permissions, please sign in'); } // redirect to login page if (!$this->user()) { // save URL to session and redirect make sense if presentation is null if (!$this->getResponse()->getPresentation()) { Session::set('rollback', Request::getRequestUri()); $this->redirectTo('users', 'signin'); } } throw new ForbiddenException(); }
/** * @param array $data * @throws Exception * @throws \Bluz\Request\RequestException * @return integer */ public function upload() { /** @var \Bluz\Http\File $file */ $file = Request::getFileUpload()->getFile('files'); $type = $file->getType(); $row = new \Application\MusicianImage\Row(); $row->getTable()->create(); $row->setFromArray(['type' => $type]); $row->beforeSave(); $row->afterSave(); if (!$file or $file->getErrorCode() != UPLOAD_ERR_OK) { if (!$file || $file->getErrorCode() == UPLOAD_ERR_NO_FILE) { throw new Exception('Please choose file to upload'); } throw new Exception('Sorry I can`t receive file'); } $name = uniqid(); $filename = $name . "." . $file->getExtension(); $file->setName($name); $file->moveTo($this->uploadDir); Session::set('image', $filename); return $file; }
/** * Initialize process * @param string $environment Array format only! * @throws ApplicationException * @return void */ public function init($environment = 'production') { $this->environment = $environment; try { // initial default helper path $this->addHelperPath(dirname(__FILE__) . '/Helper/'); // first log message Logger::info('app:init'); // setup configuration for current environment if ($debug = Config::getData('debug')) { $this->debugFlag = (bool) $debug; } // initial php settings if ($ini = Config::getData('php')) { foreach ($ini as $key => $value) { $result = ini_set($key, $value); Logger::info('app:init:php:' . $key . ':' . ($result ?: '---')); } } // init session, start inside class Session::getInstance(); // init Messages Messages::getInstance(); // init Translator Translator::getInstance(); // init request $this->initRequest(); // init response $this->initResponse(); // init router Router::getInstance(); } catch (\Exception $e) { throw new ApplicationException("Application can't be loaded: " . $e->getMessage()); } }
/** * Clear identity and user agent information * @api * @return void */ public function clearIdentity() { $this->identity = null; Session::delete('auth:identity'); Session::delete('auth:agent'); }
<?php /** * Default module/controllers * * @author Anton Shevchuk * @created 06.07.11 18:39 * @return closure */ namespace Application; use Bluz\Proxy\Layout; use Bluz\Proxy\Session; return function () use($view) { /** * @var Bootstrap $this * @var \Bluz\View\View $view */ Layout::breadCrumbs([$view->ahref('Test', ['test', 'index']), 'Session']); Layout::title("Test/Index"); Session::set('test', Session::get('test') ?: 'Session time: ' . date("H:i:s")); $view->title = Layout::title(); $view->session = Session::get('test'); // if ($identity = $app->user()) { // var_dump($acl->isAllowed('index/index', $identity['sid'])); // var_dump($acl->isAllowed('index/test', $identity['sid'])); // var_dump($acl->isAllowed('index/error', $identity['sid'])); // } else { // Auth::authenticate('admin', '123456'); // } };
if (empty($login)) { throw new Exception("Login is empty"); } if (empty($password)) { throw new Exception("Password is empty"); } // login/password // throw AuthException Auth\Table::getInstance()->authenticateEquals($login, $password); if ($rememberMe) { Auth\Table::getInstance()->generateCookie(); } Messages::addNotice('You are signed'); // try to rollback to previous called URL if ($rollback = Session::get('rollback')) { Session::delete('rollback'); $this->redirect($rollback); } // try back to index $this->redirectTo('index', 'index'); } catch (Exception $e) { Messages::addError($e->getMessage()); $view->login = $login; } catch (AuthException $e) { Messages::addError($e->getMessage()); $view->login = $login; } } // change layout $this->useLayout('small.phtml'); };
/** * Returns current messages store * * @return \ArrayObject|null Returns null if store not exists yet */ protected function getMessagesStore() { return Session::get('messages:store'); }
public function readOne($primary) { $filesArray = unserialize(Session::get('files')); $path = Config::getModuleData('menu', 'full_path'); if ($filesArray) { foreach ($filesArray as $file) { $filename = $path . $file->getFullName(); if (is_file($filename)) { unlink($filename); } } } Session::delete('files'); return parent::readOne($primary); }
/** * Can entity login * * @throws Exception * @throws AuthException * @return void */ public function tryLogin() { switch ($this->status) { case Table::STATUS_PENDING: throw new AuthException("Your account is pending activation", 403); case Table::STATUS_DISABLED: throw new AuthException("Your account is disabled by administrator", 403); case Table::STATUS_ACTIVE: // all ok // regenerate session if (PHP_SAPI !== 'cli') { Session::regenerateId(); } // save user to new session Auth::setIdentity($this); break; default: throw new Exception("User status is undefined in system"); } }
/** * Initialize process * * @param string $environment * @throws ApplicationException * @return void */ public function init($environment = 'production') { $this->environment = $environment; try { // first log message Logger::info('app:init'); // initial default helper path $this->addHelperPath(dirname(__FILE__) . '/Helper/'); // init Config $this->initConfig(); // init Session, start inside class (if needed) Session::getInstance(); // init Messages Messages::getInstance(); // init Translator Translator::getInstance(); // init Request $this->initRequest(); // init Response $this->initResponse(); // init Router $this->initRouter(); } catch (\Exception $e) { throw new ApplicationException("Application can't be loaded: " . $e->getMessage()); } }
* @namespace */ namespace Application; use Application\Media; use Bluz\Controller; use Bluz\Proxy\Config; use Bluz\Proxy\Layout; use Bluz\Proxy\Session; use Bluz\Request\AbstractRequest; return function () use($view) { /** * @var Bootstrap $this * @var \Bluz\View\View $view */ Session::start(); $this->useLayout('dashboard.phtml'); Layout::breadCrumbs([$view->ahref('Dashboard', ['dashboard', 'index']), $view->ahref('Media', ['media', 'grid']), __('Upload')]); if (!$this->user()) { throw new Exception('User not found'); } $userId = $this->user()->id; $crud = Media\Crud::getInstance(); // get path from config $path = Config::getModuleData('media', 'upload_path'); if (empty($path)) { throw new Exception('Upload path is not configured'); } $crud->setUploadDir($path . '/' . $userId . '/media'); $crudController = new Controller\Crud(); $crudController->setCrud($crud);
/** * Denied access * @param ForbiddenException $exception * @return \Bluz\Controller\Controller|null */ public function forbidden(ForbiddenException $exception) { if (AuthProxy::getIdentity()) { $message = Translator::translate("You don't have permissions to access this page"); } else { $message = Translator::translate("You don't have permissions, please sign in"); } // for AJAX and API calls (over JSON) $jsonOrApi = Request::isXmlHttpRequest() || Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON; // for guest, for requests if (!AuthProxy::getIdentity() && !$jsonOrApi) { // save URL to session and redirect make sense if presentation is null Session::set('rollback', Request::getUri()->__toString()); // add error notice Messages::addError($message); // redirect to Sign In page $url = Router::getUrl('users', 'signin'); return $this->redirect($url); } else { return $this->error(new ForbiddenException($message, 403, $exception)); } }