v3
This commit is contained in:
parent
80d945cbf3
commit
3278daef55
62
auth.php
Normal file
62
auth.php
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
<?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);
|
||||||
|
?>
|
||||||
29
firebase-service-account.json
Normal file
29
firebase-service-account.json
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
{ "type": "service_account", "project_id": "dululu-fe617", "private_key_id": "f994dbe9213123675911cb1556e73579f9a2d5b0", "private_key": "-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDIakeW+EiZZZXx
|
||||||
|
sbJ2NTkXDk6zbiyUHb3XGsVzfgaTVRIjltV6aFJLKa9qz/hHvUAZn0sr0o95gz+8
|
||||||
|
B1bBLVTABS54Sx1flhcCbVIFCZ9s25yDbV2OvL22QG1RjrhUoTMwvLaAW43kud77
|
||||||
|
OzS3tlL4pDiv+77jE17fC96VfTlmpRzpIJWdEdMN87UZlsnSdXh7Gp0U0+s6bnTv
|
||||||
|
5YuB5L38dxPYcsze7s/cbcm1S5sW1eCDWmlX+V4l77AgzJ4RzMoRxGqoN5tykzHR
|
||||||
|
wRnaX+yu60SkN4rXgubfZdIkT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GARawr
|
||||||
|
80EmeMgv7bCKl+iCXf2MwCEZhINFvvGoE5daGPXHzu4dsHAqCeehYwtwu4KkZUnE
|
||||||
|
z4bY8fMAQ6PRtd8fFAxEm88LB4llNY9klI6ZXexpilOfVf4V3vi0NSWkiEMJlvwm
|
||||||
|
D+qVwUeSjRcS+67LgGN206TURfUK49K3E8H1uZMCgYBRXJd64BKViLPUFUJBdmz8
|
||||||
|
NHKrnGQiVo57NLx/eXvvvI3/Yd3AGkUdapgkT2sCTHh9aoczgHXcjmlIcho1Q5Jz
|
||||||
|
0fkUZkjFwuSn5XjPyVDipHA46M+UqHXZ7E88TNisXTzZApj2YhlgUQNQfR8wCDup
|
||||||
|
Ccwcz12GqS1ZWpK9SoWAFw==
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
|
", "client_email": "firebase-adminsdk-fbsvc @dululu-fe617.iam.gserviceaccount.com", "client_id": "104495485400716482072", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40dululu-fe617.iam.gserviceaccount.com", "universe_domain": "googleapis.com" }
|
||||||
15
includes/firebase_config.php
Normal file
15
includes/firebase_config.php
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
// firebase_config.php
|
||||||
|
// This file will hold your Firebase project configuration.
|
||||||
|
// You need to replace the placeholder values with your actual Firebase project settings.
|
||||||
|
// You can find these values in your Firebase project console under Project settings -> General -> Your apps.
|
||||||
|
|
||||||
|
return [
|
||||||
|
'apiKey' => 'AIzaSyCwEATlIVGKEvm-Ph1oH0-fOySmx7hBYkg',
|
||||||
|
'authDomain' => 'dululu-fe617.firebaseapp.com',
|
||||||
|
'projectId' => 'dululu-fe617',
|
||||||
|
'storageBucket' => 'dululu-fe617.firebasestorage.app',
|
||||||
|
'messagingSenderId' => '553086833572',
|
||||||
|
'appId' => '1:553086833572:web:2536751230886bd8552731',
|
||||||
|
'measurementId' => 'G-5DJ9LXGSZZ' // Optional, if you use Google Analytics for Firebase
|
||||||
|
];
|
||||||
92
index.php
92
index.php
@ -1,6 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
require_once __DIR__ . '/db/config.php';
|
require_once __DIR__ . '/db/config.php';
|
||||||
|
require_once __DIR__ . '/includes/firebase_config.php';
|
||||||
|
|
||||||
|
$firebaseConfig = require __DIR__ . '/includes/firebase_config.php';
|
||||||
|
|
||||||
$delulus = [];
|
$delulus = [];
|
||||||
try {
|
try {
|
||||||
@ -39,6 +42,90 @@ $projectTitle = 'Delulu is the New Sululu';
|
|||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
|
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
|
||||||
|
|
||||||
|
<script type="module">
|
||||||
|
// Import the functions you need from the SDKs you need
|
||||||
|
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
|
||||||
|
import { getAuth, GoogleAuthProvider, signInWithPopup, signOut, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";
|
||||||
|
// TODO: Add SDKs for Firebase products that you want to use
|
||||||
|
// https://firebase.google.com/docs/web/setup#available-libraries
|
||||||
|
|
||||||
|
// Your web app's Firebase configuration
|
||||||
|
const firebaseConfig = <?= json_encode($firebaseConfig) ?>;
|
||||||
|
|
||||||
|
// Initialize Firebase
|
||||||
|
const app = initializeApp(firebaseConfig);
|
||||||
|
const auth = getAuth(app);
|
||||||
|
const provider = new GoogleAuthProvider();
|
||||||
|
|
||||||
|
const authUi = document.getElementById('auth-ui');
|
||||||
|
const signInButton = document.getElementById('signInButton');
|
||||||
|
|
||||||
|
// Update UI based on auth state
|
||||||
|
onAuthStateChanged(auth, (user) => {
|
||||||
|
if (user) {
|
||||||
|
// User is signed in
|
||||||
|
authUi.innerHTML = `
|
||||||
|
<span class="navbar-text me-3">Welcome, \${user.displayName}</span>
|
||||||
|
<button id="signOutButton" class="btn btn-outline-danger">Sign Out</button>
|
||||||
|
`;
|
||||||
|
document.getElementById('signOutButton').addEventListener('click', () => {
|
||||||
|
signOut(auth).then(() => {
|
||||||
|
// Sign-out successful.
|
||||||
|
console.log('User signed out');
|
||||||
|
}).catch((error) => {
|
||||||
|
// An error happened.
|
||||||
|
console.error('Sign out error:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// After successful sign-in, send ID token to backend for session management
|
||||||
|
user.getIdToken().then(idToken => {
|
||||||
|
fetch('auth.php', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ idToken: idToken, action: 'signin' }),
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.status === 'success') {
|
||||||
|
console.log('Backend session established:', data.message);
|
||||||
|
} else {
|
||||||
|
console.error('Backend session error:', data.message);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Error sending token to backend:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// User is signed out
|
||||||
|
authUi.innerHTML = `<button id="signInButton" class="btn btn-primary">Sign in with Google</button>`;
|
||||||
|
document.getElementById('signInButton').addEventListener('click', () => {
|
||||||
|
signInWithPopup(auth, provider)
|
||||||
|
.then((result) => {
|
||||||
|
// This gives you a Google Access Token. You can use it to access the Google API.
|
||||||
|
const credential = GoogleAuthProvider.credentialFromResult(result);
|
||||||
|
const token = credential.accessToken;
|
||||||
|
// The signed-in user info.
|
||||||
|
const user = result.user;
|
||||||
|
console.log('User signed in:', user.displayName);
|
||||||
|
}).catch((error) => {
|
||||||
|
// Handle Errors here.
|
||||||
|
const errorCode = error.code;
|
||||||
|
const errorMessage = error.message;
|
||||||
|
// The email of the user's account used.
|
||||||
|
const email = error.customData.email;
|
||||||
|
// The AuthCredential type that was used.
|
||||||
|
const credential = GoogleAuthProvider.credentialFromError(error);
|
||||||
|
console.error('Sign-in error:', errorMessage);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
@ -50,8 +137,9 @@ $projectTitle = 'Delulu is the New Sululu';
|
|||||||
</button>
|
</button>
|
||||||
<div class="collapse navbar-collapse" id="navbarNav">
|
<div class="collapse navbar-collapse" id="navbarNav">
|
||||||
<ul class="navbar-nav ms-auto">
|
<ul class="navbar-nav ms-auto">
|
||||||
<li class="nav-item">
|
<li class="nav-item" id="auth-ui">
|
||||||
<a class="btn btn-primary" href="#">Sign in with Google</a>
|
<!-- Authentication UI will be rendered here -->
|
||||||
|
<button id="signInButton" class="btn btn-primary">Sign in with Google</button>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user