diff --git a/composer.json b/composer.json index 1878241..314aba1 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,8 @@ "squizlabs/php_codesniffer": "^3.0" }, "suggest": { - "silverstripe/crontask": "^2.0" + "silverstripe/crontask": "^2.0", + "silverstripe/auditor": "^2.3" }, "autoload": { "psr-4": { diff --git a/src/Control/LoginSessionController.php b/src/Control/LoginSessionController.php new file mode 100644 index 0000000..83dc5b9 --- /dev/null +++ b/src/Control/LoginSessionController.php @@ -0,0 +1,88 @@ + 'remove', + 'DELETE remove/$ID' => 'removeLoginSession' + ]; + + private static $allowed_actions = [ + // TODO: 'remove' + 'removeLoginSession', + ]; + + /** + * Remove the specified login session + * + * @param HTTPRequest $request + * @return HTTPResponse + */ + // TODO: rename to 'remove' + public function removeLoginSession(HTTPRequest $request): HTTPResponse + { + // Ensure CSRF protection + if (!SecurityToken::inst()->checkRequest($request)) { + return $this->jsonResponse( + ['errors' => 'Request timed out, please try again'], + 400 + ); + } + + $id = $request->param('ID'); + $loginSession = LoginSession::get()->byID($id); + if (!$loginSession) { + return $this->jsonResponse( + ['errors' => 'Something went wrong.'], + 400 + ); + } + + if (!$loginSession->canDelete()) { + return $this->jsonResponse( + ['errors' => 'You do not have permission to delete this record.'], + 400 + ); + } + + $this->extend('onBeforeRemoveLoginSession', $loginSession); + + $loginSession->delete(); + + return $this->jsonResponse([ + 'success' => true, + ]); + } + + /** + * Respond with the given array as a JSON response + * + * @param array $response + * @param int $code The HTTP response code to set on the response + * @return HTTPResponse + */ + // TODO: change visibility to private + protected function jsonResponse(array $response, int $code = 200): HTTPResponse + { + return HTTPResponse::create(json_encode($response)) + ->addHeader('Content-Type', 'application/json') + ->setStatusCode($code); + } +}