avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 1 | <?php |
| 2 | namespace DAFME\Covid; |
| 3 | |
| 4 | class Auth { |
| 5 | private $client; |
| 6 | |
| 7 | public function __construct() { |
| 8 | global $conf; |
| 9 | $this->client = new \Google_Client(); |
| 10 | $this->client->setApplicationName = 'dafme-covid-tracability-backend'; |
| 11 | $this->client->setClientId($conf['goog']['clientId']); |
| 12 | $this->client->setClientSecret($conf['goog']['secret']); |
| 13 | $this->client->addScope('https://www.googleapis.com/auth/userinfo.email'); |
| 14 | $this->client->setRedirectUri($conf['fullPath'].'oauth2callback.php'); |
| 15 | $this->client->setAccessType('online'); |
avm99963 | 449d432 | 2020-09-28 23:22:37 +0200 | [diff] [blame^] | 16 | |
| 17 | // Sometimes the server is slightly out of sync with the OAuth2 server. |
| 18 | \Firebase\JWT\JWT::$leeway = 5; |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 19 | } |
| 20 | |
| 21 | public function getAuthUrl() { |
| 22 | return $this->client->createAuthUrl(); |
| 23 | } |
| 24 | |
| 25 | public function handleCallback() { |
| 26 | global $_GET, $con; |
| 27 | if (isset($_GET['error']) || !isset($_GET['code'])) return 1; |
| 28 | |
| 29 | $accessToken = null; |
| 30 | |
| 31 | try { |
| 32 | $accessToken = $this->client->fetchAccessTokenWithAuthCode($_GET['code']); |
| 33 | } catch (\Exception $exception) { |
| 34 | return 2; |
| 35 | } |
| 36 | |
| 37 | $id = $this->client->verifyIdToken(); |
| 38 | if ($id === false) |
| 39 | return 3; |
| 40 | |
| 41 | if (!isset($id['sub']) || !isset($id['email']) || !isset($id['email_verified'])) |
| 42 | return 4; |
| 43 | |
| 44 | if ($id['email_verified'] === false) |
| 45 | return 5; |
| 46 | |
| 47 | $sub = $id['sub']; |
| 48 | $email = $id['email']; |
| 49 | |
| 50 | if (preg_match('/upc.edu$/', $id['email']) !== 1) |
| 51 | return 6; |
| 52 | |
| 53 | if (!Users::signIn($sub, $email)) |
| 54 | return 7; |
| 55 | |
| 56 | return 0; |
| 57 | } |
| 58 | |
| 59 | public function setAccessToken($token) { |
| 60 | $this->client->setAccessToken($token); |
| 61 | } |
| 62 | } |