pub / rememori

Simple file-based bookmarking and notes application
git clone https://src.jayvii.de/pub/rememori.git
Home | Log | Files | Exports | Refs | README | RSS

commit 99fbd93a2051b06072fe5a2375ef739177969090
parent 1fe47254d5e3f60d9d0a64b959c4f183fe8895ce
Author: JayVii <jayvii[AT]posteo[DOT]de>
Date:   Wed, 30 Oct 2024 16:59:01 +0100

feat: use cookie in API

Diffstat:
Mapi/new.php | 11++++++++++-
Mindex.php | 4+++-
Mlib/users.php | 36++++++++++++++++++++++--------------
3 files changed, 35 insertions(+), 16 deletions(-)

diff --git a/api/new.php b/api/new.php @@ -39,13 +39,22 @@ $token = validate_input_string(gather_get("token")); } + /* read information from cookie */ + if ( + (empty($user) || empty($token)) && + (array_key_exists("session", $_COOKIE)) + ) { + $user = explode("|", $_COOKIE["session"])[0]; + $token = explode("|", $_COOKIE["session"])[1]; + } + /* if category is unset, set it! */ if (empty($category)) { $category = "unknown"; } /* run authentification method. exit immediately if it fails */ - $auth = auth_user($user, $token, -1); + $auth = auth_user($user, $token); if ($auth !== true) { http_response_code(401); // unauthorized api_error($return, $GLOBALS["i18n_noauth"]); diff --git a/index.php b/index.php @@ -44,9 +44,11 @@ } /* Check authentification of user */ - $auth = auth_user($user, $token, $cookie); + $auth = auth_user($user, $token); if ($auth !== true) { $action = "login"; + } else { + set_auth_cookie($user, $token, $cookie); } /* ensure the given filename (if it is set!) has a valid extension */ diff --git a/lib/users.php b/lib/users.php @@ -31,8 +31,7 @@ function create_password_hash( function auth_user( string $user, - string $token, - int $cookie_time + string $token ) { if (empty($user) || empty($token)) { @@ -57,24 +56,33 @@ function auth_user( /* If matches between given hash and tokens were found, return "true" */ if (count($matches) > 0 && $matches !== false) { - /* set longtime or session cookie, according to preferences */ - $cookie_content = "Set-Cookie: " . - "session=" . $user . "|" . $token . "; " . - "Domain=" . $_SERVER["SERVER_NAME"] . "; " . - "SameSite=Strict;"; - if ($cookie_time > 0) { - $cookie_content = $cookie_content . - "Max-Age=" . (60 * 60 * 24 * $cookie_time) . "; "; - } - header($cookie_content); - - /* return success state */ return true; } else { return false; } } +function set_auth_cookie( + string $user, + string $token, + int $cookie_time +) { + + /* set longtime or session cookie, according to preferences */ + $cookie_content = "Set-Cookie: " . + "session=" . $user . "|" . $token . "; " . + "Domain=" . $_SERVER["SERVER_NAME"] . "; " . + "SameSite=Strict;"; + if ($cookie_time > 0) { + $cookie_content = $cookie_content . + "Max-Age=" . (60 * 60 * 24 * $cookie_time) . "; "; + } + header($cookie_content); + + /* return true */ + return true; +} + function create_auth( string $user, string $pass