/** * Returns a JSON error output * * @param Instance of Slim * @return string */ public static function authentication(Slim $app) { $app->response->headers->set('Content-Type', 'application/json'); $token = $app->request->headers->get('Authorization'); Config::loadenv(); $key = getenv('jwt_key'); $algorithm = array('HS256'); if (!$token) { $app->halt(401, json_encode(['status' => 401, 'message' => 'You need a token to perform this action!'])); } try { $decode_jwt = JWT::decode($token, $key, $algorithm); } catch (Exception $e) { $app->halt(400, json_encode(['status' => 400, 'message' => 'The token supplied is invalid!.'])); } return $decode_jwt->user; }
/** * Constructor * * @param \Slim\Slim $app Slim app reference */ public function __construct(\Slim\Slim $app) { $this->app = $app; $this->app->notFound(function () use($app) { $data = array('error' => array('message' => 'Invalid route')); $app->contentType('application/json'); $app->halt(400, json_encode($data)); }); }
/** * This methods will be called at application startup * @param $appInstance * @return void * @throws \Exception */ public static function addRouteDefinitions(Slim $appInstance) { $appInstance->map('/protected-storage/:inst/:id/:accessMethod/:path+', function ($inst, $id, $accessMethod, $path) use($appInstance) { if (!in_array($accessMethod, cProtectedStorage::$allowedAccessMethods, true)) { $appInstance->halt(400, 'Invalid request'); } $fileName = array_pop($path); $rel = ''; foreach ($path as $value) { $rel .= $value . '/'; } $rel .= $fileName; $user = null; if ($accessMethod === 'private') { try { $user = new MembersAuth(); $user->isUserLoggedIn(); } catch (LoginExceptions $e) { $appInstance->halt(401, 'Unauthorized'); } } $fullPath = $inst . '/' . $id . '/' . $accessMethod . '/' . $rel; $controller = new cProtectedStorage($inst, $id, $accessMethod, $rel); if ($controller->isCorrectPath($fullPath)) { $appInstance->etag(md5($fullPath)); $appInstance->expires('+1 week'); $headers = $controller->outputFile(); if (array_key_exists('download', $_REQUEST)) { $headers['Content-Type'] = 'application/octet-stream'; } foreach ($headers as $key => $value) { $appInstance->response->headers->set($key, $value); } } else { $appInstance->notFound(); } })->via('GET', 'POST'); }
/** * Disable issued token to a user * * @param int $user_id ID of a user * @param Slim $app * @return string */ public static function logout($user_id, Slim $app) { $app->response->headers->set('Content-Type', 'application/json'); try { $user = User::find($user_id); } catch (RecordNotFoundException $e) { $app->halt(404, json_encode(['message' => 'Not Registered'])); } if (Setup::unsetToken($user) === 1) { return json_encode(['message' => 'Logged out']); } else { $app->halt3(503); } }
/** * Verify a resource owner * * @param $id * @param Slim $app * @return bool */ public static function grantAccess($id, Slim $app) { try { $emoji = Emoji::find($id); } catch (RecordNotFoundException $e) { $app->response->headers->set('Content-Type', 'application/json'); $app->halt(404, json_encode(['message' => 'Not Found'])); } if ($emoji->getRecord()['dbData']['user_id'] === Setup::getUserId($app)) { return true; } else { $app->response->headers->set('Content-Type', 'application/json'); $app->halt(401, json_encode(['message' => 'Not yours'])); } }
/** * Get user instance with supplied token * * @param Slim $app * @return object|string */ public static function getUserWithToken(Slim $app) { $token = $app->request->headers('Authorization'); if (isset($token)) { try { $user = User::where('token', $token); } catch (RecordNotFoundException $e) { $app->response->headers->set('Content-Type', 'application/json'); $app->halt(401, json_encode(['message' => 'Invalid Token'])); } return $user; } else { $app->response->headers->set('Content-Type', 'application/json'); $app->halt(401, json_encode(['message' => 'Empty Token'])); } }
public static function newInstance(\Slim\Slim $app) { try { $config = $app->config('connection'); $instance = new \PDO("mysql:host={$config['mysql']['host']};dbname={$config['mysql']['database']}", $config['mysql']['user'], $config['mysql']['password'], $config['mysql']['options']); if (!empty($config['mysql']['execute'])) { foreach ($config['mysql']['execute'] as $sql) { $stmt = $instance->prepare($sql); $stmt->execute(); } } } catch (\PDOException $p) { //$this->slim->log->error('BAD THINGS'); return $app->halt(500, $app->view()->fetch('error/500.php')); } return $instance; }
/** * Login method which returns token * * @param Slim $app * @return string */ public static function login(Slim $app) { $app->response->headers->set('Content-Type', 'application/json'); $username = $app->request->params(self::format('username')); $password = $app->request->params(self::format('password')); if (!isset($username, $password)) { $app->halt(401, json_encode(["status" => 401, "message" => "Username & Password Required!"])); } $authUser = User::where('username', $username)->first(); if (empty($authUser)) { return Errors::error401('This User is Not Found!'); } elseif ($authUser['password'] !== sha1($password)) { return Errors::error401('Invalid Credentials'); } else { return self::Tokenize($app); } }
\Slim\Route::setDefaultConditions(array('id' => '[0-9]{1,}')); // Autentification // POST sends username and password na route /login // route /login catches POST request and sets setEncryptedCookie('username', $username, '1 day'); // When you call get(/article .... $checkLoggedOn($app) is called // $checkLoggedOn = function ($app) validates and if user password is valid will return true // and rest of get(/article route will be triggered function isValidLogin($username, $password) { // return true; return $username == 'Greg' && $password == 'letMeIn'; } $authenticateUser = function ($app) { return function () use($app) { if (!isValidLogin($app->getCookie('username'), $app->getCookie('password'))) { $app->halt(401); // Unauthorized access } }; }; $app->post('/login', function () use($app) { try { // get user and pass from post if from form as dataType=html //$username = $app->request->post('username'); //$password = $app->request->post('password'); // get user and pass from post - get and decode JSON request body $body = $app->request()->getBody(); $input = json_decode($body); $username = (string) $input->username; $password = (string) $input->password; // this is how you can check what has been passed. Look into responds from ajaxPost.php
/** * logout Log user out and destroy token * * @param $app * * @return json */ public function logout(Slim $app) { $app->response->headers->set('Content-Type', 'application/json'); $tokenData = $app->request->headers->get('Authorization'); try { if (!isset($tokenData)) { throw new ProvideTokenException(); } $checkUser = $this->user->where(['username' => $tokenData->user])->toJson(); if (!empty($checkUser)) { $this->auth->authorizationEncode(NULL); } # $app->halt(200, json_encode(['message' => 'Logged out Successfully'])); } catch (DataNotFoundException $e) { $app->halt(404, json_encode(['message' => 'Not Found'])); } catch (InvalidTokenException $e) { $app->halt(405, json_encode(['Message' => 'Invalid Token'])); } catch (ProvideTokenException $e) { $app->halt(406, json_encode(['Message' => 'Enter a valid Token'])); } }
<?php require_once 'vendor/autoload.php'; use Slim\Slim; use Dara\Origins\User; use Dara\Origins\Emoji; date_default_timezone_set('Africa/Lagos'); $app = new Slim(); $authCheck = function ($route) use($app) { $user = new User(); $userToken = $app->request->headers['token']; $userInfo = $user->where('users', 'token', $userToken); $storedToken = $userInfo['token']; $now = date('Y-m-d H:i:s', time()); if (!$storedToken) { $app->halt(401, json_encode(["Message" => "You are not allowed to access this route!"])); } if ($now > $userInfo['token_expiry']) { $app->halt(401, json_encode(["Message" => "Expired token. Please login again"])); } }; $ownerCheck = function ($route) use($app) { $userToken = $app->request->headers['token']; $emojiId = $route->getParams()['id']; $user = new User(); $check = $user->checkEmojiOwnership($userToken, $emojiId); if (!$check) { $app->halt(301, json_encode(["Message" => "You are not allowed to modify this emoji!"])); } }; $emojiExists = function ($route) use($app) {
$app->render('html/admin.html'); }); $app->get('/admin/allowances/list', function () use($app) { $users = getUsers($app->db, 'all'); $periods = $app->periods->getAllPeriods(); $app->render('html/allowances.html', array('users' => $users, 'periods' => $periods[1])); }); $app->get('/admin/allowances/list/json', function () use($app) { $search = isset($_GET['search']) ? $_GET['search'] : ''; $sort = isset($_GET['sort']) ? $_GET['sort'] : 'id'; $order = isset($_GET['order']) ? $_GET['order'] : 'ASC'; $limit = isset($_GET['limit']) ? $_GET['limit'] : '10'; $offset = isset($_GET['offset']) ? $_GET['offset'] : '0'; $allowances = $app->allowances->getAllowances($search, $sort, $order, $limit, $offset); if ($allowances[0] === false) { $app->halt(500, $allowances[1]); } $app->contentType('application/json'); $app->render('json/allowances.json', array('allowances' => $allowances[1])); })->name('jsonAllowancesList'); $app->post('/admin/allowances/delete', function () use($app) { $error = false; if (is_array($app->request->post('data'))) { $error = $app->allowances->deleteAllowances($app->request->post('data')); } else { $error = $app->allowances->deleteAllowance($app->request->post('data')); } if ($error === false) { $app->halt(200); } else { $app->halt(500, $error);
$config = (require_once __DIR__ . '/../config.php'); use FA\DI\Container; use Slim\Slim; // Prepare app $app = new Slim($config['slim']); $container = new Container($app, $config); $app->hook('slim.before.router', function () use($app, $container) { $users = count($container['userDao']->findAll()); $pathInfo = $app->request->getPathInfo(); if ($users < 1 && $pathInfo != '/setup') { return $app->redirect('/setup'); } }); $app->get('/setup', function () use($app, $container) { if (count($container['userDao']->findAll()) > 0) { $app->halt(403); } $app->render('setup.html'); }); $app->post('/setup', function () use($app, $container) { if (count($container['userDao']->findAll()) > 0) { $app->halt(403, 'NO MOAR USERS ALLOWED'); } $params = $app->request()->post(); $email = filter_var($params['email'], FILTER_SANITIZE_EMAIL); $email = filter_var($email, FILTER_VALIDATE_EMAIL); if ($email) { try { $user = $container['userService']->createUser($email, $params['password'], $params['confirm-password']); $app->log->info(sprintf('New user %s has been created', $user['email'])); $app->flash('joinSuccess', sprintf('Congrats %s! Now log in and get started!', $user['email']));
/** * This method formats the output to be in proper JSON format * @param Slim $app * @param integer $statusCode * @param string $message */ public static function formatOutput(Slim $app, $statusCode, $message) { $responseMessage = ['Status' => $statusCode, 'Message' => $message]; $app->halt($statusCode, json_encode($responseMessage)); }
/** * Delete user's account * * @param string $username username of a user * @param Slim $app * @return string */ public static function delete($username, Slim $app) { $app->response->headers->set('Content-Type', 'application/json'); try { $user = User::where('username', $username); } catch (RecordNotFoundException $e) { $app->halt(404, json_encode(['message' => 'Not Found'])); } if (is_object($user)) { $fields = $app->request->isPut() ? $app->request->put() : $app->request->patch(); if (md5($fields['password']) == $user->getRecord()['dbData']['password']) { $check = User::destroy($user->getRecord()['dbData']['id']); if ($check === 1) { return json_encode(['message' => 'Account Deleted']); } else { $app->halt(304); } } else { $app->halt(401); } } else { $app->halt(503); } }
/** * deleteEmoji Delete already existing emoji * * @param $id * @param $app * * @return json */ public function deleteEmoji($id, Slim $app) { $app->response->headers->set('Content-Type', 'application/json'); $tokenData = $app->request->headers->get('Authorization'); try { if (!isset($tokenData)) { throw new ProvideTokenException(); } $this->auth->authorizationDecode($tokenData); $deleted = $this->dataName->destroy($id); if ($deleted) { $app->halt(200, json_encode(['Message' => 'Emoji Deleted'])); } } catch (ExpiredException $e) { $app->halt(401, json_encode(['Message' => 'Token has expired'])); } catch (InvalidTokenException $e) { $app->halt(405, json_encode(['Message' => 'Invalid Token'])); } catch (ProvideTokenException $e) { $app->halt(406, json_encode(['Message' => 'Enter a valid Token'])); } catch (DataNotFoundException $e) { $app->halt(401, json_encode(['Message' => 'Emoji not found'])); } }