📄 Source: oauth-callback.php
<?php
require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
$provider = $_GET['provider'] ?? '';
$code = $_GET['code'] ?? '';
$error = $_GET['error'] ?? '';
$state = $_GET['state'] ?? '';
if ($error) {
header('Location: login.php?error=' . urlencode($error));
exit();
}
if (empty($code)) {
header('Location: login.php?error=No authorization code received');
exit();
}
// Check if this is a linking request
$isLinking = ($state === 'link');
if ($provider === 'discord') {
// ============ DISCORD OAUTH ============
$tokenData = [
'client_id' => DISCORD_CLIENT_ID,
'client_secret' => DISCORD_CLIENT_SECRET,
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => DISCORD_REDIRECT_URI,
];
$ch = curl_init('https://discord.com/api/oauth2/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tokenData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$token = json_decode($response, true);
if (!isset($token['access_token'])) {
$errorMsg = $token['error'] ?? 'unknown error';
header('Location: login.php?error=Discord: ' . urlencode($errorMsg));
exit();
}
$ch = curl_init('https://discord.com/api/users/@me');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token['access_token']
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$userData = json_decode($response, true);
if (!isset($userData['id'])) {
header('Location: login.php?error=Failed to get Discord user data');
exit();
}
// Check if this Discord ID is already linked
$existingUser = getUserByDiscordId($userData['id']);
if ($isLinking) {
// ACCOUNT LINKING MODE
if (!isLoggedIn()) {
header('Location: login.php?error=You must be logged in to link accounts');
exit();
}
$currentUser = getCurrentUser();
if ($existingUser && $existingUser['id'] !== $currentUser['id']) {
header('Location: profile.php?error=This Discord account is already linked to another user');
exit();
}
// Link Discord to current account
updateUser($currentUser['id'], [
'discord_id' => $userData['id'],
'discord_data' => json_encode($userData)
]);
header('Location: profile.php?success=Discord account linked successfully!');
exit();
} else {
// NORMAL LOGIN MODE
if ($existingUser) {
loginUser($existingUser['id']);
header('Location: index.php?success=Logged in with Discord');
exit();
} else {
// Check if user exists with same username
$existingLocalUser = getUserByUsername($userData['username']);
if ($existingLocalUser) {
// Link Discord to existing account
updateUser($existingLocalUser['id'], [
'discord_id' => $userData['id'],
'discord_data' => json_encode($userData)
]);
loginUser($existingLocalUser['id']);
header('Location: index.php?success=Discord linked to your account');
exit();
} else {
// Create new user
$username = $userData['username'];
$baseUsername = $username;
$counter = 1;
while (getUserByUsername($username)) {
$username = $baseUsername . $counter;
$counter++;
}
$userId = createUser(
$username,
null,
$userData['id'],
null,
json_encode($userData)
);
if ($userId) {
loginUser($userId);
header('Location: index.php?success=Account created with Discord');
exit();
} else {
header('Location: login.php?error=Failed to create account');
exit();
}
}
}
}
} elseif ($provider === 'google') {
// ============ GOOGLE OAUTH ============
$tokenData = [
'client_id' => GOOGLE_CLIENT_ID,
'client_secret' => GOOGLE_CLIENT_SECRET,
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => GOOGLE_REDIRECT_URI,
];
$ch = curl_init('https://oauth2.googleapis.com/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tokenData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$token = json_decode($response, true);
if (!isset($token['access_token'])) {
$errorMsg = $token['error'] ?? 'unknown error';
header('Location: login.php?error=Google: ' . urlencode($errorMsg));
exit();
}
$ch = curl_init('https://www.googleapis.com/oauth2/v2/userinfo');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token['access_token']
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$userData = json_decode($response, true);
if (!isset($userData['id'])) {
header('Location: login.php?error=Failed to get Google user data');
exit();
}
$existingUser = getUserByGoogleId($userData['id']);
if ($isLinking) {
// ACCOUNT LINKING MODE
if (!isLoggedIn()) {
header('Location: login.php?error=You must be logged in to link accounts');
exit();
}
$currentUser = getCurrentUser();
if ($existingUser && $existingUser['id'] !== $currentUser['id']) {
header('Location: profile.php?error=This Google account is already linked to another user');
exit();
}
// Link Google to current account
updateUser($currentUser['id'], [
'google_id' => $userData['id']
]);
header('Location: profile.php?success=Google account linked successfully!');
exit();
} else {
// NORMAL LOGIN MODE
if ($existingUser) {
loginUser($existingUser['id']);
header('Location: index.php?success=Logged in with Google');
exit();
} else {
// Check if user exists with same email
$existingLocalUser = getUserByUsername($userData['email']);
if ($existingLocalUser) {
// Link Google to existing account
updateUser($existingLocalUser['id'], [
'google_id' => $userData['id']
]);
loginUser($existingLocalUser['id']);
header('Location: index.php?success=Google linked to your account');
exit();
} else {
// Create new user
$username = explode('@', $userData['email'])[0];
$baseUsername = $username;
$counter = 1;
while (getUserByUsername($username)) {
$username = $baseUsername . $counter;
$counter++;
}
$userId = createUser(
$username,
null,
null,
$userData['id']
);
if ($userId) {
loginUser($userId);
header('Location: index.php?success=Account created with Google');
exit();
} else {
header('Location: login.php?error=Failed to create account');
exit();
}
}
}
}
} else {
header('Location: login.php?error=Invalid provider');
exit();
}
?>
← Back