/** * Execute the deletion handling * * @return boolean Success/failure of delete */ public function execute() { $args = $this->getArguments(); $name = $this->getName(); $model = g::buildModel('delete', $name, $args); return $this->getDb()->delete($model); }
/** * Check to see if a user is in a group * * @param integer $userId User ID * @param integer $groupId Group ID * @param OutputInterface $output Output object */ public function inGroup($userId, $groupId, $output) { $group = Gatekeeper::findGroupById($groupId); $result = Gatekeeper::findUserById($userId)->inGroup($groupId); $output->writeln($result === true ? "User in group '" . $group->description . "'." : "User <options=bold>not</options=bold> in group '" . $group->description . "'."); return $result; }
public function loadPost($id) { $stmt = $this->pdo->prepare("SELECT text FROM postText WHERE id = :id"); $stmt->execute(['id' => $id]); $text = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt = $this->pdo->prepare("SELECT title, bgURL, authorID FROM posts WHERE postID = :id"); $stmt->execute(['id' => $id]); $details = $stmt->fetch(\PDO::FETCH_ASSOC); $authorName = ['authorName' => Gatekeeper::findUserById($details['authorID'])->firstName . " " . Gatekeeper::findUserById($details['authorID'])->lastName]; return array_merge($details, $text, $authorName); }
/** * Handle the "find by" when multiple are requested * * @param string $name Name of function called * @param array $args Arguments list * @param array $matches Matches from regex * @return \Modler\Collection collection */ public function handleFindByMultiple($name, $args, $matches) { $data = isset($args[0]) ? $args[0] : array(); $model = substr($name, 0, strlen($name) - 1); $collectionNs = '\\Psecio\\Gatekeeper\\' . $model . 'Collection'; if (!class_exists($collectionNs)) { throw new \Psecio\Gatekepper\Exception\ModelNotFoundException('Collection type ' . $model . ' could not be found'); } $model = g::modelFactory($model . 'Model'); $collection = new $collectionNs($this->getDb()); $collection = $this->getDb()->find($model, $data, true); return $collection; }
public function CloneUser($user, $data) { $ds = Gatekeeper::getDatasource(); $newUser = new \Psecio\Gatekeeper\UserModel($ds, $data); $result = $newUser->save(); if ($result == false) { return false; } // Get the user's groups and add foreach ($user->groups as $group) { $newUser->addGroup($group); } // Get the user's permissions and add foreach ($user->permissions as $permission) { $newUser->addPermission($permission); } return true; }
public function addUser(array $options, $output) { $user = Gatekeeper::findUserById($options['userid']); $ds = Gatekeeper::getDatasource(); if (isset($options['permission'])) { // If it's a permission link it to the user $perm = new \Psecio\Gatekeeper\UserPermissionModel($ds, array('userId' => $user->id, 'permissionId' => $options['permission'])); if ($ds->save($perm) === true) { $output->writeln('Permission linked to user successfully'); } } elseif (isset($options['group'])) { // If it's a group link it to the user $group = new \Psecio\Gatekeeper\UserGroupModel($ds, array('userId' => $user->id, 'groupId' => $options['group'])); if ($ds->save($group) === true) { $output->writeln('Group linked to user successfully'); } } }
/** * Execute the evaluation for the restriction * * @return boolean Success/fail of evaluation */ public function evaluate() { $config = $this->getConfig(); $throttle = \Psecio\Gatekeeper\Gatekeeper::getUserThrottle($config['userId']); $throttle->updateAttempts(); $this->model = $throttle; // See if they're blocked if ($throttle->status === \Psecio\Gatekeeper\ThrottleModel::STATUS_BLOCKED) { $result = $throttle->checkTimeout(); if ($result === false) { return false; } } else { $result = $throttle->checkAttempts(); if ($result === false) { return false; } } return true; }
/** * @auth-groups users */ public function saveAction() { if (!empty($_POST['password_new'])) { try { v::length(6)->check($_POST['password_new']); } catch (ValidationException $e) { $this->flasher->error('Please make sure new password is longer than 6 characters!'); } if ($_POST['password_new'] !== $_POST['password_new_confirm']) { $this->flasher->error('New password fields were not identical!'); } if (!Gatekeeper::authenticate(['username' => $this->user->username, 'password' => $_POST['password_old']])) { $this->flasher->error('Invalid password. Changes ignored.'); } else { $this->user->password = $_POST['password_new']; $this->user->save(); $this->flasher->success('Password updated!'); } } if ($_POST['firstname'] != '-') { try { v::alnum(' ')->check($_POST['firstname']); $this->user->firstName = $_POST['firstname']; $this->user->save(); $this->flasher->success('First name changed.'); } catch (ValidationException $e) { $this->flasher->error('Name contains invalid characters. ' . $e->getMainMessage()); } } if ($_POST['lastname'] != '-') { try { v::alnum(' ')->check($_POST['lastname']); $this->user->lastName = $_POST['lastname']; $this->user->save(); $this->flasher->success('Last name changed.'); } catch (ValidationException $e) { $this->flasher->error('Last name contains invalid characters. ' . $e->getMainMessage()); } } $this->redirect('/account'); }
public function processResetPassAction() { /** @var UserModel $user */ $user = Gatekeeper::findUserByEmail($_SESSION['user']); if (!$user) { $this->flasher->error('Password reset session expired'); unset($_SESSION['user']); $this->redirect('/'); } if ($_POST['password'] == $_POST['password_confirm']) { $user->password = $_POST['password']; if ($user->save()) { $this->flasher->success('Successfully changed password!'); } else { $this->flasher->error('Could not update password :('); } $this->redirect('/'); } }
/** * Verify the token if it exists * Removes the old token and sets up a new one if valid * * @param \Psecio\Gatekeeper\AuthTokenModel $token Token model instance * @return boolean Pass/fail result of the validation */ public function verify(\Psecio\Gatekeeper\AuthTokenModel $token = null) { if (!isset($this->data[$this->tokenName])) { return false; } if ($token === null) { $tokenParts = explode(':', $this->data[$this->tokenName]); $token = $this->getById($tokenParts[0]); } if ($token === false) { return false; } $user = $token->user; $userToken = $token->token; // Remove the token (a new one will be made later) $this->datasource->delete($token); if (\Psecio\Gatekeeper\Gatekeeper::hash_equals($this->data[$this->tokenName], $token->id . ':' . hash('sha256', $userToken)) === false) { return false; } $this->setup($user); return $user; }
/** * Register (start) the service provider * Sets up the Gatekeeper instance with init() call */ public function register() { $config = array('username' => env('GATEKEEPER_USER'), 'password' => env('GATEKEEPER_PASS'), 'host' => env('GATEKEEPER_HOST'), 'name' => env('GATEKEEPER_DATABASE')); Gatekeeper::init(null, $config); }
/** * Validate a user against the given credentials. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(Authenticatable $user, array $credentials) { $username = $user->getAuthIdentifier(); $credentials = ['username' => $username, 'password' => $credentials['password']]; return Gatekeeper::authenticate($credentials); }
public function deleteGroupAction(int $id) { if (Gatekeeper::deleteGroupById($id)) { $this->flasher->success('Group deleted'); } else { $this->flasher->error('Group not deleted.'); if ($this->site['debug']) { $this->flasher->error(Gatekeeper::getLastError()); } } $this->redirect('/users/groups'); }
}); $app->delete('/permissions', function () use($app, $view) { $groupName = $app->request->post('groupName'); $permId = $app->request->post('permissionId'); $group = g::findGroupByName($groupName); $group->removePermission($permId); echo $view->render('group/permissions.php'); }); $app->post('/users', function () use($app, $view) { $idList = $app->request->post('ids'); $groupName = $app->request->post('name'); $group = g::findGroupByName($groupName); foreach ($idList as $userId) { $group->addUser($userId); } // Remove any not in the list foreach ($group->users as $user) { if (!in_array($user->id, $idList)) { $group->removeUser($user->id); } } echo $view->render('group/users.php'); }); $app->delete('/users', function () use($app, $view) { $groupName = $app->request->post('groupName'); $userId = $app->request->post('userId'); $group = g::findGroupByName($groupName); $group->removeUser($userId); echo $view->render('group/users.php'); }); });
if (ACCEPT_JSON) { $app->response->setStatus(404); } $data = array('message' => $e->getMessage()); echo $view->render('error/index.php', $data); } }); $app->get('/delete/:userId', function ($userId) use($app, $view) { $data = array(); try { $user = g::findUserById($userId); $ds = g::getDatasource(); if ($ds->delete($user) === false) { throw new \Exception('Error deleting user.'); } echo $view->render('users/delete.php', $data); } catch (\Exception $e) { if (ACCEPT_JSON) { $app->response->setStatus(404); } $data = array('message' => $e->getMessage()); echo $view->render('error/index.php', $data); } }); $app->get('/status/:userId', function ($userId) use($app, $view) { $user = g::findUserById($userId); $user->status === 'active' ? $user->deactivate() : $user->activate(); $result = array('status' => $user->status, 'username' => $user->username); echo json_encode($result); }); });
/** * Evaluate the policy (found by name) against the data provided * * @param string $name Name of the policy * @param mixed $data Data to use in evaluation (single object or array) * @return boolean Pass/fail status of evaluation */ public static function evaluatePolicy($name, $data) { // See if it's a closure policy first if (array_key_exists($name, self::$policies)) { $policy = self::$policies[$name]; $result = $policy($data); return !is_bool($result) ? false : $result; } else { $policy = Gatekeeper::findPolicyByName($name); return $policy->evaluate($data); } }
/** * Set the "remember me" token value * * @param string $value Token value */ public function setRememberToken($value) { $tokens = $this->model->authTokens; if (isset($tokens[0])) { $token = $tokens[0]; $token->token($value); $token->save(); } else { // No token found, make one $token = new AuthTokenModel(Gatekeeper::getDatasource(), ['token' => $value, 'user_id' => $this->model->id, 'expires' => strtotime('+14 days')]); $token->save(); } }
$app->get('/', function () use($app, $view) { $permissions = g::findPermissions(); $data = ['permissions' => $permissions->toArray(true)]; $view->render('permissions/index.php', $data); }); $app->get('/edit/:permId', function ($permId) use($app, $view) { $permission = g::findPermissionById($permId); $data = ['permission' => $permission->toArray()]; $view->render('permissions/edit.php', $data); }); $app->post('/edit/:permId', function ($permId) use($app, $view) { $permission = g::findPermissionById($permId); $data = ['success' => true]; $post = $app->request->post(); $ds = g::getDatasource(); $permission->name = $post['name']; $permission->description = $post['description']; try { $ds->save($permission); } catch (\Exception $e) { $data['success'] = false; } $data['permission'] = $permission->toArray(); $view->render('permissions/edit.php', $data); }); $app->get('/view/:name', function ($perm) use($app, $view) { $permission = is_numeric($perm) ? g::findPermissionById($perm) : g::findPermissionByName($perm); $data = ['permission' => $permission->toArray(), 'groups' => $permission->groups->toArray(true)]; $view->render('permissions/view.php', $data); }); });
/** * Show the listing of permission * * @param array $options Command line options * @param OutputInterface $output Output interface object */ public function showPermissions(array $options = array(), $output) { $params = array(); if (!empty($options['id'])) { $params['id'] = $options['id']; } $columns = array('name' => 'Name', 'description' => 'Description', 'created' => 'Date Created', 'updated' => 'Date Updated', 'id' => 'ID'); $groups = Gatekeeper::findPermissions($params); $this->buildTable($columns, $groups->toArray(true), $output); }
/** * Validate a user against the given credentials. * * @param \Illuminate\Auth\UserInterface $user * @param array $credentials * @return bool */ public function validateCredentials(\Illuminate\Auth\UserInterface $user, array $credentials) { return Gatekeeper::authenticate($credentials); }
public function register($credentials) { return Gatekeeper::register($credentials); }
<?php use Pimple\Container; require_once '../vendor/autoload.php'; // Custom autoloader spl_autoload_register(function ($class) { $path = __DIR__ . '/lib/' . str_replace('\\', '/', $class) . '.php'; if (is_file($path)) { require_once $path; } }); session_start(); $app = new \Slim\Slim(); \Psecio\Gatekeeper\Gatekeeper::init('../'); $config = \Psecio\Gatekeeper\Gatekeeper::getConfig(); $app->config(array('view' => new \GatekeeperUI\View\TemplateView(), 'templates.path' => '../templates', 'debug' => true)); $app->contentType('text/html; charset=utf-8'); define('ACCEPT_JSON', strstr($app->request->headers->get('Accept'), 'application/json') !== false); $view = $app->view(); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); $view->parserOptions = array('debug' => true); $di = new Container(); $di['db'] = function () { $dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['name'] . ';charset=UTF8'; return new \PDO($dsn, $config['username'], $config['password']); }; $app->di = $di;
use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; use Monolog\ErrorHandler; use Monolog\Handler\BrowserConsoleHandler; use Monolog\Handler\StreamHandler; use Psecio\Gatekeeper\Gatekeeper; use SitePoint\Rauth; use Tamtamchik\SimpleFlash\Flash; use Tamtamchik\SimpleFlash\TemplateFactory; use Tamtamchik\SimpleFlash\Templates; use Psr\Log\LoggerInterface as Logger; Gatekeeper::init(__DIR__ . '/../../'); Gatekeeper::disableThrottle(); $user = null; if (isset($_SESSION['user'])) { $user = Gatekeeper::findUserByUsername($_SESSION['user']); if (!$user) { session_destroy(); unset($_SESSION['user']); header('Location: /'); die; } } if (getenv('INTL') == 'true') { $language = getenv('INTL_LANG'); putenv("LANGUAGE=" . $language); setlocale(LC_ALL, $language); $domain = "messages"; // which language file to use $localeFolder = getenv('LOCALE_FOLDER'); if (strpos($localeFolder, 'ROOT/') !== FALSE) {
/** * Save the current model instance (gets datasource and calls save) * * @return boolean Success/fail result of save */ public function save() { $ds = \Psecio\Gatekeeper\Gatekeeper::getDatasource(); return $ds->save($this); }