1
0
mirror of https://github.com/chinchang/web-maker.git synced 2025-10-17 06:26:08 +02:00

get auth working with offscreen document

This commit is contained in:
Kushagra Gour
2024-05-09 15:41:41 +05:30
parent 2289af6a0b
commit 71582cf608
13 changed files with 7368 additions and 24 deletions

View File

@@ -8,12 +8,23 @@ import {
signOut
} from 'firebase/auth';
import { log } from './utils';
import { signInWithCredential } from 'firebase/auth/web-extension';
export const authh = {
logout() {
signOut();
},
login(providerName) {
async login(providerName) {
debugger;
const authenticationObject = await chrome.runtime.sendMessage({
type: 'firebase-auth',
provider: 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();

View File

@@ -1,7 +1,17 @@
// import './firebaseInit';
import 'firebase/firestore';
import { db } from './firebaseInit';
import { getDoc, getDocs, doc, updateDoc, setDoc } from 'firebase/firestore';
import {
getDoc,
getDocs,
doc,
updateDoc,
setDoc,
where,
collection,
getCountFromServer,
query
} from 'firebase/firestore';
import { deferred } from './deferred';
import { trackEvent } from './analytics';
import { log } from './utils';
@@ -159,14 +169,11 @@ function getArrayFromQuerySnapshot(querySnapshot) {
async function fetchItem(itemId) {
const remoteDb = await getDb();
return remoteDb
.doc(`items/${itemId}`)
.get()
.then(doc => {
if (!doc.exists) return {};
const data = doc.data();
return data;
});
getDoc(doc(remoteDb, `items/${itemId}`)).then(doc => {
if (!doc.exists) return {};
const data = doc.data();
return data;
});
}
// Fetch user settings.
@@ -184,23 +191,23 @@ function getArrayFromQuerySnapshot(querySnapshot) {
async function getPublicItemCount(userId) {
const remoteDb = await getDb();
return remoteDb
.collection('items')
.where('createdBy', '==', userId)
.where('isPublic', '==', true)
.get()
.then(snapShot => {
return snapShot.size;
});
const q = query(
collection(remoteDb, 'items'),
where('createdBy', '==', userId),
where('isPublic', '==', true)
);
const snapshot = await getCountFromServer(q);
return snapshot.data().count;
}
async function getUserSubscriptionEvents(userId) {
const remoteDb = await getDb();
return remoteDb
.collection('subscriptions')
.where('userId', '==', userId)
.get()
.then(getArrayFromQuerySnapshot);
const q = query(
collection(remoteDb, 'subscriptions'),
where('userId', '==', userId)
);
return getDocs(q).then(getArrayFromQuerySnapshot);
}
window.db = {

View File

@@ -45,3 +45,78 @@ chrome.runtime.onInstalled.addListener(function callback(details) {
}
}
});
const OFFSCREEN_DOCUMENT_PATH = '/offscreen.html';
// A global promise to avoid concurrency issues
let creatingOffscreenDocument;
// Chrome only allows for a single offscreenDocument. This is a helper function
// that returns a boolean indicating if a document is already active.
async function hasDocument() {
// Check all windows controlled by the service worker to see if one
// of them is the offscreen document with the given path
const matchedClients = await clients.matchAll();
return matchedClients.some(
c => c.url === chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH)
);
}
async function setupOffscreenDocument(path) {
// If we do not have a document, we are already setup and can skip
if (await chrome.offscreen.hasDocument()) return;
await chrome.offscreen.createDocument({
url: path,
reasons: [chrome.offscreen.Reason.DOM_SCRAPING],
justification: 'authentication'
});
}
async function closeOffscreenDocument() {
if (!(await hasDocument())) {
return;
}
await chrome.offscreen.closeDocument();
}
function getAuth() {
return new Promise(async (resolve, reject) => {
const auth = await chrome.runtime.sendMessage({
type: 'firebase-auth',
target: 'offscreen'
});
auth?.name !== 'FirebaseError' ? resolve(auth) : reject(auth);
});
}
async function firebaseAuth() {
await setupOffscreenDocument(OFFSCREEN_DOCUMENT_PATH);
const auth = await getAuth()
.then(auth => {
console.log('User Authenticated', auth);
return auth;
})
.catch(err => {
if (err.code === 'auth/operation-not-allowed') {
console.error(
'You must enable an OAuth provider in the Firebase' +
' console in order to use signInWithPopup. This sample' +
' uses Google by default.'
);
} else {
console.error(err);
return err;
}
})
.finally(closeOffscreenDocument);
return auth;
}
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.type === 'firebase-auth') {
firebaseAuth().then(sendResponse);
return true;
}
});

View File

@@ -4,7 +4,7 @@
"manifest_version": 3,
"description": "Blazing fast & offline playground for your web experiments",
"homepage_url": "https://webmaker.app",
"permissions": ["storage", "tabs"],
"permissions": ["storage", "tabs", "offscreen"],
"optional_permissions": ["downloads"],
"host_permissions": ["<all_urls>"],
"content_security_policy": {
@@ -26,6 +26,8 @@
"service_worker": "eventPage.js",
"type": "module"
},
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp4s9naKH2y92qItJCcj3deRGjjqhDfgUR2WDe34IEYEB4PGtmx/9IO4PaO49gMr82DBRuwxCg/vr9SyiVlG1/j0TApJlkaHVsRZE4EME2rbL1vzIQRE8gNB+b5L6rPl4GPX/eFqIuUe/UgQPZAadLBVxdwBdOv5ou8OY0jrLx/h0wcLVvk9d8/ELpk28Hb2LArCBd+vIngHK55Db1GMEGAyNUVzFCTg/MZ7w5fKLpA94mF2X0/Bv9sCjj7vDir24Mp5Z/Y3obTHvpzddppAE6ZEQ3fmpRkOJ3MbuaKYm9hNHs4az6XLW6Sdlv2YcIcCfvsev/WEKUZeD8KIRtRyyPQIDAQAB",
"icons": {
"16": "icon-16.png",
"48": "icon-48.png"