Added url ignore support for the csrf token middleware. Also properly implemented create_token.

This commit is contained in:
Relintai 2022-01-09 15:53:40 +01:00
parent e728d826f1
commit 885d6cb4a6
2 changed files with 29 additions and 1 deletions

View File

@ -3,6 +3,7 @@
#include "core/hash/sha256.h" #include "core/hash/sha256.h"
#include "http_session.h" #include "http_session.h"
#include "request.h" #include "request.h"
#include <time.h>
bool CSRFTokenMiddleware::on_before_handle_request_main(Request *request) { bool CSRFTokenMiddleware::on_before_handle_request_main(Request *request) {
switch (request->get_method()) { switch (request->get_method()) {
@ -11,6 +12,10 @@ bool CSRFTokenMiddleware::on_before_handle_request_main(Request *request) {
case HTTP_METHOD_PATCH: case HTTP_METHOD_PATCH:
case HTTP_METHOD_PUT: { case HTTP_METHOD_PUT: {
if (shold_ignore(request)) {
return false;
}
if (!request->session.is_valid()) { if (!request->session.is_valid()) {
request->send_error(HTTP_STATUS_CODE_401_UNAUTHORIZED); request->send_error(HTTP_STATUS_CODE_401_UNAUTHORIZED);
return true; return true;
@ -39,8 +44,24 @@ bool CSRFTokenMiddleware::on_before_handle_request_main(Request *request) {
return false; return false;
} }
bool CSRFTokenMiddleware::shold_ignore(Request *request) {
const String &path = request->get_path_full();
for (int i = 0; i < ignored_urls.size(); ++i) {
if (path.starts_with(ignored_urls[i])) {
return true;
}
}
return false;
}
String CSRFTokenMiddleware::create_token() { String CSRFTokenMiddleware::create_token() {
return "test"; Ref<SHA256> h = SHA256::get();
String s = h->compute(String::num(time(NULL)));
return s.substr(0, 10);
} }
CSRFTokenMiddleware::CSRFTokenMiddleware() { CSRFTokenMiddleware::CSRFTokenMiddleware() {

View File

@ -3,6 +3,9 @@
#include "middleware.h" #include "middleware.h"
#include "core/containers/vector.h"
#include "core/string.h"
class Request; class Request;
class CSRFTokenMiddleware : public Middleware { class CSRFTokenMiddleware : public Middleware {
@ -12,10 +15,14 @@ public:
//returnring true means handled, false means continue //returnring true means handled, false means continue
bool on_before_handle_request_main(Request *request); bool on_before_handle_request_main(Request *request);
bool shold_ignore(Request *request);
virtual String create_token(); virtual String create_token();
CSRFTokenMiddleware(); CSRFTokenMiddleware();
~CSRFTokenMiddleware(); ~CSRFTokenMiddleware();
Vector<String> ignored_urls;
}; };
#endif #endif