From 6600f542e2235b19ca805ce1fa1dfdf4d06584ee Mon Sep 17 00:00:00 2001 From: Orestis Moresis Date: Fri, 23 Jun 2023 13:58:22 +0300 Subject: [PATCH] fix guest login --- src/Controllers/AuthController.php | 17 ++++++++++++++--- src/Services/PgSql.php | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/Controllers/AuthController.php b/src/Controllers/AuthController.php index 5f3db1d..c96ad24 100644 --- a/src/Controllers/AuthController.php +++ b/src/Controllers/AuthController.php @@ -24,12 +24,12 @@ class AuthController { // Handle guest login if (!isset($_POST['password'])) { - $_SESSION['user_id'] = guidv4($email); $_SESSION['user_groups'] = [1]; $_SESSION['user_name'] = "Guest"; + $_SESSION['user_id'] = self::insertGuestUser($email); /* header('HTTP/1.1 302 Found'); */ - header('Location: /home'); - /* return TRUE; */ + header('Location: /'); + return TRUE; } else { // handle user login $email = $_POST['username']; $password = $_POST['password']; @@ -85,6 +85,17 @@ class AuthController { exit(); /* header('Refresh: 2; URL = index.php'); */ } + + + private function insertGuestUser($email) { + $uid = guidv4($email); + $sql = "INSERT INTO webapp.users (email, password, origin, geo_id) + VALUES ('${email}', '', 'GUEST', '${uid}') + ON CONFLICT (email) DO UPDATE + SET geo_id = EXCLUDED.geo_id, + last_login = now()"; + return json_decode(PgSql::insert($sql, 'geo_id'))->geo_id; + } } diff --git a/src/Services/PgSql.php b/src/Services/PgSql.php index 187d233..90aaadf 100644 --- a/src/Services/PgSql.php +++ b/src/Services/PgSql.php @@ -101,6 +101,25 @@ class PgSql return json_encode($response); } + // For UPSERT + // Returns one or more columns of the successful insert + public static function upsert($sql, $conf, $exc, ...$ret) + { + $excluded_columns = implode(',', $exc); + if ($ret != 'NULL') { + $sql = rtrim($sql, ';'); + $sql .= "\nON CONFLICT (${conf}) DO UPDATE + SET "; + $sql .= ' RETURNING '; + $sql .= implode(',', $ret); + } + echo $sql; + $result = pg_query(self::$db, $sql); + if (pg_last_error()) exit(pg_last_error()); + $response = pg_fetch_object($result); + return json_encode($response); + } + // For UPDATE, DELETE and CREATE TABLE // Returns number of affected rows public static function exec($sql)