import type { PlasmoMessaging } from "@plasmohq/messaging"
import {
GoogleAuthProvider,
signInWithCredential,
signOut,
} from "firebase/auth";
import { app, auth } from "~firebase";
const handleSignIn = async (request, sender) => {
try {
const redirectUri = chrome.identity.getRedirectURL();
const clientId = process.env.PLASMO_PUBLIC_FIREBASE_CLIENT_ID
const authUrl = `https://accounts.google.com/o/oauth2/auth?client_id=${clientId}&response_type=token&redirect_uri=${encodeURIComponent(redirectUri)}&scope=email openid profile`;
return new Promise((resolve, reject) => {
chrome.identity.launchWebAuthFlow({
url: authUrl,
interactive: true,
}, (redirectUrl) => {
if (chrome.runtime.lastError || !redirectUrl) {
reject(new Error("WebAuthFlow failed: " + chrome.runtime.lastError.message));
return;
}
const params = new URLSearchParams(new URL(redirectUrl).hash.substring(1));
const accessToken = params.get('access_token');
const credential = GoogleAuthProvider.credential(null, accessToken);
signInWithCredential(auth, credential).then((userCredential) => {
resolve(userCredential.user);
}).catch((error) => {
reject(new Error("Firebase signInWithCredential failed: " + error.message));
});
});
});
} catch (e) {
throw new Error("Sign-in failed: " + e.message);
}
};
const handleSignOut = async (request, sender) => {
try {
await signOut(auth);
return "Signed out successfully.";
} catch (e) {
throw new Error("Sign-out failed: " + e.message);
}
};
const getUser = async (request, sender) => {
return auth.currentUser;
}