forked from aeecleclair/PiwigoOpenIdConnect
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoidc.php
More file actions
260 lines (213 loc) · 6.52 KB
/
oidc.php
File metadata and controls
260 lines (213 loc) · 6.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php
/*
Copyright 2020-2021 Jasper Weyne
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
defined('PHPWG_ROOT_PATH') or die('Hacking attempt!');
require __DIR__ . '/vendor/autoload.php';
use Jumbojett\OpenIDConnectClient;
/**
* Create an instance of OpenIDConnectClient with the configured settings
*/
function get_oidc_client() {
global $conf;
$config = $conf['OIDC'];
// Create OIDC client
$oidc = new OpenIDConnectClient(
$config['issuer_url'] ?? '',
$config['client_id'] ?? '',
$config['client_secret'] ?? ''
);
// Set verification bits
$oidc->setVerifyHost($config['verify_host']);
$oidc->setVerifyPeer($config['verify_peer']);
// Set HTTP proxy
if (!empty($config['proxy'])) {
$oidc->setHttpProxy($config['proxy']);
}
// Set auth params
if ($array = json_decode($config['authparam'], true) !== null) {
$oidc->addAuthParam($array);
}
// Set scopes
$oidc->addScope(explode(' ', $config['scope']));
return $oidc;
}
/**
* Return whether the authorization code flow is enabled from config
*/
function can_authorization_grant() {
global $conf;
return $conf['OIDC']['authorization_code_flow'];
}
/**
* Return whether the resource owner credentials flow is enabled from config
*/
function can_resource_owner_credentials_grant() {
global $conf;
return $conf['OIDC']['password_flow'];
}
/**
* Redirect a user to the auth.php page if enabled
* If disabled, returns false
*/
function redirect_auth()
{
if (can_authorization_grant()) {
redirect(OIDC_PATH . 'auth.php');
return true;
}
return false;
}
/**
* Get the preferred username of the resource owner
* Resource owner is authenticated by the access token, stored in $oidc
*/
function get_preferred_username(OpenIDConnectClient $oidc) {
global $conf;
$config = $conf['OIDC'];
// Note: this value must be unique, therefore we use sub
$name = $oidc->requestUserInfo('sub');
if (!empty($config['preferred_username'] && $preferred = $oidc->requestUserInfo($config['preferred_username']))) {
$name = $preferred;
}
return $name;
}
/// Login/logout methods
/**
* Retrieve Piwigo user associated with the current OIDC resource owner
* Resource owner is authenticated by the access token, stored in $oidc
*/
function oidc_retrieve(OpenIDConnectClient $oidc, $force_registration = false) {
global $conf;
$config = $conf['OIDC'];
// Fetch user data
$sub = $oidc->requestUserInfo('sub');
$email = $oidc->requestUserInfo('email');
$name = get_preferred_username($oidc);
// Try to find the resource owner in the OIDC user table
$query = '
SELECT `user_id` AS id
FROM ' . OIDC_TABLE . '
WHERE `sub` = \'' . pwg_db_real_escape_string($sub) . '\';';
$row = pwg_db_fetch_assoc(pwg_query($query));
// If the user is not found, try to register
if (empty($row['id'])) {
if ($config['register_new_users'] || $force_registration) {
// Registration is allowed, overwrite $row
$errors = [];
$row['id'] = register_user($name, random_pass(), $email, $config['notify_admins_on_register'], $errors, $config['notify_user_on_register']);
single_insert(OIDC_TABLE, [
'sub' => $sub,
'user_id' => $row['id'],
]);
} else {
// Registration is not allowed, fail
return null;
}
}
// Groups registration //
// If the group management setting is enabled, add the user to the configured groups
if ($config['manage_groups']) {
$groups_claim = "groups";
if (!empty($config['groups_claim'])) {
$groups_claim = $config['groups_claim'];
}
// Remove existing groups
$query = '
DELETE FROM ' . USER_GROUP_TABLE . '
WHERE `user_id` = ' . $row['id'] . ';';
pwg_query($query);
// Get the groups array provided by the oidc provider
$groups = $oidc->requestUserInfo($groups_claim);
foreach ($groups as $group_name)
{
// Check if expected group exists
$query = '
SELECT id FROM `'.GROUPS_TABLE.'`
WHERE name = \'' . pwg_db_real_escape_string($group_name) . '\'';
$group_row = pwg_db_fetch_assoc(pwg_query($query));
// The group does not exist, we need to create it
if (empty($group_row['id'])) {
// creating the group, see line 82 gallery/include/ws_functions/pwg.groups.php
single_insert(
GROUPS_TABLE,
array(
'name' => pwg_db_real_escape_string($group_name),
'is_default' => boolean_to_string(false),
)
);
$inserted_id = pwg_db_insert_id();
$group_id = $inserted_id;
} else {
// The group exists, we just need its id
$group_id = $group_row['id'];
}
// Add the user to the group
single_insert(USER_GROUP_TABLE, [
'user_id' => $row['id'],
'group_id' => $group_id,
]);
}
}
return $row['id'];
}
/**
* Log the Piwigo user associated with the provided $token, through the current $oidc session
*/
function oidc_login(OpenIDConnectClient $oidc, $token, $remember_me)
{
global $conf;
// Find user in piwigo database
$id = oidc_retrieve($oidc);
if ($id === null) {
return false;
}
$name = get_preferred_username($oidc);
$email = $oidc->requestUserInfo('email');
// Store access token in the session
$encoded = array();
if (isset($token->access_token)) {
$encoded['access_token'] = $token->access_token;
}
if (isset($token->refresh_token)) {
$encoded['refresh_token'] = $token->refresh_token;
}
if (isset($token->expires_in)) {
$encoded['expires'] = time() + $token->expires_in;
}
$_SESSION[OIDC_SESSION] = json_encode($encoded);
// Update user data from ID token data
$fields = array($conf['user_fields']['email'], $conf['user_fields']['username']);
$data = array();
$data[$conf['user_fields']['id']] = $id;
$data[$conf['user_fields']['email']] = $email;
$data[$conf['user_fields']['username']] = $name;
mass_updates(USERS_TABLE,
array(
'primary' => array($conf['user_fields']['id']),
'update' => $fields
),
array($data));
// Log the user in
log_user($id, $remember_me);
trigger_notify('login_success', stripslashes($name));
return true;
}
/**
* Log out the currently logged in user and redirect to the login page
*/
function oidc_logout()
{
logout_user();
redirect_auth() or redirect('identification.php');
}
?>