-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallback.php
More file actions
363 lines (356 loc) · 16.3 KB
/
Copy pathcallback.php
File metadata and controls
363 lines (356 loc) · 16.3 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
session_start();
// Load configuration
require_once '/var/www/config/streamersconnect.php';
require_once __DIR__ . '/oauth_helpers.php';
/**
* Handle OAuth callback from service provider
*/
if (isset($_GET['code']) && isset($_GET['state'])) {
// Verify state to prevent CSRF attacks
if (!isset($_SESSION['oauth_state']) || $_GET['state'] !== $_SESSION['oauth_state']) {
die('Error: Invalid state parameter. Possible CSRF attack.');
}
// Get the authorization code and service
$authCode = $_GET['code'];
$service = $_SESSION['auth_service'] ?? null;
// Validate service parameter exists
if (!$service) {
http_response_code(400);
die('Error: Missing service information. Authentication request was not properly initiated.');
}
// Get custom credentials from session if they were provided
$customClientId = $_SESSION['custom_client_id'] ?? null;
$customClientSecret = $_SESSION['custom_client_secret'] ?? null;
// If no custom credentials, try to get domain-specific OAuth app
if (!$customClientId || !$customClientSecret) {
$originDomain = $_SESSION['origin_domain'] ?? 'unknown';
$domainCredentials = getOAuthCredentialsForDomain($service, $originDomain);
if ($domainCredentials) {
$customClientId = $domainCredentials['client_id'];
$customClientSecret = $domainCredentials['client_secret'];
}
}
// Route to appropriate service handler
$originDomain = $_SESSION['origin_domain'] ?? 'unknown';
$requestedScopes = $_SESSION['requested_scopes'] ?? '';
switch ($service) {
case 'twitch':
$tokenData = exchangeTwitchCodeForToken($authCode, $customClientId, $customClientSecret);
if ($tokenData === false) {
scLogAuthAttempt($service, $originDomain, [], $requestedScopes, false, 'Failed to exchange authorization code for access token');
die('Error: Failed to exchange authorization code for access token.');
}
$userData = getTwitchUserData($tokenData['access_token'], $customClientId);
if ($userData === false) {
scLogAuthAttempt($service, $originDomain, [], $requestedScopes, false, 'Failed to retrieve user data from Twitch API');
die('Error: Failed to retrieve user data from Twitch.');
}
break;
case 'discord':
$tokenData = exchangeDiscordCodeForToken($authCode, $customClientId, $customClientSecret);
if ($tokenData === false) {
scLogAuthAttempt($service, $originDomain, [], $requestedScopes, false, 'Failed to exchange authorization code for access token');
die('Error: Failed to exchange authorization code for access token.');
}
$userData = getDiscordUserData($tokenData['access_token']);
if ($userData === false) {
scLogAuthAttempt($service, $originDomain, [], $requestedScopes, false, 'Failed to retrieve user data from Discord API');
die('Error: Failed to retrieve user data from Discord.');
}
break;
default:
scLogAuthAttempt('unknown', $originDomain, [], $requestedScopes, false, 'Unknown service in session');
die('Error: Unknown service in session');
}
// Prepare data to send back to the originating service
$returnData = [
'success' => true,
'service' => $service,
'access_token' => $tokenData['access_token'],
'refresh_token' => $tokenData['refresh_token'],
'expires_in' => $tokenData['expires_in'],
'scope' => $tokenData['scope'],
'token_type' => $tokenData['token_type'],
'user' => [
'id' => $userData['id'],
'login' => $userData['login'],
'display_name' => $userData['display_name'],
'email' => $userData['email'] ?? null,
'profile_image_url' => $userData['profile_image_url'],
'broadcaster_type' => $userData['broadcaster_type']
]
];
// Get the return URL from session (originDomain and requestedScopes already loaded above)
$returnUrl = $_SESSION['return_url'] ?? null;
if (!$returnUrl || !$originDomain) {
scLogAuthAttempt($service ?? 'unknown', $originDomain ?? 'unknown', [], $requestedScopes, false, 'Missing return URL or origin domain in session');
die('Error: No return URL found in session.');
}
// Log successful authentication
scLogAuthAttempt($service, $originDomain, $returnData['user'], $requestedScopes, true);
// Dispatch webhook notifications (standard or Discord embed)
dispatch_webhooks($service, $originDomain, $returnData['user'], 'authentication_success');
// Store origin domain for display (before clearing session)
$displayOrigin = $originDomain;
// Check if this is StreamersConnect's own authentication (dashboard or base URL)
$internalUrls = [
INTERNAL_DASHBOARD_URL,
'https://' . STREAMERS_CONNECT_DOMAIN . '/',
'https://' . STREAMERS_CONNECT_DOMAIN
];
if (in_array($returnUrl, $internalUrls)) {
// Handle internal auth directly - store session and redirect to home
$_SESSION['user_id'] = $returnData['user']['id'];
$_SESSION['user_login'] = $returnData['user']['login'];
$_SESSION['user_display_name'] = $returnData['user']['display_name'];
$_SESSION['user_email'] = $returnData['user']['email'];
$_SESSION['access_token'] = $returnData['access_token'];
$_SESSION['refresh_token'] = $returnData['refresh_token'];
$_SESSION['auth_service'] = $service;
// Clear OAuth state data
unset($_SESSION['oauth_state'], $_SESSION['return_url'], $_SESSION['origin_domain'], $_SESSION['requested_scopes'], $_SESSION['custom_client_id'], $_SESSION['custom_client_secret'], $_SESSION['oauth_app_id'], $_SESSION['oauth_force_verify']);
// Redirect to home page
$redirectUrl = 'https://' . STREAMERS_CONNECT_DOMAIN . '/';
} else {
// External service authentication - send auth_data back
// Clear sensitive session data we don't need anymore
unset($_SESSION['oauth_state'], $_SESSION['return_url'], $_SESSION['origin_domain'], $_SESSION['requested_scopes'], $_SESSION['auth_service'], $_SESSION['custom_client_id'], $_SESSION['custom_client_secret'], $_SESSION['oauth_app_id'], $_SESSION['oauth_force_verify']);
// Legacy: encode the data as base64 JSON (kept for backwards compatibility)
$legacy = base64_encode(json_encode($returnData));
// Build redirect URL
$separator = strpos($returnUrl, '?') !== false ? '&' : '?';
$redirectUrl = $returnUrl . $separator . 'auth_data=' . urlencode($legacy);
// Additionally provide a signed token (HMAC-SHA256) for receivers able to verify authenticity.
if (defined('AUTH_DATA_SIGNING_KEY') && AUTH_DATA_SIGNING_KEY) {
$signed = create_signed_auth_data($returnData);
if ($signed) {
$redirectUrl .= '&auth_data_sig=' . urlencode($signed);
}
}
// Create a short-lived server-side token the partner can exchange for the payload
// (useful for keeping sensitive tokens off of URLs / client logs)
$serverToken = create_server_token($returnData, $displayOrigin ?? $originDomain ?? null);
if ($serverToken) {
$redirectUrl .= '&server_token=' . urlencode($serverToken);
}
}
}
// Handle OAuth errors
if (isset($_GET['error'])) {
$error = $_GET['error'];
$errorDescription = $_GET['error_description'] ?? 'Unknown error';
$returnUrl = $_SESSION['return_url'] ?? null;
$displayOrigin = $_SESSION['origin_domain'] ?? null;
$service = $_SESSION['auth_service'] ?? 'unknown';
$requestedScopes = $_SESSION['requested_scopes'] ?? '';
// Log failed authentication
if ($displayOrigin) {
scLogAuthAttempt($service, $displayOrigin, [], $requestedScopes, false, $errorDescription);
dispatch_webhooks($service, $displayOrigin, [], 'authentication_failure');
}
// Set error state for display
$authError = true;
$errorMessage = match($error) {
'access_denied' => 'Authentication was canceled or denied.',
'invalid_request' => 'Invalid authentication request.',
'unauthorized_client' => 'Unauthorized client application.',
'server_error' => 'Server error occurred during authentication.',
default => htmlspecialchars($errorDescription)
};
// If we have a return URL, we'll redirect after showing error for a moment
if ($returnUrl) {
$separator = strpos($returnUrl, '?') !== false ? '&' : '?';
$redirectUrl = $returnUrl . $separator . 'error=' . urlencode($error) . '&error_description=' . urlencode($errorDescription);
}
}
/**
* Exchange Twitch authorization code for access token
*/
function exchangeTwitchCodeForToken($code, $customClientId = null, $customClientSecret = null) {
// Use custom credentials if provided, otherwise get from database
if (!$customClientId || !$customClientSecret) {
$credentials = getDefaultOAuthCredentials('twitch', $_SESSION['user_id'] ?? null);
if ($credentials) {
$customClientId = $customClientId ?? $credentials['client_id'];
$customClientSecret = $customClientSecret ?? $credentials['client_secret'];
}
}
$tokenUrl = 'https://id.twitch.tv/oauth2/token';
$postData = [
'client_id' => $customClientId ?? TWITCH_CLIENT_ID,
'client_secret' => $customClientSecret ?? TWITCH_CLIENT_SECRET,
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => REDIRECT_URI
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
error_log('Twitch token exchange failed: ' . $response);
return false;
}
return json_decode($response, true);
}
/**
* Get user data from Twitch API
*/
function getTwitchUserData($accessToken, $customClientId = null) {
// Use custom client ID if provided, otherwise get from database
if (!$customClientId) {
$credentials = getDefaultOAuthCredentials('twitch', $_SESSION['user_id'] ?? null);
if ($credentials) {
$customClientId = $credentials['client_id'];
}
}
$userUrl = 'https://api.twitch.tv/helix/users';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $userUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Client-Id: ' . ($customClientId ?? TWITCH_CLIENT_ID)
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
error_log('Twitch user data fetch failed: ' . $response);
return false;
}
$data = json_decode($response, true);
return $data['data'][0] ?? false;
}
/**
* Exchange Discord authorization code for access token
*/
function exchangeDiscordCodeForToken($code, $customClientId = null, $customClientSecret = null) {
// Use custom credentials if provided, otherwise get from database
if (!$customClientId || !$customClientSecret) {
$credentials = getDefaultOAuthCredentials('discord', $_SESSION['user_id'] ?? null);
if ($credentials) {
$customClientId = $customClientId ?? $credentials['client_id'];
$customClientSecret = $customClientSecret ?? $credentials['client_secret'];
}
}
$tokenUrl = 'https://discord.com/api/oauth2/token';
$postData = [
'client_id' => $customClientId ?? DISCORD_CLIENT_ID,
'client_secret' => $customClientSecret ?? DISCORD_CLIENT_SECRET,
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => REDIRECT_URI
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
error_log('Discord token exchange failed: ' . $response);
return false;
}
return json_decode($response, true);
}
/**
* Get user data from Discord API
*/
function getDiscordUserData($accessToken) {
$userUrl = 'https://discord.com/api/users/@me';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $userUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
error_log('Discord user data fetch failed: ' . $response);
return false;
}
$userData = json_decode($response, true);
// Normalize Discord user data to match expected format
return [
'id' => $userData['id'],
'login' => $userData['username'],
'display_name' => $userData['global_name'] ?? $userData['username'],
'email' => $userData['email'] ?? null,
'profile_image_url' => $userData['avatar'] ? "https://cdn.discordapp.com/avatars/{$userData['id']}/{$userData['avatar']}.png" : null,
'broadcaster_type' => '' // Discord doesn't have this concept
];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Processing Authentication...</title>
<link rel="icon" href="https://cdn.yourstreamingtools.com/img/logo.ico">
<link rel="apple-touch-icon" href="https://cdn.yourstreamingtools.com/img/logo.ico">
<link rel="stylesheet" href="custom.css">
</head>
<body>
<div class="loader">
<?php if (isset($authError) && $authError): ?>
<div class="error-icon">✖</div>
<h2>Authentication Failed</h2>
<p><?php echo $errorMessage; ?></p>
<?php if (isset($redirectUrl) && isset($displayOrigin)): ?>
<p class="redirect-note">Redirecting back to <strong><?php echo htmlspecialchars($displayOrigin); ?></strong> in <span id="countdown">5</span> seconds...</p>
<?php else: ?>
<p class="mt-2rem">Please close this window and try again.</p>
<?php endif; ?>
<?php elseif (isset($redirectUrl)): ?>
<div class="spinner"></div>
<h2>Authentication Successful!</h2>
<?php if (isset($displayOrigin)): ?>
<p>Redirecting you back to <strong><?php echo htmlspecialchars($displayOrigin); ?></strong>...</p>
<?php else: ?>
<p>Redirecting you back to your service...</p>
<?php endif; ?>
<?php else: ?>
<div class="spinner"></div>
<h2>Processing Authentication...</h2>
<p>Please wait while we redirect you back to your service.</p>
<?php endif; ?>
</div>
<?php if (isset($redirectUrl)): ?>
<script>
<?php if (isset($authError) && $authError): ?>
// Error redirect with countdown
let countdown = 5;
const countdownEl = document.getElementById('countdown');
const timer = setInterval(function() {
countdown--;
if (countdownEl) countdownEl.textContent = countdown;
if (countdown <= 0) {
clearInterval(timer);
window.location.href = <?php echo json_encode($redirectUrl); ?>;
}
}, 1000);
<?php else: ?>
// Success redirect
setTimeout(function() {
window.location.href = <?php echo json_encode($redirectUrl); ?>;
}, 2000);
<?php endif; ?>
</script>
<?php endif; ?>
</body>
</html>