public function __invoke(Request $request, Response $response, $next) { $parser = new RequestParser($request); $data = $parser->getData(); $session_key = $username = $password = null; if (!empty($data['session_key'])) { $session_key = $data['session_key']; } if (!empty($data['username'])) { $username = $data['username']; } if (!empty($data['password'])) { $password = $data['password']; } if (!is_null($session_key)) { $session = SessionRepository::getSessionByKey($session_key); if (is_null($session)) { $new_response = $response->withStatus(401); $new_response->getBody()->write("Unauthorized: Invalid session key"); return $new_response; } $request->session = $session; $response = $next($request, $response); return $response; } if (is_null($username) || is_null($password)) { $new_response = $response->withStatus(401); $new_response->getBody()->write("Unauthorized: Must supply (session_key) or (username and password)"); return $new_response; } $user = UserRepository::getUserByUsernameAndPassword($username, $password); if (is_null($user)) { $new_response = $response->withStatus(401); $new_response->getBody()->write("Unauthorized: Invalid credentials"); return $new_response; } $session = new Session(); $session->setUser($user); $response = $next($request, $response); return $response; }
use Syndicate\Repositories\SessionRepository; use Syndicate\Utils\RequestParser; $create_session = function (Request $request, Response $response) { $session = Session::getAuthenicatedSession(); $user = $session->getUser(); SessionRepository::saveSession($session); $session_data = array("session_key" => $session->getKey()); $user_data = array("id" => $user->getId(), "username" => $user->username, "first_name" => $user->first_name, "last_name" => $user->last_name); $response_data = array("session" => $session_data, "user" => $user_data, "privileges" => $user->getPrivileges()); $response->getBody()->write(json_encode($response_data)); return $response; }; $app->post("/session/create", $create_session); $close_session = function (Request $request, Response $response) { $parser = new RequestParser($request); $data = $parser->getData(); if (empty($data['session_key'])) { $new_response = $response->withStatus(400); $new_response->getBody()->write("Must supply session_key"); return $new_response; } $count = SessionRepository::markSessionAsDeleted($data['session_key']); if ($count < 1) { $new_response = $response->withStatus(404); $new_response->getBody()->write("Invalid session key"); return $new_response; } $response->getBody()->write("Successfully deleted session with key: " . $data['session_key']); return $response; }; $app->post("/session/close", $close_session);