avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 1 | <?php |
| 2 | namespace DAFME\Covid; |
| 3 | |
| 4 | class Users { |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 5 | private static function getUserIdFromSub($sub) { |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 6 | global $con; |
| 7 | $query = $con->prepare('SELECT id FROM users WHERE sub = ?'); |
| 8 | if (!$query->execute([$sub])) |
| 9 | return false; |
| 10 | |
| 11 | if ($query->rowCount() < 1) |
| 12 | return false; |
| 13 | |
| 14 | $row = $query->fetch(); |
| 15 | return $row['id'] ?? false; |
| 16 | } |
| 17 | |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 18 | public static function add($sub, $email): int { |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 19 | global $con; |
| 20 | $query = $con->prepare('INSERT INTO users (sub, email) VALUES (?, ?)'); |
| 21 | if (!$query->execute([$sub, $email])) |
| 22 | return false; |
| 23 | |
| 24 | return $con->lastInsertId(); |
| 25 | } |
| 26 | |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 27 | public static function signIn($sub, $email): bool { |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 28 | global $_SESSION; |
| 29 | |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 30 | $userId = self::getUserIdFromSub($sub); |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 31 | |
| 32 | if ($userId === false) |
| 33 | $userId = self::add($sub, $email); |
| 34 | |
| 35 | if ($userId === false) |
| 36 | return false; |
| 37 | |
| 38 | $_SESSION['userId'] = $userId; |
| 39 | return true; |
| 40 | } |
| 41 | |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 42 | public static function signOut(): void { |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 43 | global $_SESSION; |
| 44 | unset($_SESSION['userId']); |
| 45 | } |
| 46 | |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 47 | public static function isSignedIn(): bool { |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 48 | global $_SESSION; |
| 49 | return isset($_SESSION['userId']); |
| 50 | } |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 51 | |
| 52 | public static function getUserId(): int { |
| 53 | global $_SESSION; |
| 54 | return (self::isSignedIn() ? $_SESSION['userId'] : -1); |
| 55 | } |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 56 | } |