From cb9d1193c37b7567dcad5497330169d43ab1e8a2 Mon Sep 17 00:00:00 2001 From: Freya Murphy Date: Mon, 27 May 2024 00:29:36 -0400 Subject: initial --- src/web/helpers/auth.php | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/web/helpers/auth.php (limited to 'src/web/helpers/auth.php') diff --git a/src/web/helpers/auth.php b/src/web/helpers/auth.php new file mode 100644 index 0000000..7aa4aff --- /dev/null +++ b/src/web/helpers/auth.php @@ -0,0 +1,59 @@ + $content[0], + 'time' => $content[1] + ); +} + +function store_key($key, $user) { + $file = "/tmp/$key"; + $now = (string)time(); + $content = "$user\n{$now}"; + file_put_contents($file, $content, LOCK_EX); +} + +function get_random($n) +{ + $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $randomString = ''; + + for ($i = 0; $i < $n; $i++) { + $index = rand(0, strlen($characters) - 1); + $randomString .= $characters[$index]; + } + + return $randomString; +} + +function key_auth() { + if (!isset($_SESSION['auth'])) { + return FALSE; + } + $key = $_SESSION['auth']; + $data = load_key($key); + if ($data === FALSE) { + return FALSE; + } + $user = $data['user']; + $time = $data['time']; + $now = time(); + if ($time > $now || $now - $time > 60 * 60 * 24) { + return FALSE; + } + store_key($key, $user); + return $user; +} + +function key_new($user) { + $key = get_random(128); + store_key($key, $user); + $_SESSION['auth'] = $key; +} -- cgit v1.2.3-freya