63 lines
2.5 KiB
PHP
63 lines
2.5 KiB
PHP
<?php
|
|
session_start();
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
require __DIR__ . '/vendor/autoload.php'; // Composer Autoloader
|
|
|
|
use Kreait\Firebase\Factory;
|
|
use Kreait\Firebase\Exception\Auth\InvalidToken;
|
|
|
|
$response = ['status' => 'error', 'message' => 'Invalid request'];
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
$action = $input['action'] ?? '';
|
|
$idToken = $input['idToken'] ?? '';
|
|
|
|
// Initialize Firebase Admin SDK
|
|
// IMPORTANT: Replace 'path/to/your/serviceAccountKey.json' with the actual path to your Firebase service account key file.
|
|
// This file contains your project's credentials and should be kept secure.
|
|
// You can download it from Firebase Console -> Project settings -> Service accounts -> Generate new private key.
|
|
try {
|
|
$factory = (new Factory())->withServiceAccount(__DIR__ . '/firebase-service-account.json');
|
|
$auth = $factory->createAuth();
|
|
} catch (\Exception $e) {
|
|
error_log('Firebase Admin SDK initialization error: ' . $e->getMessage());
|
|
$response = ['status' => 'error', 'message' => 'Server configuration error.'];
|
|
echo json_encode($response);
|
|
exit;
|
|
}
|
|
|
|
|
|
if ($action === 'signin' && !empty($idToken)) {
|
|
try {
|
|
$verifiedIdToken = $auth->verifyIdToken($idToken);
|
|
$uid = $verifiedIdToken->claims()->get('sub');
|
|
$email = $verifiedIdToken->claims()->get('email');
|
|
$displayName = $verifiedIdToken->claims()->get('name');
|
|
|
|
$_SESSION['user_id'] = $uid;
|
|
$_SESSION['user_email'] = $email;
|
|
$_SESSION['user_name'] = $displayName;
|
|
$_SESSION['is_logged_in'] = true;
|
|
|
|
$response = ['status' => 'success', 'message' => 'Sign-in successful.', 'user' => ['uid' => $uid, 'email' => $email, 'name' => $displayName]];
|
|
} catch (InvalidToken $e) {
|
|
$response = ['status' => 'error', 'message' => 'Invalid Firebase ID token.'];
|
|
error_log('Firebase ID token verification failed: ' . $e->getMessage());
|
|
} catch (\Exception $e) {
|
|
$response = ['status' => 'error', 'message' => 'Authentication failed.'];
|
|
error_log('General authentication error: ' . $e->getMessage());
|
|
}
|
|
} else if ($action === 'signout') {
|
|
session_unset();
|
|
session_destroy();
|
|
$response = ['status' => 'success', 'message' => 'Sign-out successful. Session destroyed.'];
|
|
}
|
|
}
|
|
|
|
echo json_encode($response);
|
|
?>
|