public static function check_user_is_manager() { BaseController::check_logged_in(); if (!BaseController::get_user_logged_in()->manager) { Redirect::to(\Slim\Slim::getInstance()->urlFor('index'), array('message' => 'Sinulla ei ole oikeuksiä käyttää toimintoa!', 'error' => true)); } }
function login() { $app = \Slim\Slim::getInstance(); $json = decodeJsonOrFail($app->request->getBody()); $user = User::where('username', '=', $json['username'])->where('password', '=', $json['password'])->firstOrFail(); getUser($user->id); }
/** * Sets response body of appended data to be json_encoded * * @param int $status * @param array|null $data * @return void */ public function render($status = 200, $data = array()) { $data = array_merge(array('status' => $status), $this->all(), is_array($data) ? $data : array()); if (isset($data['flash']) && is_object($data['flash'])) { $flash = $this->data->flash->getMessages(); if (count($flash)) { $data['flash'] = $flash; } else { unset($data['flash']); } } // Nettoyage des accents des chaines de caractère à afficher array_walk($data, function (&$value, $key) { if (is_string($value)) { $value = $this->ascii_to_entities($value); } }); $app = \Slim\Slim::getInstance(); $response = $app->response(); $response->status($status); $response->header('Content-Encoding', 'UTF-8'); $response->header('Access-Control-Allow-Origin', '*'); $response->header('Access-Control-Allow-Methods', '*'); $response->header('Content-Type', 'application/json;charset=UTF-8'); $response->body(html_entity_decode(json_encode($data, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT))); }
public static function Authenticate($route) { $app = \Slim\Slim::getInstance(); try { $args = $route->getParam('args'); if ($args && in_array($args[0], array('login', 'register', 'getlookups'))) { return; } } catch (Exception $e) { } if ($app->auth->getUser()) { return; } $username = $app->request()->headers('PHP_AUTH_USER'); $password = $app->request()->headers('PHP_AUTH_PW'); if (false && isset($username) && isset($password)) { $rs = $app->orm->user->where(array('user_number' => $username, 'password ' => $password))->limit(1); if (count($rs)) { $user = $app->orm->toArray($rs)[0]; if ($user) { unset($user['password']); $app->auth->setUser($user); $app->session->set('_auth_', $app->auth->getUser()); return; } } } else { $user = $app->session->get('_auth_'); if ($user) { $app->auth->setUser($user); return; } } $app->writeJSON(null, 401, 'Unauthorized'); }
function authenticate(\Slim\Route $route) { $app = \Slim\Slim::getInstance(); if (API_TOKEN != $_POST['token']) { $app->halt(401); } }
public function query($dql, $page_size = 10, $current_page = 1) { $app = Slim::getInstance(); $query = $app->em->createQuery($dql)->setFirstResult($page_size * ($current_page - 1))->setMaxResults($page_size); $paginator = new Paginator($query); return $paginator; }
/** * Save an event to the database. If an id is given, the existing event is * updated, if not a new one is created. The event will be stored in the * events table and all properties given as arrays are stored in the * accompanying junction table. * * @param $event - map of an event with the following keys * - title => the title of the event * - summary => the summary of the post mortem * - starttime => start time as unix timestamp * - endtime => end time as unix timestamp * - statustime => status time as unix timestamp * - detecttime => detect time as unix timestamp * @param $conn - PDO connection object, will be newly instantiated when * null (default: null) * * @returns the event map including an "id" field on success and a map of the * form ( "id" => null, "error" => "an error message" ) on failure */ static function save_event($event, $conn = null) { $conn = $conn ?: Persistence::get_database_object(); if (is_null($conn)) { return array("id" => null, "error" => "Couldn't get connection object."); } $action = isset($event["id"]) ? self::ACTION_EDIT : self::ACTION_ADD; if ($action == self::ACTION_ADD) { $now = new DateTime(null, new DateTimeZone('UTC')); $event["created"] = $now->getTimestamp(); } $event = Persistence::save_event($event, $conn); if (is_null($event["id"])) { return $event; } if ($action == self::ACTION_ADD) { $app = \Slim\Slim::getInstance(); $env = $app->environment; $admin = $env['admin']['username']; $result = Postmortem::add_history($event["id"], $admin, $action); } // close connection and return $conn = null; return $event; }
public function render($status = 200, $data = NULL) { $app = \Slim\Slim::getInstance(); $status = (int) $status; $response = $this->all(); //add flash messages if (isset($this->data->flash) && is_object($this->data->flash)) { $flash = $this->data->flash->getMessages(); if (count($flash)) { $response['flash'] = $flash; } else { unset($response['flash']); } } // if $response array contains only one scalar value, extract it if (isset($response[0]) && count($response) === 1 && is_scalar($response[0])) { $response = $response[0]; } $app->response()->status($status); $app->response()->header('Content-Type', $this->contentType); $jsonp_callback = $app->request->get('callback', null); if ($jsonp_callback !== null) { $app->response()->body($jsonp_callback . '(' . json_encode($response, $this->encodingOptions) . ')'); } else { $app->response()->body(json_encode($response, $this->encodingOptions)); } $app->stop(); }
/** * Fetch an L10n content string * * @param $key string YAML key of the desired text string * @param $language string Optionally override the desired language * @return mixed */ public static function fetch($key, $language = null, $lower = false) { $app = \Slim\Slim::getInstance(); $language = $language ? $language : Config::getCurrentLanguage(); $value = $key; /* |-------------------------------------------------------------------------- | Check for new language |-------------------------------------------------------------------------- | | English is loaded by default. If requesting a language not already | cached, go grab it. | */ if (!isset($app->config['_translations'][$language])) { $app->config['_translations'][$language] = YAML::parse(Config::getTranslation($language)); } /* |-------------------------------------------------------------------------- | Resolve translation |-------------------------------------------------------------------------- | | If the set language is found and the key exists, return it. Falls back to | English, and then falls back to the slug-style key itself. | */ if (array_get($app->config['_translations'][$language]['translations'], $value, false)) { $value = array_get($app->config['_translations'][$language]['translations'], $value); } else { $value = array_get($app->config['_translations']['en']['translations'], $value, $value); } return $lower ? strtolower($value) : $value; }
/** * Checks to see if a user is currently logged in * * @return Member|null */ public static function getLoggedInMember() { // grab the cookie $app = \Slim\Slim::getInstance(); $cookie = $app->getEncryptedCookie('stat_auth_cookie'); if (strpos($cookie, ':') === false) { return null; } // break it into parts and create the Member object list($username, $hash) = explode(":", $cookie); $member = self::getMember($username); // was a Member object found? if ($member) { $hash = self::createHash($member); // compare the stored hash to a fresh one, do they match? if ($cookie === $hash) { // they match, Member is valid, extend lifetime $expire = $app->config['_cookies.lifetime']; $app->setEncryptedCookie('stat_auth_cookie', $cookie, $expire); // return the Member object return $member; } } // something above went wrong, return null return null; }
public function getHandler($conn) { Context::clear(); $app = \Slim\Slim::getInstance(); $credentials = $conn->WebSocket->request->getQuery()->toArray(); // // Aparently, this doesn't work as expected. // // set x-auth-token if (isset($credentials['X-Auth-Token'])) { $app->request->headers->set('X-Auth-Token', $credentials['X-Auth-Token']); unset($credentials['X-Auth-Token']); } // remove "/" and possible "ws/" from resource path $resource = str_replace("ws/", "", substr($conn->WebSocket->request->getPath(), 1)); $hash = md5($resource . join(",", array_values($credentials))); if (!isset($this->handlers[$hash])) { if ($key = Model\AppKey::where('app_id', $credentials['X-App-Id'])->where('key', $credentials['X-App-Key'])->first()) { Context::setKey($key); $channel = Model\Module::channel($resource); if ($channel) { $this->handlers[$hash] = $channel->compile(); } } } return isset($this->handlers[$hash]) ? $this->handlers[$hash] : null; }
/** * Adding Middle Layer to authenticate every request * Checking if the request has valid api key in the 'Authorization' header */ function authenticate(\Slim\Route $route) { // Getting request headers $headers = apache_request_headers(); $response = array(); $app = \Slim\Slim::getInstance(); // Verifying Authorization Header if (isset($headers['Authorization'])) { $db = new DBHandler(); // get the api key $apikey = $headers['Authorization']; // validating api key if (!$db->isValidApiKey($apikey)) { // api key is not present in users table $response["error"] = true; $response["message"] = "Zugriff verweigert! Falscher API-Key!"; echoRespnse(401, $response); $app->stop(); } else { global $userid; // get user primary key id $user = $db->getUserId($apikey); if ($user != NULL) { $userid = $user; } } } else { // api key is missing in header $response["error"] = true; $response["message"] = "Zugriff verweigert! API-Key fehlt!"; echoRespnse(400, $response); $app->stop(); } }
/** * Renders the template. * * @param string $template The HTTP status code. * @param null $data Not used. * @return string|void */ public function render($status, $data = null) { $app = \Slim\Slim::getInstance(); $app->contentType('application/json'); $app->expires(0); $app->response()->setStatus(intval($status)); $response = ['status' => $status]; $error = $this->data->get('error', false); switch ($status) { case 404: $error = $error ? $error : 'Resource not found'; break; case 500: $error = $error ? $error : 'Server Error'; break; } if ($error) { $response['error'] = $error; } $keys = $this->data->keys(); unset($keys[array_search('flash', $keys)]); foreach ($keys as $key) { $response[$key] = $this->data->get($key); } $app->response()->body(json_encode($response, JSON_NUMERIC_CHECK)); }
function checkAdminAuthorization() { $app = \Slim\Slim::getInstance(); if ($app->userHelper->checkAdminAuthorization() != true) { $app->halt(403, "You have to have admin rights."); } }
function auth(){ $app2 = \Slim\Slim::getInstance(); $req=$app2->request(); $key=$req->get('key'); $key=md5($key); if($key==''){ $app2->render (401,array('msg'=>'Key incorrecto','error'=>'true')); } $conn = mysqli_connect('127.0.0.1','root','155070847','monitoreo'); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql="select * from users where pass='******'"; $result = mysqli_query($conn,$sql); $row_cnt = mysqli_num_rows($result); if($row_cnt == 0) $app2->render (401,array('msg'=>'Key incorrecto','error'=>'true')); mysqli_close($conn); }
/** * @param int|string $status * @param array|null $data * @return void */ public function render($status, $data = null) { $app = Slim::getInstance(); $response = $this->all(); $status = \intval($status); $app->response()->status($status); if (isset($response['flash']) && \is_object($response['flash'])) { $flash = $this->data->flash->getMessages(); if (count($flash)) { $response['flash'] = $flash; } else { unset($response['flash']); } } switch ($status) { case 200: $responseType = 'success'; break; case 500: $responseType = 'fail'; break; default: $responseType = 'error'; $response = $response['error']; } $app->response()->header('Content-Type', 'application/json'); $app->response()->body(JSendResponse::$responseType($response)); //echo JSendResponse::$responseType($response); }
/** * * @return \Slim\Slim */ protected function getApp() { if (null === $this->app) { $this->app = \Slim\Slim::getInstance(); } return $this->app; }
/** * @return \Slim\Slim */ public function getApp() { if (is_null($this->_app)) { $this->_app = \Slim\Slim::getInstance(); } return $this->_app; }
function verifyRequiredParams($required_fields) { $error = false; $error_fields = ""; $request_params = array(); $request_params = $_REQUEST; // Handling PUT request params if ($_SERVER['REQUEST_METHOD'] == 'PUT') { $app = \Slim\Slim::getInstance(); parse_str($app->request()->getBody(), $request_params); } foreach ($required_fields as $field) { if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) { $error = true; $error_fields .= $field . ', '; } } if ($error) { // Required field(s) are missing or empty // echo error json and stop the app $response = array(); $app = \Slim\Slim::getInstance(); $response["status"] = false; $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty'; echo json_encode($response); $app->stop(); } }
function login() { $request = \Slim\Slim::getInstance()->request(); $usuario = json_decode($request->getBody()); $sql_query = "SELECT * FROM administrador WHERE usuario = '{$usuario->usuario}' AND password = '******'"; try { $dbCon = getConnection(); $stmt = $dbCon->query($sql_query); $admin = $stmt->fetchAll(PDO::FETCH_OBJ); $dbCon = null; } catch (PDOException $e) { $answer = array('estatus' => 'error', 'msj' => $e->getMessage()); } $sql_query = "SELECT * FROM clientes WHERE usuario = '{$usuario->usuario}' AND password = '******'"; try { $dbCon = getConnection(); $stmt = $dbCon->query($sql_query); $cliente = $stmt->fetchAll(PDO::FETCH_OBJ); $dbCon = null; } catch (PDOException $e) { $answer = array('estatus' => 'error', 'msj' => $e->getMessage()); } if (count($admin) > 0) { $admin = $admin[0]; $answer = array('estatus' => 'ok', 'msj' => "¡Bienvenido {$admin->nombre}!", 'tipoUsuario' => 'admin', 'admin' => $admin); } else { if (count($cliente) > 0) { $cliente = $cliente[0]; $answer = array('estatus' => 'ok', 'msj' => "¡Bienvenido {$cliente->nombre}!", 'tipoUsuario' => 'cliente', 'cliente' => $cliente); } else { $answer = array('estatus' => 'error', 'msj' => 'Usuario y/o contraseña incorrecta. Por Favor intente de nuevo.'); } } echo json_encode($answer); }
/** * Sets a buch of static API calls * */ function __construct() { $app = \Slim\Slim::getInstance(); $app->config('debug', false); $app->response()->header('Access-Control-Allow-Origin', '*'); // Mirrors the API request $app->get('/return', function () use($app) { $app->render(200, array('method' => $app->request()->getMethod(), 'name' => $app->request()->get('name'), 'headers' => $app->request()->headers(), 'params' => $app->request()->params())); }); // Generic error handler $app->error(function (Exception $e) use($app) { $app->render($e->getCode(), array('error' => true, 'msg' => \ApiMiddleware::_errorType($e->getCode()) . ": " . $e->getMessage())); }); // Not found handler (invalid routes, invalid method types) $app->notFound(function () use($app) { $app->render(404, array('error' => TRUE, 'msg' => 'Invalid route')); }); // Handle Empty response body $app->hook('slim.after.router', function () use($app) { //Fix sugested by: https://github.com/bdpsoft //Will allow download request to flow if ($app->response()->header('Content-Type') === 'application/octet-stream') { return; } if (strlen($app->response()->body()) == 0) { $app->render(500, array('error' => TRUE, 'msg' => 'Empty response')); } }); }
protected static function getApp() { if (!self::$app) { self::$app = Slim::getInstance(); } return self::$app; }
public function run($id) { header('X-Accel-Buffering: no'); $app = \Slim\Slim::getInstance(); $query = "SELECT * FROM batch WHERE bid=?"; try { $stmt = $this->db->prepare($query); $stmt->execute(array($id)); if ($stmt->rowCount() > 0) { $batch = $stmt->fetch(PDO::FETCH_ASSOC); $params = unserialize($batch['params']); if (!empty($params)) { call_user_func($batch['batch'], $params['status'], $params['pids']); } else { call_user_func($batch['batch']); } sleep(1); $response = array('redirect' => isset($_SESSION['batch_uri']) ? $_SESSION['batch_uri'] : null); echo json_encode($response); $this->db = null; } else { return false; } } catch (PDOException $e) { error_log($e->getMessage(), 3, 'log/php.log'); } }
public function call() { $app = Slim::getInstance(); $this->app->container->singleton(__NAMESPACE__, function () { return $this; }); // make them available for other classes */ $hook = function ($app) { $plugin = $this->app->container->get(__NAMESPACE__); return function () use($app, $plugin) { /* $env = $app->environment(); $current = $app->request()->getPathInfo() != '/' ? $app->request()->getURL().str_replace( $app->request()->getPathInfo(), $env['slim.localization.original_path'], $app->request()->getPath() ) : $app->request()->getURL().$app->request()->getPath().trim($env['slim.localization.original_path'], '/'); $target = $app->request()->getPathInfo() != '/' ? 'http://' . $app->request()->getHost() . str_replace( $app->request()->getPathInfo(), '/'.$app->config('i18n.locale'), $app->request()->getPath() ) . $app->request()->getPathInfo() : 'http://' . $app->request()->getHost() . $app->request()->getPath() . $app->config('i18n.locale'); $app->page->canonical = $target; if( $current != $target ) echo '<link rel="canonical" href="'.$target.'" />';*/ }; }; $app->hook('header', $hook($app)); $this->next->call(); }
/** * Logout * * Controller for the Authenticate module. * * @author Goran Halusa <*****@*****.**> * @since 0.1.0 */ function logout() { $app = \Slim\Slim::getInstance(); $final_global_template_vars = $app->config('final_global_template_vars'); unset($_SESSION[$final_global_template_vars["session_key"]]); $app->redirect($final_global_template_vars["login_url"]); }
public function __construct(array $config = array()) { if (!isset($this->app)) { $this->app = \Slim\Slim::getInstance(); } $this->config = array_merge($this->settings, $config); }
/** * Verify Email * * Controller for the User Account module. * * @author Goran Halusa <*****@*****.**> * @since 0.1.0 */ function verify_email() { $app = \Slim\Slim::getInstance(); $final_global_template_vars = $app->config('final_global_template_vars'); require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/user_account.class.php"; $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]); $db_resource = $db_conn->get_resource(); $get_data = $app->request()->get() ? $app->request()->get() : false; $message = array(); // SELECT this user from the database $statement = $db_resource->prepare("SELECT user_account_email\n ,first_name\n ,last_name\n ,emailed_hash\n FROM user_account\n WHERE user_account_email = :user_account_email\n AND emailed_hash = :emailed_hash\n AND active = 0"); $statement->bindValue(":user_account_email", $get_data['user_account_email'], PDO::PARAM_STR); $statement->bindValue(":emailed_hash", $get_data['emailed_hash'], PDO::PARAM_STR); $statement->execute(); $data = $statement->fetch(PDO::FETCH_ASSOC); $error = $db_resource->errorInfo(); if ($error[0] != "00000") { die('The SELECT FROM user_account failed.'); } if ($data) { // UPDATE this user account to be active $statement = $db_resource->prepare("UPDATE user_account\n SET active = 1\n WHERE user_account_email = :user_account_email\n AND emailed_hash = :emailed_hash"); $statement->bindValue(":user_account_email", $get_data['user_account_email'], PDO::PARAM_STR); $statement->bindValue(":emailed_hash", $get_data['emailed_hash'], PDO::PARAM_STR); $statement->execute(); $error = $db_resource->errorInfo(); if ($error[0] != "00000") { die('The UPDATE user_account active flag.'); } $message["success"] = "Email address verification was successful."; } else { $message["failed"] = "Email address verification failed. Do you already have an active account?"; } $app->render('verify_email.php', array("page_title" => "Email Address Verification", "hide_page_header" => true, "message" => $message)); }
function view_blog() { require_once ROOT . '/application/models/Post.php'; $app = \Slim\Slim::getInstance(); $posts = Post::getMarkdownPosts(Post::POST_PATH); return $app->render('view_blog.php', array('posts' => $posts, 'pagination' => 4)); }
function authenticate(\Slim\Route $route) { // Getting request headers $headers = apache_request_headers(); $response = array(); $app = \Slim\Slim::getInstance(); // Verifying Authorization Header if (isset($headers['Authorization'])) { $db = new UserDbHandler(); // get the api key $api_key = $headers['Authorization']; // validating api key if (!$db->isValidApiKey($api_key)) { // api key is not present in users table $response["error"] = true; $response["message"] = "Access Denied. Invalid Api key"; echoResponse(401, $response); $app->stop(); } else { global $user_id; // get user primary key id $user = $db->getUserId($api_key); if ($user != NULL) { $user_id = $user["id"]; } } } else { // api key is missing in header $response["error"] = true; $response["message"] = "Api key is misssing"; echoResponse(400, $response); $app->stop(); } }
function postMainmsg() { if (isset($_SESSION['user_id'])) { $request = \Slim\Slim::getInstance()->request(); $postData = json_decode($request->getBody()); $userID = $_SESSION['user_id']; $urlavat = './udata/' . $userID . '/avatar/avat.jpeg'; if (strlen(strip_tags($postData->bo)) <= 256) { $sql = "INSERT INTO post(user_id,post_header, post_body, post_type,avat_url)\n\t\t\tVALUES (:user,:he,:bo,'MAIN',:avaturl)"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("user", $userID); $stmt->bindParam("he", $postData->he); $stmt->bindParam("bo", $postData->bo); $stmt->bindParam("avaturl", $urlavat); $stmt->execute(); $db = null; echo strlen(strip_tags($postData->bo)); } catch (PDOException $e) { echo '{"error":{"text":' . $e->getMessage() . '}}'; } } else { echo "error"; } } }