public static function get_instance() { if (self::$instance == false) { self::$instance = new Authorization(); } return self::$instance; }
public static function CanEditProblem($user_id, Problems $problem) { if (is_null($problem) || !is_a($problem, "Problems")) { return false; } return Authorization::IsProblemAdmin($user_id, $problem); }
public static function getPanel() { if( !Authorization::isAuthorized() ) return; $panelStyles = API::parseStylesFile(CUSTOMPATH.DS."Global.views"); $paneltpl = $panelStyles["VeronicaAdminPanel"][2]; $menuItemtpl = $panelStyles["VeronicaMenuListItem"][2]; $controllers = Api::getCustom("Controller"); $modeles = Api::getCustom("Model"); $user = Authorization::getCurrentUser(); $userpanel = ViewHandler::wrap("CurrentUser", $user[0]); $paneltpl = str_replace("<? echo \$USERPANEL;?>", $userpanel, $paneltpl); $list = ""; foreach ($controllers as $controller){ if($controller::$inAdminPanel){ $l = str_replace("<? echo \$ADDCLICKHANDLER;?>", "Controller.add('".$controller::$name."');", $menuItemtpl); $l = str_replace("<? echo \$CLICKHANDLER;?>", "Controller.openDashboard('".$controller::$name."');", $l); $l = str_replace("<? echo \$COUNT;?>", "Controller.openDashboard('".$controller::$name."');", $l); $list .= str_replace("<? echo \$ALIAS;?>", $controller::$alias, $l); } } $paneltpl = str_replace("<? echo \$MENULIST;?>", $list, $paneltpl); return $paneltpl; }
public static function configure( $home ){ self::$home = $home; $js = ""; $css = ""; if( Authorization::isAuthorized() ){ $files = API::getFileList( INCLUDEPATH ); $files = array_merge(API::getFileList( PLUGINSPATH ), $files); $pos = array_search("./include/cmf/js/lib.js",$files); unset($files[$pos]); } else{ $files = API::getFileList( INCLUDEPATH,-1 ); $files[] = "./include/cmf/js/lib.js"; $files[] = "./include/cmf/css/cmf.notify.css"; $files[] = "./include/cmf/css/cmf.ui.css"; } rsort($files); foreach ($files as $path) { $ext = pathinfo($path); if( substr($ext['filename'], 0,1) == '_' ) continue; $ext = $ext['extension']; if($ext == "js"){ $js .= str_replace("{PATH}", $path, Storage::get("Template::jsInclude")); }else if($ext == "css") $css .= str_replace("{PATH}", $path, Storage::get("Template::cssInclude")); } self::assign("TITLE", Config::$SiteConf['name']); self::assign("META", Config::$SiteConf['meta']); self::assign("JSINCLUDE", $js); self::assign("CSSINCLUDE", $css); // l(self::$vars); }
public static function init() { if (empty(self::$obj)) { self::$obj = new Authorization(); } return self::$obj; }
/** * Handles the requests for post() and get() * * @param $name * @param $arguments */ public static function __callStatic($name, $arguments) { $response = static::_transfer($name, $arguments); if ($response && $name != 'delete') { $result = static::_reponse($response); if ($result) { if (is_object($result) || !isset($result['error'])) { return $result; } else { // Expired token ? if (isset($result['error']['message']) && $result['error']['message'] == Auth::$_errors['oAuthTokenExpired']) { if (isset($arguments[2])) { Authorization::oAuthRefreshToken($arguments[2], 'updateSession', 'force'); call_user_func(array('Rest', $name), $arguments); } else { return compact('result', 'name', 'arguments', 'response'); } } else { if (isset($result['error']['message']) && $result['error']['message'] != 'Forbidden' && $result['error']['message'] != 'Not Found') { return compact('result', 'name', 'arguments', 'response'); } } } } else { return compact('result', 'name', 'arguments', 'response'); } } else { if ($name != 'delete') { return compact('result', 'name', 'arguments', 'response'); } } }
public static function Insert($data, $settings, $marathon, $campaign, $database) { if (!Authorization::IsAuthorized($settings)) { return new ZdpArrayObject(['error' => 'You are not authorized to perform this action.']); } $playerID; $gameID; $scheduleStartTime; $scheduleEndTime; $scheduleUnlockAmount; $error = false; $errorMessage; if (array_key_exists('PlayerID', $data)) { $playerID = $data['PlayerID']; } else { $error = true; $errorMessage = 'No player id was provided.'; } if (array_key_exists('GameID', $data)) { $gameID = $data['GameID']; } else { $error = true; $errorMessage = 'No game id was provided.'; } if (array_key_exists('StartTime', $data)) { $scheduleStartTime = $data['StartTime']; } else { $error = true; $errorMessage = 'No start time was provided.'; } if (array_key_exists('EndTime', $data)) { $scheduleEndTime = $data['EndTime']; } else { $error = true; $errorMessage = 'No end time was provided.'; } if (array_key_exists('UnlockAmount', $data)) { $scheduleUnlockAmount = $data['UnlockAmount']; } else { $error = true; $errorMessage = 'No unlock amount was provided.'; } if ($database instanceof ZdpArrayObject) { $error = true; $errorMessage = $database['error']; } if (!$error) { $sql = 'CALL sp_insert_schedule (:game_id, :campaign_id, :player_id, :schedule_endtime, :schedule_starttime, :schedule_unlockamount)'; $statement = $database->prepare($sql); if ($statement->execute([':game_id' => $gameID, ':campaign_id' => $campaign, ':player_id' => $playerID, ':schedule_starttime' => $scheduleStartTime, ':schedule_endtime' => $scheduleEndTime, ':schedule_unlockamount' => $scheduleUnlockAmount])) { $schedules = $statement->fetchAll(PDO::FETCH_ASSOC); $output = new ZdpArrayObject(['result' => new ZdpArrayObject(['schedule' => $schedules])]); } else { $output = new ZdpArrayObject(['error' => $statement->errorInfo()]); } } else { $output = new ZdpArrayObject(['error' => $errorMessage]); } return $output; }
public static function getInstance() { if (null === self::$_instance) { self::$_instance = new self(); } return self::$_instance; }
public function editCategory($id) { if (Authorization::Authorize('Admin')) { $this->view->category = $this->model->getCategory(); // viet code xy lu o day $this->data = array(); $this->view->title = 'Edit Category'; $this->view->cat = $this->model->showCatById($id); if (isset($_POST['submit'])) { if (empty($_POST['catname'])) { $this->view->msg = "Vui lòng nhập tên Category"; $this->view->renderAdmin('category/editcategory'); } else { $this->data['catname'] = mysqli_real_escape_string($this->model->connect, $_POST['catname']); $this->data['parent'] = $_POST['category']; if ($this->model->editCat($this->data, $id) == true) { $this->view->redirect('listcategory'); } else { $this->view->msg = "Edit category faild"; $this->view->renderAdmin('category/editcategory'); } } } else { $this->view->renderAdmin("category/editcategory"); } } else { $this->view->render("user/index"); } }
public static function Insert($data, $settings, $marathon, $campaign, $database) { if (!Authorization::IsAuthorized($settings)) { return new ZdpArrayObject(['error' => 'You are not authorized to perform this action.']); } $playerName; $error = false; if (array_key_exists('name', $POST) && trim($_POST['name']) != '') { $playerName = $_POST['name']; } else { $error = true; $errorMessage = 'No player name was provided.'; } if ($database instanceof ZdpArrayObject) { $error = true; $errorMessage = $database['error']; } if (!$error) { $sql = 'CALL sp_insert_player (:campaign_id, :marathon_id, :player_name)'; $statement = $database->prepare($sql); if ($statement->execute([':marathon_id' => $marathon, ':campaign_id' => $campaign, ':player_name' => $playerName])) { $players = $statement->fetchAll(PDO::FETCH_ASSOC); $output = new ZdpArrayObject(['result' => new ZdpArrayObject(['player' => $players])]); } else { $output = new ZdpArrayObject(['error' => $statement->errorInfo()]); } } else { $output = new ZdpArrayObject(['error' => $errorMessage]); } return $output; }
/** * Validate requests for grader apis * * @param Request $r * @throws ForbiddenAccessException */ private static function validateRequest(Request $r) { self::authenticateRequest($r); if (!Authorization::IsSystemAdmin($r['current_user_id'])) { throw new ForbiddenAccessException(); } }
/** * @return retorna un peticion solicitada */ public static function run(Request $peticion) { $controller = $peticion->getControlador() . "Controller"; $rutaControlador = ROOT . "controllers" . DS . $controller . ".php"; $metodo = $peticion->getMetodo(); $args = $peticion->getArgs(); //exit; if (is_readable($rutaControlador)) { require_once $rutaControlador; $Controlador = new $controller(); if (is_callable(array($controller, $metodo))) { $metodo = $peticion->getMetodo(); } else { $metodo = "index"; } if ($metodo == 'login') { # code... } else { Authorization::Logged(); } if (isset($args)) { call_user_func_array(array($Controlador, $metodo), $args); } else { call_user_func(array($Controlador, $metodo)); } } else { throw new Exception("Controlador no encontrado "); } }
/** * run ejecuta clase Request * permite llamar una funcion sin necesidad de instanciar la clase * @param string $peticion parametro que se recibe de Request * @var string controller almacena controlador * @var string rutaControlador guarda ruta del controlador * @var string $metodo invoca a la funcion getMetodo de request * @var string $args invoca a la funcion getArgs de request * */ public static function run(Request $peticion) { $controller = $peticion->getControlador() . 'Controller'; $rutaControlador = ROOT . 'controllers' . DS . $controller . '.php'; $metodo = $peticion->getMetodo(); $args = $peticion->getArgs(); if (is_readable($rutaControlador)) { include_once $rutaControlador; $controlador = new $controller(); if (is_callable(array($controller, $metodo))) { $metodo = $peticion->getMetodo(); } else { $metodo = 'index'; } if ($metodo == 'login') { } else { Authorization::logged(); } if (isset($args)) { call_user_func_array(array($controlador, $metodo), $args); } else { call_user_func_array(array($controller, $metodo)); } } else { throw new Exception("Controlador no encontrado"); } }
function approveUser($login, $pass, $createIP) { if ($this->checkPass($pass, $login)) { #ПРОВЕРЯЕМ ПРАВИЛЬНОСТЬ ПАРОЛЯ $ip = 0; $time = time() + 60 * 2; $this->hash = md5($this->generateCode(10)); if ($createIP) { $ip = ip2long($_SERVER['REMOTE_ADDR']); } $this->prepareQuery("INSERT INTO sessions SET user_id=:id, time=:time, hash=:hash, ip=:ip"); /*$this->prepareQuery("UPDATE user SET hash=:hash, ip=:ip WHERE id=:id");*/ $this->query->bindParam(':hash', $this->hash); $this->query->bindParam(':ip', $ip); $this->query->bindParam(':id', $this->thisUser['user_id']); $this->query->bindParam(':time', $time); // Два часа! $this->executeQuery_Simple(); $this->createCookie(); // Создаем куки /* $this->deleteOldSessions(); // Удаляем устаревшие сессии*/ return true; } else { $this->errors['password_login'] = '******'; // class из bootstrap Authorization::logOut(); return false; } }
public function delete_session() { $user_id = (int) $_COOKIE['user_id']; $this->prepare("DELETE FROM sessions WHERE user_id=:id"); $this->query->bindParam(':id', $user_id, PDO::PARAM_INT); $this->execute_simple(); Authorization::delete_cookie(); }
static function Instance() { if (!isset(self::$mrInstance)) { $class_name = __CLASS__; self::$mrInstance = new $class_name(); } return self::$mrInstance; }
/** * Display the specified resource. * * @param int $hash * @return Response */ public function index($hash) { if ($hash) { $wishes = $this->service->getWishesForUser($hash); } else { $wishes = $this->service->getWishesForUser(\Authorization::user()->hash); } return $this->returnWishlist($wishes); }
public function beforeroute() { parent::beforeroute(); if (!$this->setAuthorizedUserAndMenu()) { $this->notAuthorized(); } else { $this->list_perpage = $this->fw->get('account.perpage'); // Проверяем существуют ли кастомные маршруты для ЛК $this->fw->set('use_app_routes', \helpers\BackendRoutes::exists()); } }
public static function makeAuth($args) { $md5pass = md5($args[1].Config::$Security['passwordsalt']); $table = Config::$DBConf['prefix'].Authorization::$table; $row = DB::getRow("Select * From $table Where `login`='$args[0]' and `password`='$md5pass'"); if($row != NULL && $row['status'] == '0' ){ self::$user = $row; DB::exec( "UPDATE $table SET `status` = 1 WHERE `login` = '".$args[0]."'" ); setcookie("user_name",$row['name'], time()+60*60*24*365); setcookie("user_id",$row['id'], time()+60*60*24*365); return $row['category']; }else return NULL; }
protected function runParentTransaction($amount = 10.0) { self::authorizeFromEnv(); $transaction = new Authorization(); $transaction->money->setAmount($amount); $transaction->money->setCurrency('EUR'); $transaction->setDescription('test'); $transaction->setTrackingId('my_custom_variable'); $transaction->card->setCardNumber('4200000000000000'); $transaction->card->setCardHolder('John Doe'); $transaction->card->setCardExpMonth(1); $transaction->card->setCardExpYear(2030); $transaction->card->setCardCvc('123'); $transaction->customer->setFirstName('John'); $transaction->customer->setLastName('Doe'); $transaction->customer->setCountry('LV'); $transaction->customer->setAddress('Demo str 12'); $transaction->customer->setCity('Riga'); $transaction->customer->setZip('LV-1082'); $transaction->customer->setIp('127.0.0.1'); $transaction->customer->setEmail('*****@*****.**'); return $transaction->submit(); }
static function Start($auth = []) { $called_class = get_called_class(); if (count($auth)) { $where = []; foreach ($auth as $k => $v) { $where[] = "`" . es($k) . "` = '" . es($v) . "'"; } $res = q("\n\t\t\t\tSELECT `access`" . (count($called_class::$datas) ? ',`' . implode('`,`', $called_class::$datas) . '`' : '') . "\n\t\t\t\tFROM `fw_users`\n\t\t\t\tWHERE " . implode(" AND ", $where) . "\n\t\t\t"); if (!$res->num_rows) { Authorization::logout(); redirect('/'); } $row = $res->fetch_assoc(); if ($row['access'] != 1) { Authorization::logout(); $_SESSION['error'] = 'no-access'; redirect('/'); } foreach ($called_class::$datas as $k => $v) { $called_class::${$v} = $row[$v]; // unset($row[$v]); -- Раскомментировать после обновления функционала на сайте } if (count($row)) { self::$data = $row; } } elseif (isset($_COOKIE['autologinid'], $_COOKIE['autologinhash'])) { $auth = new Authorization(); if (!$auth->authByHash($_COOKIE['autologinid'], $_COOKIE['autologinhash'])) { Authorization::logout(); redirect('/'); } } if (!empty(self::$data['id']) && !empty(self::$autoupdate)) { q("\n\t\t\t\tUPDATE `fw_users` SET\n\t\t\t\t`browser` = '" . (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '') . "',\n\t\t\t\t`ip` = '" . es($_SERVER['REMOTE_ADDR']) . "'\n\t\t\t\tWHERE `id` = " . (int) self::$data['id'] . "\n\t\t\t"); } }
public function index() { $this->view->title = "Dashboard"; if (Authorization::Authorize('Admin')) { $this->view->title = "Dashboard"; $this->view->cat = $this->model->getCat(); $this->view->post = $this->model->getPost(); $this->view->comment = $this->model->getComment(); $this->view->user = $this->model->getUser(); $this->view->page = $this->model->getPage(); $this->view->renderAdmin("dashboard/index"); } else { $this->view->render("user/index"); } }
public function deleteSite(&$markerSite) { $distribution = Distribution::find($markerSite->distribution); Authorization::where('atlas_id', '=', $markerSite->id)->delete(); Log::info("Deleted authorization " . $markerSite->id . " from " . $_SERVER['REMOTE_ADDR']); Log::info("Deleting Site" . $markerSite->id . " from " . $_SERVER['REMOTE_ADDR']); $markerSite->delete(); Log::info("Deleted Site"); Log::info("Distribution name=" . $distribution->name . " id=" . $distribution->id . " standard=" . $distribution->is_standard); if ($distribution && $distribution->isNonStandard()) { Log::info("Deleting distribution " . $distribution->id . " from " . $_SERVER['REMOTE_ADDR']); $distribution->delete(); Log::info("Deleted Distribution"); } }
public function action_jwks() { try { $response = array('keys' => array("e" => "AQAB", "n" => "kWp2zRA23Z3vTL4uoe8kTFptxBVFunIoP4t_8TDYJrOb7D1iZNDXVeEsYKp6ppmrTZDAgd-cNOTKLd4M39WJc5FN0maTAVKJc7NxklDeKc4dMe1BGvTZNG4MpWBo-taKULlYUu0ltYJuLzOjIrTHfarucrGoRWqM0sl3z2-fv9k", "kty" => "RSA", "kid" => "1")); } catch (League\OAuth2\Server\Exception\ClientException $e) { // Throw an exception because there was a problem with the client's request $response = array('error' => $this->authserver->getExceptionType($e->getCode()), 'error_description' => $e->getMessage()); // Set the correct header header($this->authserver->getExceptionHttpHeaders($this->authserver->getExceptionType($e->getCode()))[0]); } catch (Exception $e) { // Throw an error when a non-library specific exception has been thrown $response = array('error' => 'undefined_error', 'error_description' => $e->getMessage()); } header('Content-type: application/json'); echo json_encode($response); }
/** * Validates that group alias and contest alias do exist * * @param Request $r * @throws InvalidDatabaseOperationException * @throws InvalidParameterException */ private static function validateGroupScoreboardAndContest(Request $r) { self::validateGroupScoreboard($r); Validators::isValidAlias($r["contest_alias"], "contest_alias"); try { $r["contest"] = ContestsDAO::getByAlias($r["contest_alias"]); } catch (Exception $ex) { throw new InvalidDatabaseOperationException($ex); } if (is_null($r["contest"])) { throw new InvalidParameterException("parameterNotFound", "Contest"); } if ($r["contest"]->public == 0 && !Authorization::IsContestAdmin($r["current_user_id"], $r["contest"])) { throw new ForbiddenAccessException(); } }
public function store(Request $request) { $file = $request->file('upload'); if (!$request->hasFile('upload') || !$request->has('type')) { throw new BadRequestHttpException(); } $unique = \Input::get('unique'); if (!$unique) { $unique = true; } $uploadType = ['type' => \Input::get('type'), 'unique' => $unique]; $user = \Authorization::user(); $model = $this->service->createUpload($user, $file, \Authorization::user(), $uploadType); $model = $this->returnUploadModel($model); return $model; }
/** * zobrazi zoznam vsetkych * @global array $ALIEN */ public static function showPermissionsList() { if (!Authorization::getCurrentUser()->hasPermission(38)) { new Notification("Prístup zamietnutý.", "error"); header("Location: ?page=home", false, 301); ob_end_flush(); exit; } global $ALIEN; $ALIEN['HEADER'] = 'Zoznam existujúcich oprávnení'; $limit = sizeof(Authorization::$Permissions); for ($i = 1; $i <= $limit; $i++) { $permission = new Permission(Authorization::$Permissions[$i]['label']); echo '<div class="item"><img src="images/icons/shield.png"> ID: ' . $permission->getId() . ' | <strong>' . $permission->getLabel() . '</strong> | ' . $permission->getDescription() . '</div>'; } }
public static function Insert($data, $settings, $marathon, $campaign, $database) { if (!Authorization::IsAuthorized($settings)) { return new ZdpArrayObject(['error' => 'You are not authorized to perform this action.']); } $fileDefinitionLimit; $fileDefinitionName; $gameId; $error = false; $errorMessage; $output; if (array_key_exists('Limit', $data)) { $fileDefinitionLimit = $data['Limit']; } else { $error = true; $errorMessage = 'No limit was provided.'; } if (array_key_exists('Name', $data)) { $fileDefinitionName = $data['Name']; } else { $error = true; $errorMessage = 'No name was provided.'; } if (array_key_exists('GameId', $data)) { $gameId = $data['GameId']; } else { $error = true; $errorMessage = 'No game Id was provided.'; } if ($database instanceof ZdpArrayObject) { $error = true; $errorMessage = $database['error']; } if (!$error) { $sql = 'CALL sp_insert_filedefinition (:campaign_id, :marathon_id, :game_id, :filedefinition_limit, :filedefinition_name)'; $statement = $database->prepare($sql); if ($statement->execute([':campaign_id' => $campaign, ':marathon_id' => $marathon, ':game_id' => $gameId, ':filedefinition_limit' => $fileDefinitionLimit, ':filedefinition_name' => $fileDefinitionName])) { $return = $statement->fetchAll(PDO::FETCH_ASSOC)[0]['Id']; $output = new ZdpArrayObject(['result' => new ZdpArrayObject(['fileDefinitionId' => $return])]); } else { $output = new ZdpArrayObject(['error' => $statement->errorInfo()]); } } else { $output = new ZdpArrayObject(['error' => $errorMessage]); } return $output; }
/** * Execute the console command. * * @return mixed */ public function handle() { $hash = $this->argument('hash'); $key = $this->argument('key'); try { \Authorizer::validateAccessToken(false, $key); $resourceOwnerId = \Authorizer::getResourceOwnerId(); $user = \Authorization::loginUsingId($resourceOwnerId); if ($user->hash === $hash) { $this->info('Authenticated'); } else { throw new \Exception('User hash does not match auth key'); } } catch (OAuthException $e) { throw new \Exception('Authentication error: invalid authentication key'); } }
public function run() { // проверяем ридирект с ошибки $rdStatus = isset($_SERVER['REDIRECT_STATUS']) ? $_SERVER['REDIRECT_STATUS'] : 0; if (array_key_exists($rdStatus, $this->httpError)) { $this->makeError("[" . __CLASS__ . "] " . $this->httpError[$rdStatus]); } // проверяем авторизацию if (!Authorization::init()->isAuth()) { $this->makeError("[" . __CLASS__ . "] API доступно только авторизованным пользователям!"); } $action = $this->getParam($this->actionName); if (!array_key_exists($action, $this->api)) { $this->makeError("[" . __CLASS__ . "] не найдена комманда " . $action . '!'); } $metod = $this->api[$action]['metod']; $param = array(); switch ($action) { // дополнительная проверка \ обработка параметров для комманд case 'get': $filter = array(); foreach ($this->api[$action]['param'] as $val) { $paramElem = $this->getParam($val, false); if ($paramElem !== false) { $filter[$val] = $paramElem; } } $param[] = $filter; break; default: foreach ($this->api[$action]['param'] as $val) { $param[] = $this->getParam($val); } break; } // создаем экземпляр класса try { $obj = new UserModel(DB::GetDBH()); $userObject = call_user_func_array(array($obj, $metod), $param); } catch (Exception $e) { $this->makeError($e->getMessage()); } echo $this->outputFormated($userObject); return; }