Subversion Repositories oidplus

Rev

Rev 440 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
432 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
5
 * Copyright 2020 Daniel Marschall, ViaThinkSoft
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
20
# More information about the OAuth2 implementation:
21
# - https://developers.google.com/identity/protocols/oauth2/openid-connect
22
 
23
require_once __DIR__ . '/../../../includes/oidplus.inc.php';
24
 
25
OIDplus::init(true);
440 daniel-mar 26
set_exception_handler(array('OIDplusGui', 'html_exception_handler'));
432 daniel-mar 27
 
28
if (!OIDplus::baseConfig()->getValue('GOOGLE_OAUTH2_ENABLED', false)) {
29
        throw new OIDplusException(_L('Google OAuth authentication is disabled on this system.'));
30
}
31
 
32
if (!isset($_GET['code'])) die();
33
if (!isset($_GET['state'])) die();
34
 
35
if ($_GET['state'] != $_COOKIE['csrf_token']) {
36
        die('Invalid CSRF token');
37
}
38
 
463 daniel-mar 39
if (!function_exists('curl_exec')) {
40
        die(_L('The "CURL" PHP extension is not installed at your system. Please enable the PHP extension <code>php_curl</code>.'));
41
}
42
 
432 daniel-mar 43
$ch = curl_init();
44
curl_setopt($ch, CURLOPT_URL,"https://oauth2.googleapis.com/token");
45
curl_setopt($ch, CURLOPT_POST, 1);
46
curl_setopt($ch, CURLOPT_POSTFIELDS,
47
        "grant_type=authorization_code&".
48
        "code=".$_GET['code']."&".
49
        "redirect_uri=".urlencode(OIDplus::getSystemUrl(false).OIDplus::webpath(__DIR__).'oauth.php')."&".
50
        "client_id=".urlencode(OIDplus::baseConfig()->getValue('GOOGLE_OAUTH2_CLIENT_ID'))."&".
51
        "client_secret=".urlencode(OIDplus::baseConfig()->getValue('GOOGLE_OAUTH2_CLIENT_SECRET'))
52
);
53
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
54
$cont = curl_exec($ch);
55
curl_close($ch);
56
 
57
// Decode JWT "id_token"
58
// see https://medium.com/@darutk/understanding-id-token-5f83f50fa02e
59
// Note: We do not need to verify the signature because the token comes directly from Google
60
$data = json_decode($cont,true);
61
if (isset($data['error'])) {
440 daniel-mar 62
        throw new OIDplusException(_L('Error receiving the authentication token from %1: %2','Google',$data['error'].' '.$data['error_description']));
432 daniel-mar 63
}
64
$id_token = $data['id_token'];
65
$access_token = $data['access_token'];
66
list($header,$payload,$signature) = explode('.', $id_token);
438 daniel-mar 67
$data = json_decode(base64_decode($payload),true);
68
$email = $data['email'];
432 daniel-mar 69
 
438 daniel-mar 70
// Check if the email was verified
71
 
72
if ($data['email_verified'] != 'true') {
440 daniel-mar 73
        throw new OIDplusException(_L('The email address %1 was not verified. Please verify it first!',$email));
438 daniel-mar 74
}
75
 
432 daniel-mar 76
// Everything's done! Now login and/or create account
77
 
78
if (!empty($email)) {
79
        $ra = new OIDplusRA($email);
80
        if (!$ra->existing()) {
81
                $ra->register_ra(null); // create a user account without password
82
 
433 daniel-mar 83
                // Query user infos
84
                $ch = curl_init('https://www.googleapis.com/oauth2/v3/userinfo'); // Initialise cURL
85
                $data_string = '';
86
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
87
                        'Content-Length: ' . strlen($data_string),
88
                        "Authorization: Bearer ".$access_token
89
                ));
90
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
91
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
92
                curl_setopt($ch, CURLOPT_POST, 1);
93
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
94
                $result = curl_exec($ch);
95
                curl_close($ch);
96
                $data = json_decode($result,true);
97
                $personal_name = $data['name']; // = given_name + " " + family_name
98
 
432 daniel-mar 99
                OIDplus::db()->query("update ###ra set ra_name = ?, personal_name = ? where email = ?", array($personal_name, $personal_name, $email));
100
 
101
                OIDplus::logger()->log("[INFO]RA($email)!", "RA '$email' was created because of successful Google OAuth2 login");
102
        }
103
 
104
        OIDplus::logger()->log("[OK]RA($email)!", "RA '$email' logged in via Google OAuth2");
105
        OIDplus::authUtils()::raLogin($email);
106
 
107
        OIDplus::db()->query("UPDATE ###ra set last_login = ".OIDplus::db()->sqlDate()." where email = ?", array($email));
108
 
109
        // Go back to OIDplus
110
 
111
        header('Location:'.OIDplus::getSystemUrl(false));
112
}
433 daniel-mar 113
 
114
// We now have the data of the person that wanted to log in
115
// So we can log off again
116
$ch = curl_init();
117
curl_setopt($ch, CURLOPT_URL,"https://oauth2.googleapis.com/revoke");
118
curl_setopt($ch, CURLOPT_POST, 1);
119
curl_setopt($ch, CURLOPT_POSTFIELDS,
120
        "client_id=".urlencode(OIDplus::baseConfig()->getValue('GOOGLE_OAUTH2_CLIENT_ID'))."&".
121
        "client_secret=".urlencode(OIDplus::baseConfig()->getValue('GOOGLE_OAUTH2_CLIENT_SECRET'))."&".
122
        "token_type_hint=access_token&".
123
        "token=".$access_token
124
);
125
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
126
curl_exec($ch);
127
curl_close($ch);