/** * Get survey(s) * * Call examples : * /survey : get all survey the user can view TODO check heaviness * /survey/<id> : get survey from its id * * @param int $id survey id * * @return mixed * * @throws RestBadParameterException * @throws RestOwnershipRequiredException * @throws RestSurveyNotFoundException * @throws RestNotAllowedException */ public static function get($id = null) { if ($id) { // Trying to get a single survey try { $survey = Survey::fromId($id); } catch (NotFoundException $e) { throw new RestSurveyNotFoundException($id); } // Check permission if (!$survey->can->view) { throw new RestNotAllowedException('view survey ' . $survey->id); } return self::cast($survey); } $surveys = array(); foreach (Survey::all() as $survey) { if (!Auth::isAuthenticated()) { continue; } if (!Auth::isAdmin() && !Auth::user()->is($survey->owner)) { continue; } if (!$survey->can->view) { continue; } $surveys[] = self::cast($survey); } return $surveys; }
function preDispatch() { parent::preDispatch(); $jsonRenderer = new \App\View\Renderer\Json(); $this->setLayout(''); // No layout is used. $this->setRenderer($jsonRenderer); // Require an authenticated session. if (!\Auth::isAuthenticated()) { header('HTTP/1.1 401 Authorization Required'); exit; } }
<?php /** * Displays login form */ if (Auth::isAuthenticated()) { Util::getTemplate('index.php'); return; } Util::getHeader(); ?> <!-- Page Heading --> <div class="row"> <div class="col-lg-4"> <h1 class="page-header">Login</h1> <?php if (isset($GLOBALS['error'])) { global $error; ?> <div class="alert alert-danger" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> <?php echo $error; ?> </div> <?php } ?>
/** * This file is part of the BaseProject project. * 2015 * Copyright (c) RENATER */ define('APPLICATION_BASE', realpath(dirname(__FILE__) . '/../../')); // Include classes autoloader require_once APPLICATION_BASE . '/classes/core/autoload.php'; // Set default timezone date_default_timezone_set(Config::get('default_timezone')); // Set encoding mb_internal_encoding('UTF-8'); if (php_sapi_name() === 'cli') { // Command Line Interface include APPLICATION_BASE . '/includes/core/init_cli.php'; Logger::setProcess(ProcessTypes::CLI); } else { // Default, web server include APPLICATION_BASE . '/includes/core/init_web.php'; Logger::setProcess(ProcessTypes::WEB); } // Report all errors ini_set('display_errors', Config::get('debug') ? '1' : '0'); PluginManager::initialize(); if (file_exists(APPLICATION_BASE . '/includes/init.php')) { include APPLICATION_BASE . '/includes/init.php'; } (new Event('init_done'))->trigger(); if (php_sapi_name() !== 'cli' && Auth::isAuthenticated()) { Auth::user()->recordActivity(); }
public function sendRequest() { //add authentication headers, if they exist if (Auth::isAuthenticated()) { $this->addLsmAuth(); } //add the headers foreach ($this->_headers as $k => $v) { $this->_ch->setHeader($k, $v); } //determine our method and send the request switch ($this->_method) { case "post": $this->_ch->post($this->_url, $this->_ch->buildPostData($this->_parameters)); break; case "put": $this->_ch->put($this->_url, $this->_parameters); break; case "delete": $this->_ch->delete($this->_url, $this->_parameters); break; default: case "get": $this->_ch->get($this->_url, $this->_parameters); break; } $this->_responseHeaders = $this->_ch->responseHeaders; $this->_responseStatus = $this->_ch->httpStatusCode; $this->_responseBody = $this->_ch->response; $this->_rawResponseBody = $this->_ch->rawResponse; if ($this->_debug) { echo "<pre class='debug'><h3>DEBUG - DUMP OF LSM CURL WRAPPER:</h3>" . PHP_EOL; var_dump($this); echo "</pre>"; } }
/** * Get user specific instance uid * * @return string */ public static function userUID($user_specific = false) { if (is_null(self::$uids['user'])) { $uid = hash_hmac('sha1', Auth::isAuthenticated() ? Auth::user()->id : 'anonymous', self::instanceUID()); self::$uids['user'] = substr($uid, -12); } return self::$uids['user']; }
/** * Get user(s) * * Call examples : * /user : get all users (admin) * /user/@me : get current user (null if no session) * /user/<uid> : get user (admin or current) * * @param int $id user id to get info about * * @return mixed * * @throws RestAuthenticationRequiredException * @throws RestAdminRequiredException * @throws RestBadParameterException */ public static function get($id = null) { // "Session getter" if ($id == '@me') { return Auth::isAuthenticated() ? static::cast(Auth::user()) : null; } // Need to be authenticated ... if (!Auth::isAuthenticated()) { throw new RestAuthenticationRequiredException(); } $request = RestServer::getRequest(); if ($id) { $user = User::fromId($id); // Check ownership if (!$user->is(Auth::user()) && !Auth::isAdmin()) { throw new RestOwnershipRequiredException(Auth::user()->id, 'user = ' . $user->id); } return self::cast($user); } if (!Auth::isAdmin()) { throw new RestAdminRequiredException(); } $users = User::all(); if ($request->filterOp) { $users = static::filter($users, $request->filterOp); } if ($request->updatedSince) { $time = $request->updatedSince; $users = array_filter($users, function ($user) use($time) { return $user->last_activity >= $time; }); } $data = array(); foreach ($users as $user) { $data[] = static::cast($user); } return $data; }
/** * Log message * * @param LogLevels $level The log level * @param string $message The message */ public static function log($level, $message) { if (!is_scalar($message)) { foreach (explode("\n", print_r($message, true)) as $line) { self::log($level, $line); } return; } self::setup(); //TODO: test level if (LogLevels::isValidValue($level) && !array_key_exists($level, self::$levels)) { $level = LogLevels::ERROR; } if ($level == LogLevels::DEBUG) { $stack = debug_backtrace(); while ($stack && array_key_exists('class', $stack[0]) && $stack[0]['class'] == 'Logger') { array_shift($stack); } if ($stack && array_key_exists('function', $stack[0]) && $stack[0]['function']) { $caller = $stack[0]; $s = $caller['file'] . ':' . $caller['line'] . ' '; if (array_key_exists('class', $caller)) { if (!array_key_exists('type', $caller)) { $caller['type'] = ' '; } if ($caller['type'] == '::') { $s .= $caller['class'] . '::'; } else { $s .= '(' . $caller['class'] . ')' . $caller['type']; } } if (in_array($caller['function'], array('__call', '__callStatic'))) { $caller['function'] = $caller['args'][0]; $caller['args'] = $caller['args'][1]; } $args = array(); foreach ($caller['args'] as $arg) { $a = ''; if (is_bool($arg)) { $a = $arg ? '(true)' : '(false)'; } else { if (is_scalar($arg)) { $a = '(' . $arg . ')'; } else { if (is_array($arg)) { $a = array(); foreach ($arg as $k => $v) { $a[] = (is_numeric($k) ? '' : $k . ' => ') . gettype($v) . (is_scalar($v) ? is_bool($v) ? $v ? '(true)' : '(false)' : '(' . $v . ')' : ''); } $a = '(' . implode(', ', $a) . ')'; } } } $args[] = gettype($arg) . $a; } $s .= $caller['function'] . '(' . implode(', ', $args) . ')'; $message = $s . ' ' . $message; } } try { $dbiexception = count(array_filter(debug_backtrace(), function ($t) { return array_key_exists('class', $t) && preg_match('`^DBI.+Exception$`', $t['class']); })); if ($level != LogLevels::DEBUG && !$dbiexception && Auth::isAuthenticated()) { $message = '[user ' . Auth::user()->email . '] ' . $message; } } catch (Exception $e) { } $message = '[' . self::$process . ':' . $level . '] ' . $message; foreach (self::$facilities as $facility) { if (array_key_exists('process', $facility)) { $accepted = array_filter(array_map('trim', preg_split('`[\\s,|]`', $facility['process']))); if (!in_array('*', $accepted) && !in_array(self::$process, $accepted)) { continue; } } if (array_key_exists('level', $facility)) { $max = self::$levels[$facility['level']]; if (self::$levels[$level] > $max) { continue; } } $method = get_called_class() . '::' . $facility['method']; call_user_func($method, $facility, $level, $message); } }
/** * NotesMenu constructor */ public function __construct() { $this->isAuthenticated = Auth::isAuthenticated(); $this->isAuthorized = Auth::isAuthorized(); $this->allRights = Auth::user() && Auth::user()->email != '' && $this->isAuthenticated && $this->isAuthorized; }
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ require_once dirname(__FILE__) . '/library/ODataProducer/Common/ClassAutoLoader.php'; require_once dirname(__FILE__) . '/library/Auth.php'; require_once 'Dispatcher.php'; use ODataProducer\Common\ClassAutoLoader; ClassAutoLoader::register(); /** * Initial entry point for all the request to the library. * * @category ODataPHPProd * @package ODataPHPProd * @author Microsoft Open Technologies, Inc. <*****@*****.**> * @copyright Microsoft Open Technologies, Inc. * @license New BSD license, (http://www.opensource.org/licenses/bsd-license.php) * @version GIT: 1.2 * @link https://github.com/MSOpenTech/odataphpprod */ $auth = new Auth(); //echo $auth->register("testUser", "asdfjkl;12", "leon ho", "1367 East 61st Ave", "604 327 8390", "*****@*****.**"); //$auth->login("testUser", "asdfjkl;12"); //$auth->changePassword("leonHo","", "test"); if ($auth->isAuthenticated()) { $dispatcher = new Dispatcher(); $dispatcher->dispatch(); } else { header("HTTP/1.1 401 Unauthorized"); exit; }
/** * Get current lang code stack * * @return array */ private static function getCodeStack() { if (is_null(self::$code_stack)) { $stack = array(); // Fill stack by order of preference and without duplicates // Auth exception should not stop processing of lang code try { // URL/session given language if (Config::get('lang_url_enabled')) { if (array_key_exists('lang', $_GET) && preg_match('`^[a-z]+(-.+)?$`', $_GET['lang'])) { $code = self::realCode($_GET['lang']); if ($code) { if (isset($_SESSION)) { $_SESSION['lang'] = $code; } if (Config::get('lang_save_url_switch_in_userpref') && Auth::isAuthenticated()) { Auth::user()->lang = $code; Auth::user()->save(); } } } if (isset($_SESSION) && array_key_exists('lang', $_SESSION)) { if (!in_array($_SESSION['lang'], $stack)) { $stack[] = $_SESSION['lang']; } } } // User preference stored language if (Config::get('lang_userpref_enabled') && Auth::isAuthenticated()) { $code = Auth::user()->lang; if ($code && !in_array($code, $stack)) { $stack[] = $code; } } } catch (Exception $e) { } // Browser language if (Config::get('lang_browser_enabled') && array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) { $codes = array(); foreach (array_map('trim', explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $part) { $code = $part; $weight = 1; if (strpos($part, ';') !== false) { $part = array_map('trim', explode(';', $part)); $code = array_shift($part); foreach ($part as $p) { if (preg_match('`^q=([0-9]+\\.[0-9]+)$`', $p, $m)) { $weight = (double) $m[1]; } } } $codes[$code] = $weight; } uasort($codes, function ($a, $b) { return $b > $a ? 1 : ($b < $a ? -1 : 0); }); foreach ($codes as $code => $weight) { $code = self::realCode($code); if ($code && !in_array($code, $stack)) { $stack[] = $code; } } } // Config default language $code = Config::get('default_language'); if ($code) { $code = self::realCode($code); if ($code && !in_array($code, $stack)) { $stack[] = $code; } } // Absolute default if not already present $code = self::realCode('en'); if ($code) { if (!in_array($code, $stack)) { $stack[] = $code; } } else { $stack[] = key(self::getAvailableLanguages()); } // Should not go there ... // Add to cached stack (most significant first) $main = array_shift($stack); self::$code_stack = array('main' => $main, 'fallback' => $stack); } return self::$code_stack; }
/** * Process the request * * @throws lots of various exceptions */ public static function process() { try { @session_start(); // If undergoing maintenance report it as an error if (Config::get('maintenance')) { throw new RestUndergoingMaintenanceException(); } // Split request path to get tokens $path = array(); if (array_key_exists('PATH_INFO', $_SERVER)) { $path = array_filter(explode('/', $_SERVER['PATH_INFO'])); } // Get method from possible headers $method = null; foreach (array('X_HTTP_METHOD_OVERRIDE', 'REQUEST_METHOD') as $k) { if (!array_key_exists($k, $_SERVER)) { continue; } $method = strtolower($_SERVER[$k]); } // Record called method (for log), fail if unknown if (!in_array($method, array('get', 'post', 'put', 'delete'))) { throw new RestMethodNotAllowedException(); } // Get endpoint (first token), fail if none $endpoint = array_shift($path); if (!$endpoint) { throw RestEndpointNotFound(); } // Request data accessor self::$request = new RestRequest($method, $endpoint, $path); // Because php://input can only be read once for PUT requests we rely on a shared getter $input = Request::body(); // Get request content type from possible headers $type = array_key_exists('CONTENT_TYPE', $_SERVER) ? $_SERVER['CONTENT_TYPE'] : null; if (!$type && array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) { $type = $_SERVER['HTTP_CONTENT_TYPE']; } // Parse content type $type_parts = array_map('trim', explode(';', $type)); $type = array_shift($type_parts); self::$request->properties['type'] = $type; $type_properties = array(); foreach ($type_parts as $part) { $part = array_map('trim', explode('=', $part)); if (count($part) == 2) { self::$request->properties[$part[0]] = $part[1]; } } Logger::debug('Got "' . $method . '" request for endpoint "' . $endpoint . '/' . implode('/', $path) . '" with ' . strlen($input) . ' bytes payload'); // Parse body switch ($type) { case 'text/plain': self::$request->rawinput = trim(Utilities::sanitizeInput($input)); break; case 'application/octet-stream': // Don't sanitize binary input ! self::$request->rawinput = $input; break; case 'application/x-www-form-urlencoded': $data = array(); parse_str($input, $data); self::$request->input = (object) Utilities::sanitizeInput($data); break; case 'application/json': default: self::$request->input = json_decode(trim(Utilities::sanitizeInput($input))); } // Get authentication state (fills auth data in relevant classes) Auth::isAuthenticated(); if (Auth::isRemoteApplication()) { // Remote applications must honor ACLs $application = AuthRemote::application(); if (!$application->allowedTo($method, $endpoint)) { throw new RestNotAllowedException(); } } else { if (Auth::isRemoteUser()) { // Nothing peculiar to do } else { if (in_array($method, array('post', 'put', 'delete'))) { // SP or Guest, lets do XSRF check $token_name = 'HTTP_X_SECURITY_TOKEN'; $token = array_key_exists($token_name, $_SERVER) ? $_SERVER[$token_name] : ''; if ($method == 'post' && array_key_exists('security-token', $_POST)) { $token = $_POST['security-token']; } if (!$token || !Utilities::checkSecurityToken($token)) { throw new RestXSRFTokenInvalidException($token); } } } } // JSONP specifics if (array_key_exists('callback', $_GET) && $method != 'get') { throw new RestJSONPonlyGETException(); } // Get response filters foreach ($_GET as $k => $v) { switch ($k) { case 'count': case 'startIndex': if (preg_match('`^[0-9]+$`', $v)) { self::$request->{$k} = (int) $v; } break; case 'format': break; case 'filterOp': if (is_array($v)) { foreach ($v as $p => $f) { self::$request->filterOp[$p] = array(); foreach (array('equals', 'startWith', 'contains', 'present') as $k) { if (array_key_exists($k, $f)) { self::$request->filterOp[$p][$k] = $f[$k]; } } } } break; case 'sortOrder': if (in_array($v, array('ascending', 'descending'))) { self::$request->sortOrder = $v; } break; case 'updatedSince': // updatedSince takes ISO date, relative N days|weeks|months|years format and epoch timestamp (UTC) $updatedSince = null; if (preg_match('`^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(Z|[+-][0-9]{2}:[0-9]{2})$`', $v)) { // ISO date $localetz = new DateTimeZone(Config::get('default_timezone')); $offset = $localetz->getOffset(new DateTime($v)); $updatedSince = strtotime($v) + $offset; } else { if (preg_match('`^([0-9]+)\\s*(hour|day|week|month|year)s?$`', $v, $m)) { // Relative N day|days|week|weeks|month|months|year|years format $updatedSince = strtotime('-' . $m[1] . ' ' . $m[2]); } else { if (preg_match('`^[0-9]+$`', $v)) { $updatedSince = (int) $v; } } } // Epoch timestamp if (!$updatedSince || !is_numeric($updatedSince)) { throw new RestUpdatedSinceBadFormatException($updatedSince); } self::$request->updatedSince = $updatedSince; break; } } $event = new Event('rest_request', self::$request); $data = $event->trigger(function () { $request = RestServer::getRequest(); // Forward to handler, fail if unknown or method not implemented $class = ucfirst($request->endpoint) . 'Endpoint'; if (!file_exists(APPLICATION_BASE . '/classes/endpoints/' . $class . '.class.php') && !file_exists(APPLICATION_BASE . '/classes/core/endpoints/' . $class . '.class.php')) { throw new RestEndpointNotFoundException(); } if (!method_exists($class, $request->method)) { throw new RestMethodNotImplementedException(); } Logger::debug('Forwarding call to ' . $class . '::' . $request->method . '() handler'); return call_user_func_array($class . '::' . $request->method, $request->path); }); Logger::debug('Got data to send back'); // Output data if (array_key_exists('callback', $_GET)) { header('Content-Type: text/javascript'); $callback = preg_replace('`[^a-z0-9_\\.-]`i', '', $_GET['callback']); echo $callback . '(' . json_encode($data) . ');'; exit; } if (array_key_exists('iframe_callback', $_GET)) { header('Content-Type: text/html'); $callback = preg_replace('`[^a-z0-9_\\.-]`i', '', $_GET['iframe_callback']); echo '<html><body><script type="text/javascript">window.parent.' . $callback . '(' . json_encode($data) . ');</script></body></html>'; exit; } header('Content-Type: application/json'); if ($method == 'post' && $data) { RestUtilities::sendResponseCode(201); if (substr($data['path'], 0, 1) != '/') { $data['path'] = '/' . $data['path']; } header('Location: ' . Config::get('application_url') . 'rest.php' . $data['path']); $data = $data['data']; } echo json_encode($data); } catch (Exception $e) { // Return exceptions as HTTP errors $code = $e->getCode(); if ($code < 400 || $code >= 600) { $code = 500; } RestUtilities::sendResponseCode($code); header('Content-Type: application/json'); echo json_encode(array('message' => $e->getMessage(), 'uid' => method_exists($e, 'getUid') ? $e->getUid() : null, 'details' => method_exists($e, 'getDetails') ? $e->getDetails() : null)); } }