-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.php
More file actions
339 lines (283 loc) · 10.1 KB
/
Copy pathauth.php
File metadata and controls
339 lines (283 loc) · 10.1 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<?php
session_start();
require_once 'host.php';
/**
* Decode a JWT payload without verifying the signature.
*/
function decodeJwtPayload(string $token): ?array {
$parts = explode('.', $token);
if (count($parts) !== 3) {
return null;
}
$payload = base64_decode(strtr($parts[1], '-_', '+/'));
if ($payload === false) {
return null;
}
$data = json_decode($payload, true);
return is_array($data) ? $data : null;
}
/**
* Build a shared GraphQL request payload.
*/
function graphqlRequest(string $domain, string $protocol, string $query, array $variables = [], array $headers = []): ?array {
$normalizedDomain = preg_replace('#^https?://#i', '', trim($domain));
$endpoint = $protocol . '://' . $normalizedDomain . '/graphql';
$payload = json_encode([
'query' => $query,
'variables' => $variables ?: new stdClass(),
]);
$headerString = "Content-Type: application/json\r\n";
foreach ($headers as $name => $value) {
$headerString .= $name . ': ' . $value . "\r\n";
}
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => $headerString,
'content' => $payload,
'timeout' => 8,
'ignore_errors' => true,
],
]);
$body = @file_get_contents($endpoint, false, $context);
if ($body === false) {
return null;
}
return json_decode($body, true);
}
/**
* Store auth and helper cookies with optional long-term expiry.
*/
function setAuthCookies(string $accessToken, string $refreshToken, bool $rememberMe, ?string $email = null, ?string $password = null): void {
$expiry = $rememberMe ? time() + (60) : 0; // approx. 10 years 3650 * 24 * 60 *
$options = [
'expires' => $expiry,
'path' => '/',
'secure' => true,
'httponly' => false,
'samesite' => 'Strict',
];
setcookie('authToken', $accessToken, $options);
setcookie('refreshToken', $refreshToken, $options);
setcookie('rememberMe', $rememberMe ? 'true' : 'false', $options);
if ($email !== null) {
setcookie('userEmail', $email, $options);
}
if ($password !== null) {
setcookie('userPassword', $password, $options);
}
}
/**
* Remove all auth related cookies.
*/
function clearAuthCookies(): void {
$names = ['authToken', 'refreshToken', 'rememberMe', 'userEmail', 'userPassword'];
$options = [
'expires' => time() - 3600,
'path' => '/',
'secure' => true,
'httponly' => false,
'samesite' => 'Strict',
];
foreach ($names as $name) {
setcookie($name, '', $options);
}
}
/**
* Try to refresh tokens using the refreshToken cookie.
*/
function attemptTokenRefresh(string $refreshToken, string $domain, string $protocol = 'https'): ?array {
$query = '
mutation RefreshToken($refreshToken: String!) {
refreshToken(refreshToken: $refreshToken) {
status
ResponseCode
accessToken
refreshToken
}
}';
$data = graphqlRequest($domain, $protocol, $query, ['refreshToken' => $refreshToken]);
if (!is_array($data)) {
return null;
}
$result = $data['data']['refreshToken'] ?? null;
if (!is_array($result) || $result['status'] !== 'success' || empty($result['accessToken']) || empty($result['refreshToken'])) {
return null;
}
return [
'authToken' => $result['accessToken'],
'refreshToken' => $result['refreshToken'],
];
}
/**
* Fallback login using stored email/password cookies.
*/
function attemptPasswordLogin(string $email, string $password, string $domain, string $protocol = 'https'): ?array {
if ($email === '' || $password === '') {
return null;
}
$query =
'mutation Login($email: String!, $password: String!) {
login(email: $email, password: $password) {
status
ResponseCode
accessToken
refreshToken
}
}';
$data = graphqlRequest($domain, $protocol, $query, ['email' => $email, 'password' => $password]);
if (!is_array($data)) {
return null;
}
$result = $data['data']['login'] ?? null;
if (!is_array($result) || $result['status'] !== 'success' || empty($result['accessToken']) || empty($result['refreshToken'])) {
return null;
}
return [
'authToken' => $result['accessToken'],
'refreshToken' => $result['refreshToken'],
];
}
function checkAuth($redirectMessage = "unauthorized") {
global $domain, $protocol;
$token = $_COOKIE['authToken'] ?? '';
$payload = $token !== '' ? decodeJwtPayload($token) : null;
$isExpired = !is_array($payload) || !isset($payload['exp']) || (int) $payload['exp'] < time();
$temP = (int) $payload['exp'] - time();
// Token still valid - proceed.
if ($token !== '' && !$isExpired) {
return;
}
$refreshToken = $_COOKIE['refreshToken'] ?? '';
$rememberMe = ($_COOKIE['rememberMe'] ?? '') === 'true';
$email = $_COOKIE['userEmail'] ?? '';
$password = $_COOKIE['userPassword'] ?? '';
// Attempt silent refresh first.
if ($refreshToken !== '') {
$refreshed = attemptTokenRefresh($refreshToken, $domain ?? ($_SERVER['HTTP_HOST'] ?? ''), $protocol ?? 'https');
if ($refreshed !== null) {
setAuthCookies($refreshed['authToken'], $refreshed['refreshToken'], $rememberMe, $email, $password !== '' ? $password : null);
return;
}
}
// Fallback to stored credentials when available.
if ($rememberMe && $email !== '' && $password !== '') {
$login = attemptPasswordLogin($email, $password, $domain ?? ($_SERVER['HTTP_HOST'] ?? ''), $protocol ?? 'https');
if ($login !== null) {
setAuthCookies($login['authToken'], $login['refreshToken'], true, $email, $password);
return;
}
}
clearAuthCookies();
header("Location: login.php?message=$redirectMessage");
exit();
}
/**
* Execute Hello query via GraphQL using the auth token.
* Returns the decoded "hello" object or null on failure.
*/
function fetchHelloData(string $domain, string $protocol = 'https'): ?array {
$token = $_COOKIE['authToken'] ?? '';
if ($token == '') {
return null;
}
//$domain='getpeer.eu';
// Normalize domain in case a scheme was passed accidentally.
$domain = preg_replace('#^https?://#i', '', trim($domain));
$payload = json_encode([
'query' => 'query Hello {
hello {
currentuserid
currentVersion
wikiLink
lastMergedPullRequestNumber
companyAccountId
userroles
userRoleString
}
}',
'variables' => new stdClass(),
]);
$attempt = function (string $scheme, string $path) use ($domain, $payload, $token): ?array {
$endpoint = $scheme . '://' . $domain . $path;
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nAuthorization: Bearer {$token}\r\n",
'content' => $payload,
'timeout' => 5,
'ignore_errors' => true,
],
]);
$body = @file_get_contents($endpoint, false, $context);
$data = json_decode($body, true);
// Check if API returned { "error": "Invalid Access Token" }
if (!empty($data['error']) && $data['error'] === 'Invalid Access Token') {
return null;
}
$status = 0;
if (isset($http_response_header[0]) && preg_match('#HTTP/\\S+\\s(\\d{3})#', $http_response_header[0], $m)) {
$status = (int) $m[1];
}
return ['body' => $body, 'status' => $status];
};
$paths = ['/graphql', '/api/graphql'];
$schemes = [$protocol];
if ($protocol === 'https') {
# $schemes[] = 'http'; // fallback if https unreachable
}
foreach ($schemes as $scheme) {
foreach ($paths as $path) {
$response = $attempt($scheme, $path);
if ($response !== null && $response['status'] === 200 && $response['body'] !== false) {
$data = json_decode($response['body'], true);
return $data['data']['hello'] ?? null;
}
}
}
return null;
}
/**
* Resolve the current user id via GraphQL using the auth token.
* Returns null on failure so callers can fail closed.
*/
function fetchCurrentUserId(string $domain, string $protocol = 'https'): ?string {
$hello = fetchHelloData($domain, $protocol);
return $hello['currentuserid'] ?? null;
}
/**
* Resolve the current user role string via GraphQL using the auth token.
*/
function fetchUserRoleString(string $domain, string $protocol = 'https'): ?string {
$hello = fetchHelloData($domain, $protocol);
return $hello['userRoleString'] ?? null;
}
/**
* Deny access unless the current user id matches an allowed one.
*/
function enforceAllowedUser(array $allowedUserIds, string $domain, string $protocol = 'https'): void {
$currentUserId = fetchCurrentUserId($domain, $protocol);
if ($currentUserId === null || !in_array($currentUserId, $allowedUserIds, true)) {
http_response_code(403);
exit('Access denied');
}
}
/**
* Deny access unless the current user role string is ADMIN.
*/
function enforceAdminRole(string $domain, string $protocol = 'https'): void {
$role = fetchUserRoleString($domain, $protocol);
if ($role !== 'MODERATOR') {
http_response_code(403);
exit('Access denied');
}
}
/* ---------------------------------------------------
Initialize global role once per request
--------------------------------------------------- */
$role = fetchUserRoleString($domain);
$GLOBALS["userRole"] = strtoupper($role !== null ? $role : "GUEST");
function isModerator(): bool {
return isset($GLOBALS["userRole"]) && $GLOBALS["userRole"] === "MODERATOR";
}
?>