/** * @throws \PSFS\base\exception\RouterException */ public function __construct() { $this->setAction(Router::getInstance()->getRoute('admin-setup')); $this->add('username', array('label' => _('User Alias'), 'autocomplete' => 'off'))->add('password', array('type' => 'password', 'label' => _('Password'), 'autocomplete' => 'off'))->add('profile', array('type' => 'select', 'label' => _("Role"), 'value' => sha1('superadmin'), 'autocomplete' => 'off', 'data' => Security::getProfiles())); //Apply styling to the form $this->setAttrs(array("class" => "col-md-6", "autocomplete" => "off")); //Add action buttons to form $this->addButton('submit'); }
/** * Test for specific cache functionality in requests */ public function testCacheForRequests() { $session = Security::getInstance(); $session->setSessionKey('__CACHE__', ['cache' => 1, 'http' => 'localhost/', 'slug' => 'test']); $hash = Cache::getInstance()->getRequestCacheHash(); $this->assertNotNull($hash, 'Invalid cache hash'); $this->assertEquals($hash, sha1('localhost/ test'), 'Different hash returned by cache'); $this->assertTrue(false !== Cache::needCache(), 'Test url expired or error checking cache'); }
/** * @throws \PSFS\base\exception\FormException * @throws \PSFS\base\exception\RouterException */ public function __construct() { $this->init(); $this->setAction($this->router->getRoute('admin-module'))->setAttrs(array()); $this->add('module', array('label' => _('Nombre del Módulo')))->add('force', array('label' => _('Sobreescribir ficheros'), 'type' => 'select', 'data' => array(_('No'), _('Sí')), 'required' => false))->add('is_module', array('label' => _('Es un módulo de PSFS'), 'type' => 'select', 'data' => array(_('No'), _('Sí')), 'required' => false))->add('controllerType', array('label' => _('Tipo de controlador'), 'type' => 'select', 'data' => array("" => _("Normal"), "Auth" => _("Requiere autenticación de usuario"), "AuthAdmin" => _("Requiere autenticación de administrador")), 'required' => false)); $data = Security::getInstance()->getAdmins(); //Aplicamos estilo al formulario $this->setAttrs(array('class' => 'col-md-6')); //Hidratamos el formulario $this->setData($data); //Añadimos las acciones del formulario $this->addButton('submit', 'Generar'); }
/** * Method that checks the access to the restricted zone * * @param string $route * * @throws AccessDeniedException */ public static function checkRestrictedAccess($route) { Logger::log('Checking admin zone'); //Chequeamos si entramos en el admin if (!Config::getInstance()->checkTryToSaveConfig() && (preg_match('/^\\/(admin|setup\\-admin)/i', $route) || NULL !== Config::getInstance()->get('restricted'))) { if (!file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . 'admins.json')) { //Si no hay fichero de usuarios redirigimos directamente al gestor return UserController::getInstance()->adminers(); } if (!Security::getInstance()->checkAdmin()) { throw new AccessDeniedException(); } Logger::log('Admin access granted'); } }
/** * Service to regenerate routes * @GET * @route /admin/routes/gen * @visible false * @return string HTML */ public function regenerateUrls() { $router = Router::getInstance(); try { $router->hydrateRouting(); $router->simpatize(); Security::getInstance()->setFlash("callback_message", _("Rutas generadas correctamente")); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-routes", true)); } catch (\Exception $e) { Logger::log($e->getMessage(), LOG_ERR); Security::getInstance()->setFlash("callback_message", _("Algo no ha salido bien, revisa los logs")); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-routes", true)); } return $this->redirect('admin-routes'); }
/** * Check service authentication * @return bool */ private function checkAuth() { $namespace = explode('\\', $this->getModelTableMap()); $module = strtolower($namespace[0]); $secret = Config::getInstance()->get($module . '.api.secret'); if (NULL === $secret) { $secret = Config::getInstance()->get("api.secret"); } if (NULL === $secret) { $auth = TRUE; } else { $token = Request::getInstance()->getHeader('X-API-SEC-TOKEN'); if (array_key_exists('API_TOKEN', $this->query)) { $token = $this->query['API_TOKEN']; } $auth = Security::checkToken($token ?: '', $secret, $module); } return $auth || $this->isAdmin(); }
/** * Run method * @return string HTML */ public function run() { Logger::log('Begin runner'); try { if ($this->config->isConfigured()) { if (!$this->parser->isFile()) { return $this->router->execute($this->actualUri); } } else { return ConfigController::getInstance()->config(); } } catch (ConfigException $c) { return $this->dumpException($c); } catch (SecurityException $s) { return $this->security->notAuthorized($this->actualUri); } catch (UserAuthException $u) { $this->redirectToHome(); } catch (RouterException $r) { return $this->router->httpNotFound($r); } catch (\Exception $e) { return $this->dumpException($e); } }
/** * @POST * @route /admin/module * @return string */ public function doGenerateModule() { $form = new ModuleForm(); $form->build(); $form->hydrate(); if ($form->isValid()) { $module = $form->getFieldValue("module"); $force = $form->getFieldValue("force"); $type = $form->getFieldValue("controllerType"); $is_module = $form->getFieldValue("is_module"); try { $module = preg_replace('/(\\\\|\\/)/', '/', $module); $module = preg_replace('/^\\//', '', $module); $this->gen->createStructureModule($module, $force, $type, (bool) $is_module); Security::getInstance()->setFlash("callback_message", str_replace("%s", $module, _("Módulo %s generado correctamente"))); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-module", true)); } catch (\Exception $e) { pre($e->getMessage(), true); Logger::getInstance()->infoLog($e->getMessage() . " [" . $e->getFile() . ":" . $e->getLine() . "]"); throw new ConfigException('Error al generar el módulo, prueba a cambiar los permisos', 403); } } return $this->render("modules.html.twig", array('properties' => $this->config->getPropelParams(), 'form' => $form)); }
/** * Servicio que guarda la configuración de la plataforma * @POST * @route /admin/config * @visible false * @return string * @throws \HttpException */ public function saveConfig() { Logger::getInstance()->infoLog(_("Guardando configuración")); /* @var $form \PSFS\base\config\ConfigForm */ $form = new ConfigForm(Router::getInstance()->getRoute('admin-config'), Config::$required, Config::$optional, Config::getInstance()->dumpConfig()); $form->build(); $form->hydrate(); if ($form->isValid()) { $debug = Config::getInstance()->getDebugMode(); $newDebug = $form->getFieldValue("debug"); if (Config::save($form->getData(), $form->getExtraData())) { Logger::log(_('Configuración guardada correctamente')); //Verificamos si tenemos que limpiar la cache del DocumentRoot if (boolval($debug) !== boolval($newDebug)) { Config::clearDocumentRoot(); } Security::getInstance()->setFlash("callback_message", _("Configuración actualizada correctamente")); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-config", true)); } else { throw new \HttpException(_('Error al guardar la configuración, prueba a cambiar los permisos'), 403); } } return $this->render('welcome.html.twig', array('text' => _("Bienvenido a PSFS"), 'config' => $form, 'typeahead_data' => array_merge(Config::$required, Config::$optional))); }
/** * Método que ejecuta una acción del framework y revisa si lo tenemos cacheado ya o no * * @param string $route * @param array|null $action * @param types\Controller $class * @param array $params */ protected function executeCachedRoute($route, $action, $class, $params = NULL) { Logger::log('Executing route ' . $route, LOG_INFO); Security::getInstance()->setSessionKey("__CACHE__", $action); $cache = Cache::needCache(); $execute = TRUE; if (FALSE !== $cache && Config::getInstance()->getDebugMode() === FALSE) { $cacheDataName = $this->cache->getRequestCacheHash(); $cachedData = $this->cache->readFromCache("templates" . DIRECTORY_SEPARATOR . $cacheDataName, $cache, function () { }); if (NULL !== $cachedData) { $headers = $this->cache->readFromCache("templates" . DIRECTORY_SEPARATOR . $cacheDataName . ".headers", $cache, function () { }, Cache::JSON); Template::getInstance()->renderCache($cachedData, $headers); $execute = FALSE; } } if ($execute) { call_user_func_array(array($class, $action['method']), $params); } }
/** * Servicio que valida el login * @param null $route * @POST * @visible false * @route /admin/login * @return string * @throws \PSFS\base\exception\FormException */ public function postLogin($route = null) { $form = new LoginForm(); $form->setData(array("route" => $route)); $form->build(); $tpl = Template::getInstance(); $tpl->setPublicZone(true); $template = "login.html.twig"; $params = array('form' => $form); $cookies = array(); $form->hydrate(); if ($form->isValid()) { if (Security::getInstance()->checkAdmin($form->getFieldValue("user"), $form->getFieldValue("pass"))) { $cookies = array(array("name" => Security::getInstance()->getHash(), "value" => base64_encode($form->getFieldValue("user") . ":" . $form->getFieldValue("pass")), "expire" => time() + 3600, "http" => true)); $template = "redirect.html.twig"; $params = array('route' => $form->getFieldValue("route"), 'status_message' => _("Acceso permitido... redirigiendo!!"), 'delay' => 1); } else { $form->setError("user", _("El usuario no tiene acceso a la web")); } } return $tpl->render($template, $params, $cookies); }
/** * Basic test for Security functionality */ public function testSecurity() { $security = Security::getInstance(); // Is Security instance? $this->assertTrue($security instanceof Security); }
/** * Método que realiza una redirección a la url dada * @param string $url */ public function redirect($url = null) { if (null === $url) { $url = $this->getServer('HTTP_ORIGIN'); } ob_start(); header('Location: ' . $url); ob_end_clean(); Security::getInstance()->updateSession(); exit(_("Redireccionando...")); }
/** * Servicio que chequea si un usuario es super administrador o no * @return bool */ public function isSuperAdmin() { $users = $this->getAdmins(); $logged = $this->getAdminFromCookie(); $profiles = Security::getCleanProfiles(); if ($users[$logged[0]]) { $security = $users[$logged[0]]['profile']; return $profiles['__SUPER_ADMIN__'] === $security; } return FALSE; }
/** * Método que construye un hash para almacenar la cache * @return string */ public function getRequestCacheHash() { $hash = ""; $action = Security::getInstance()->getSessionKey("__CACHE__"); if (null !== $action && $action["cache"] > 0) { $hash = $action["http"] . " " . $action["slug"]; } return sha1($hash); }
/** * Template function that get a flash session var * @param string $key * @return mixed */ public static function getFlash($key) { $var = Security::getInstance()->getFlash($key); Security::getInstance()->setFlash($key, null); return $var; }
/** * Constructor por defecto */ public function __construct() { $this->security = Security::getInstance(); }
/** * Método que devuelve el contenido de una plantilla * @param string $tpl * @param array $vars * @return string */ public function dump($tpl, array $vars = array()) { $vars["__user__"] = Security::getInstance()->getUser(); $vars["__admin__"] = Security::getInstance()->getAdmin(); $vars["__profiles__"] = Security::getCleanProfiles(); $vars["__flash__"] = Security::getInstance()->getFlashes(); $dump = ''; try { $dump = $this->tpl->render($tpl, $vars); } catch (\Exception $e) { Logger::log($e->getMessage(), LOG_ERR); } return $dump; }