blob: b91737feabad313547d826682789805845add4c9 [file] [log] [blame]
avm9996370995382020-09-23 01:03:01 +02001<?php
2namespace DAFME\Covid;
3
4class Users {
avm99963339e6f72020-09-27 17:12:43 +02005 private static function getUserIdFromSub($sub) {
avm9996370995382020-09-23 01:03:01 +02006 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
avm99963339e6f72020-09-27 17:12:43 +020018 public static function add($sub, $email): int {
avm9996370995382020-09-23 01:03:01 +020019 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
avm99963339e6f72020-09-27 17:12:43 +020027 public static function signIn($sub, $email): bool {
avm9996370995382020-09-23 01:03:01 +020028 global $_SESSION;
29
avm99963339e6f72020-09-27 17:12:43 +020030 $userId = self::getUserIdFromSub($sub);
avm9996370995382020-09-23 01:03:01 +020031
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
avm99963339e6f72020-09-27 17:12:43 +020042 public static function signOut(): void {
avm9996370995382020-09-23 01:03:01 +020043 global $_SESSION;
44 unset($_SESSION['userId']);
45 }
46
avm99963339e6f72020-09-27 17:12:43 +020047 public static function isSignedIn(): bool {
avm9996370995382020-09-23 01:03:01 +020048 global $_SESSION;
49 return isset($_SESSION['userId']);
50 }
avm99963339e6f72020-09-27 17:12:43 +020051
52 public static function getUserId(): int {
53 global $_SESSION;
54 return (self::isSignedIn() ? $_SESSION['userId'] : -1);
55 }
avm9996370995382020-09-23 01:03:01 +020056}