1
0
mirror of https://github.com/chinchang/web-maker.git synced 2025-07-23 06:51:12 +02:00

make auth work with correct provider

This commit is contained in:
Kushagra Gour
2024-05-09 16:44:28 +05:30
parent 71582cf608
commit 3482fabefd
5 changed files with 70 additions and 58 deletions

View File

@@ -1,3 +1,2 @@
<!doctype html>
<audio></audio>
<script src="./offscreen.js"></script>

View File

@@ -24,6 +24,7 @@ function handleChromeMessages(message, sender, sendResponse) {
data = JSON.parse(data);
self.removeEventListener('message', handleIframeMessage);
// being sent back to worker
sendResponse(data);
} catch (e) {
console.log(`json parse failed - ${e.message}`);
@@ -35,6 +36,9 @@ function handleChromeMessages(message, sender, sendResponse) {
// Initialize the authentication flow in the iframed document. You must set the
// second argument (targetOrigin) of the message in order for it to be successfully
// delivered.
iframe.contentWindow.postMessage({ initAuth: true }, new URL(_URL).origin);
iframe.contentWindow.postMessage(
{ initAuth: true, providerName: message.providerName },
new URL(_URL).origin
);
return true;
}

View File

@@ -1,9 +1,9 @@
setTimeout(() => {
console.log('firing postmessag from iframe');
// window.top.postMessage('{"a":2}', "*");
}, 3000);
import { signInWithPopup, GoogleAuthProvider, getAuth } from 'firebase/auth';
import {
signInWithPopup,
GithubAuthProvider,
GoogleAuthProvider,
getAuth
} from 'firebase/auth';
import { initializeApp } from 'firebase/app';
import { config } from './firebaseConfig.js';
@@ -15,21 +15,25 @@ const auth = getAuth();
// You will need this to assign the targetOrigin for postMessage.
const PARENT_FRAME = document.location.ancestorOrigins[0];
// This demo uses the Google auth provider, but any supported provider works.
// Make sure that you enable any provider you want to use in the Firebase Console.
// https://console.firebase.google.com/project/_/authentication/providers
const PROVIDER = new GoogleAuthProvider();
function sendResponse(result) {
globalThis.parent.self.postMessage(JSON.stringify(result), PARENT_FRAME);
}
globalThis.addEventListener('message', function ({ data }) {
if (data.initAuth) {
const { providerName } = data;
let provider;
if (providerName === 'google') {
provider = new GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/userinfo.profile');
} else {
provider = new GithubAuthProvider();
}
// Opens the Google sign-in page in a popup, inside of an iframe in the
// extension's offscreen document.
// To centralize logic, all respones are forwarded to the parent frame,
// which goes on to forward them to the extension's service worker.
signInWithPopup(auth, PROVIDER).then(sendResponse).catch(sendResponse);
signInWithPopup(auth, provider).then(sendResponse).catch(sendResponse);
}
});

View File

@@ -1,57 +1,59 @@
import { trackEvent } from './analytics';
import { auth } from './firebaseInit';
import { log } from './utils';
import {
GithubAuthProvider,
TwitterAuthProvider,
GoogleAuthProvider,
signInWithPopup,
signOut
} from 'firebase/auth';
import { log } from './utils';
import { signInWithCredential } from 'firebase/auth/web-extension';
signOut,
signInWithCredential
} from 'firebase/auth/web-extension';
export const authh = {
logout() {
signOut();
signOut(auth);
},
async login(providerName) {
debugger;
const authenticationObject = await chrome.runtime.sendMessage({
const result = await chrome.runtime.sendMessage({
type: 'firebase-auth',
provider: providerName
providerName
});
const credential =
GoogleAuthProvider.credentialFromResult(authenticationObject);
// authenticationObject is of the type UserCredentialImpl. Use it to authenticate here
return signInWithCredential(auth, credential);
var provider;
if (providerName === 'facebook') {
provider = new FacebookAuthProvider();
} else if (providerName === 'twitter') {
provider = new TwitterAuthProvider();
} else if (providerName === 'google') {
provider = new GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/userinfo.profile');
} else {
provider = new GithubAuthProvider();
if (
result.name === 'FirebaseError' &&
result.code === 'auth/account-exists-with-different-credential'
) {
alert(
'You have already signed up with the same email using different social login'
);
return;
}
return signInWithPopup(auth, provider)
.then(function () {
trackEvent('fn', 'loggedIn', providerName);
// Save to recommend next time
window.db.local.set({
lastAuthProvider: providerName
});
})
.catch(function (error) {
log(error);
if (error.code === 'auth/account-exists-with-different-credential') {
alert(
'You have already signed up with the same email using different social login'
);
}
let credential;
switch (providerName) {
case 'google':
credential = GoogleAuthProvider.credentialFromResult(result);
break;
case 'github':
credential = GithubAuthProvider.credentialFromResult(result);
break;
}
// authenticationObject is of the type UserCredentialImpl. Use it to authenticate here
return signInWithCredential(auth, credential).then(() => {
trackEvent('fn', 'loggedIn', providerName);
// Save to recommend next time
window.db.local.set({
lastAuthProvider: providerName
});
});
return signInWithPopup(auth, provider).catch(function (error) {
log(error);
if (error.code === 'auth/account-exists-with-different-credential') {
alert(
'You have already signed up with the same email using different social login'
);
}
});
}
};

View File

@@ -79,20 +79,22 @@ async function closeOffscreenDocument() {
await chrome.offscreen.closeDocument();
}
function getAuth() {
function getAuth(providerName) {
return new Promise(async (resolve, reject) => {
// sending to offscreen document
const auth = await chrome.runtime.sendMessage({
type: 'firebase-auth',
target: 'offscreen'
target: 'offscreen',
providerName
});
auth?.name !== 'FirebaseError' ? resolve(auth) : reject(auth);
});
}
async function firebaseAuth() {
async function firebaseAuth(providerName) {
await setupOffscreenDocument(OFFSCREEN_DOCUMENT_PATH);
const auth = await getAuth()
const auth = await getAuth(providerName)
.then(auth => {
console.log('User Authenticated', auth);
return auth;
@@ -115,8 +117,9 @@ async function firebaseAuth() {
}
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
// received from the app
if (message.type === 'firebase-auth') {
firebaseAuth().then(sendResponse);
firebaseAuth(message.providerName).then(sendResponse);
return true;
}
});