blob: 8027a36e8d0789c8635aa55ec766f2abcc4cb966 [file] [log] [blame]
avm9996370995382020-09-23 01:03:01 +02001<?php
2namespace DAFME\Covid;
3
4class 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');
avm99963449d4322020-09-28 23:22:37 +020016
17 // Sometimes the server is slightly out of sync with the OAuth2 server.
18 \Firebase\JWT\JWT::$leeway = 5;
avm9996370995382020-09-23 01:03:01 +020019 }
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}