একটি Chrome এক্সটেনশনে Firebase দিয়ে প্রমাণীকরণ করুন

ম্যানিফেস্ট V3 ব্যবহার করে এমন একটি Chrome এক্সটেনশনে ব্যবহারকারীদের সাইন ইন করতে Firebase প্রমাণীকরণ কীভাবে ব্যবহার করবেন এই নথিটি আপনাকে দেখায়।

Firebase প্রমাণীকরণ একটি Chrome এক্সটেনশন থেকে ব্যবহারকারীদের সাইন ইন করার জন্য একাধিক প্রমাণীকরণ পদ্ধতি প্রদান করে, কিছুর জন্য অন্যদের তুলনায় আরও বেশি উন্নয়ন প্রচেষ্টা প্রয়োজন।

একটি ম্যানিফেস্ট V3 ক্রোম এক্সটেনশনে নিম্নলিখিত পদ্ধতিগুলি ব্যবহার করতে, আপনাকে শুধুমাত্র firebase/auth/web-extension থেকে সেগুলি আমদানি করতে হবে:

  • ইমেল এবং পাসওয়ার্ড দিয়ে সাইন ইন করুন ( createUserWithEmailAndPassword এবং signInWithEmailAndPassword )
  • ইমেল লিঙ্ক দিয়ে সাইন ইন করুন ( sendSignInLinkToEmail , isSignInWithEmailLink , এবং signInWithEmailLink )
  • বেনামে সাইন ইন করুন ( signInAnonymously )
  • একটি কাস্টম প্রমাণীকরণ সিস্টেমের সাথে সাইন ইন করুন ( signInWithCustomToken )
  • প্রদানকারীর সাইন-ইন স্বাধীনভাবে পরিচালনা করুন তারপর signInWithCredential ব্যবহার করুন

নিম্নলিখিত সাইন ইন পদ্ধতিগুলিও সমর্থিত কিন্তু কিছু অতিরিক্ত কাজের প্রয়োজন:

  • একটি পপ-আপ উইন্ডো দিয়ে সাইন ইন করুন ( signInWithPopup , linkWithPopup , এবং reauthenticateWithPopup )
  • সাইন-ইন পৃষ্ঠায় পুনঃনির্দেশ করে সাইন ইন করুন ( signInWithRedirect , linkWithRedirect , এবং reauthenticateWithRedirect )
  • reCAPTCHA দিয়ে ফোন নম্বর দিয়ে সাইন ইন করুন
  • reCAPTCHA সহ SMS মাল্টি-ফ্যাক্টর প্রমাণীকরণ
  • reCAPTCHA এন্টারপ্রাইজ সুরক্ষা

ম্যানিফেস্ট V3 ক্রোম এক্সটেনশনে এই পদ্ধতিগুলি ব্যবহার করতে, আপনাকে অবশ্যই অফস্ক্রিন ডকুমেন্টস ব্যবহার করতে হবে।

Firebase/auth/web-extension এন্ট্রি পয়েন্ট ব্যবহার করুন

firebase/auth/web-extension থেকে আমদানি করা একটি Chrome এক্সটেনশন থেকে ব্যবহারকারীদের সাইন ইন করা একটি ওয়েব অ্যাপের মতো করে।

firebase/auth/web-extension শুধুমাত্র ওয়েব SDK সংস্করণ v10.8.0 এবং তার উপরে সমর্থিত।

import { getAuth, signInWithEmailAndPassword } from 'firebase/auth/web-extension';

const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });

অফস্ক্রিন ডকুমেন্টস ব্যবহার করুন

কিছু প্রমাণীকরণ পদ্ধতি, যেমন signInWithPopup , linkWithPopup , এবং reauthenticateWithPopup , Chrome এক্সটেনশনগুলির সাথে সরাসরি সামঞ্জস্যপূর্ণ নয়, কারণ তাদের এক্সটেনশন প্যাকেজের বাইরে থেকে কোড লোড করা প্রয়োজন৷ ম্যানিফেস্ট V3 থেকে শুরু করে, এটি অনুমোদিত নয় এবং এক্সটেনশন প্ল্যাটফর্ম দ্বারা ব্লক করা হবে। এটির কাছাকাছি পেতে, আপনি একটি অফস্ক্রিন নথি ব্যবহার করে একটি আইফ্রেমের মধ্যে সেই কোডটি লোড করতে পারেন৷ অফস্ক্রিন নথিতে, স্বাভাবিক প্রমাণীকরণ প্রবাহ বাস্তবায়ন করুন এবং অফস্ক্রিন নথি থেকে এক্সটেনশনে ফলাফল প্রক্সি করুন৷

এই নির্দেশিকা একটি উদাহরণ হিসাবে signInWithPopup ব্যবহার করে, কিন্তু একই ধারণা অন্যান্য প্রমাণীকরণ পদ্ধতিতে প্রযোজ্য।

তুমি শুরু করার আগে

এই কৌশলটির জন্য আপনাকে ওয়েবে উপলব্ধ একটি ওয়েব পৃষ্ঠা সেট আপ করতে হবে, যা আপনি একটি আইফ্রেমে লোড করবেন। ফায়ারবেস হোস্টিং সহ যেকোনো হোস্ট এর জন্য কাজ করে। নিম্নলিখিত বিষয়বস্তু সহ একটি ওয়েবসাইট তৈরি করুন:

<!DOCTYPE html>
<html>
  <head>
    <title>signInWithPopup</title>
    <script src="signInWithPopup.js"></script>
  </head>
  <body><h1>signInWithPopup</h1></body>
</html>

ফেডারেটেড সাইন ইন

আপনি যদি ফেডারেটেড সাইন ইন ব্যবহার করেন, যেমন Google, Apple, SAML, বা OIDC এর সাথে সাইন ইন, তাহলে আপনাকে অবশ্যই অনুমোদিত ডোমেনের তালিকায় আপনার Chrome এক্সটেনশন আইডি যোগ করতে হবে:

  1. Firebase কনসোলে আপনার প্রকল্প খুলুন।
  2. প্রমাণীকরণ বিভাগে, সেটিংস পৃষ্ঠাটি খুলুন।
  3. অনুমোদিত ডোমেনের তালিকায় নিচের মত একটি URI যোগ করুন:
    chrome-extension://CHROME_EXTENSION_ID

আপনার Chrome এক্সটেনশনের ম্যানিফেস্ট ফাইলে নিশ্চিত করুন যে আপনি content_security_policy অনুমোদিত তালিকায় নিম্নলিখিত URLগুলি যোগ করেছেন:

  • https://apis.google.com
  • https://www.gstatic.com
  • https://www.googleapis.com
  • https://securetoken.googleapis.com

প্রমাণীকরণ বাস্তবায়ন করুন

আপনার HTML নথিতে, signInWithPopup.js হল জাভাস্ক্রিপ্ট কোড যা প্রমাণীকরণ পরিচালনা করে। এক্সটেনশনে সরাসরি সমর্থিত একটি পদ্ধতি বাস্তবায়নের দুটি ভিন্ন উপায় রয়েছে:

  • Firebase firebase/auth/web-extension এর পরিবর্তে firebase/auth ব্যবহার করুন। web-extension এন্ট্রি পয়েন্ট হল এক্সটেনশনের মধ্যে চলমান কোডের জন্য। যদিও এই কোডটি শেষ পর্যন্ত এক্সটেনশনে চলে (একটি আইফ্রেমে, আপনার অফস্ক্রিন নথিতে), এটি যে প্রেক্ষাপটে চলছে সেটি হল স্ট্যান্ডার্ড ওয়েব।
  • প্রমাণীকরণের অনুরোধ এবং প্রতিক্রিয়া প্রক্সি করার জন্য একটি postMessage লিসেনারে প্রমাণীকরণ লজিকটি মোড়ানো।
import { signInWithPopup, GoogleAuthProvider, getAuth } from'firebase/auth';
import { initializeApp } from 'firebase/app';
import firebaseConfig from './firebaseConfig.js'

const app = initializeApp(firebaseConfig);
const auth = getAuth();

// This code runs inside of an iframe in the extension's offscreen document.
// This gives you a reference to the parent frame, i.e. the offscreen document.
// 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) {
    // 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)
  }
});

আপনার Chrome এক্সটেনশন তৈরি করুন

আপনার ওয়েবসাইট লাইভ হওয়ার পরে, আপনি এটি আপনার Chrome এক্সটেনশনে ব্যবহার করতে পারেন৷

  1. আপনার manifest.json ফাইলে offscreen অনুমতি যোগ করুন:
  2.     {
          "name": "signInWithPopup Demo",
          "manifest_version" 3,
          "background": {
            "service_worker": "background.js"
          },
          "permissions": [
            "offscreen"
          ]
        }
        
  3. অফস্ক্রিন ডকুমেন্ট নিজেই তৈরি করুন। এটি আপনার এক্সটেনশন প্যাকেজের ভিতরে একটি ন্যূনতম HTML ফাইল যা আপনার অফস্ক্রিন নথি জাভাস্ক্রিপ্টের যুক্তি লোড করে:
  4.     <!DOCTYPE html>
        <script src="./offscreen.js"></script>
        
  5. আপনার এক্সটেনশন প্যাকেজে offscreen.js অন্তর্ভুক্ত করুন। এটি ধাপ 1 এ সেট আপ করা সর্বজনীন ওয়েবসাইট এবং আপনার এক্সটেনশনের মধ্যে প্রক্সি হিসাবে কাজ করে।
  6.     // This URL must point to the public site
        const _URL = 'https://example.com/signInWithPopupExample';
        const iframe = document.createElement('iframe');
        iframe.src = _URL;
        document.documentElement.appendChild(iframe);
        chrome.runtime.onMessage.addListener(handleChromeMessages);
    
        function handleChromeMessages(message, sender, sendResponse) {
          // Extensions may have an number of other reasons to send messages, so you
          // should filter out any that are not meant for the offscreen document.
          if (message.target !== 'offscreen') {
            return false;
          }
    
          function handleIframeMessage({data}) {
            try {
              if (data.startsWith('!_{')) {
                // Other parts of the Firebase library send messages using postMessage.
                // You don't care about them in this context, so return early.
                return;
              }
              data = JSON.parse(data);
              self.removeEventListener('message', handleIframeMessage);
    
              sendResponse(data);
            } catch (e) {
              console.log(`json parse failed - ${e.message}`);
            }
          }
    
          globalThis.addEventListener('message', handleIframeMessage, false);
    
          // 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);
          return true;
        }
        
  7. আপনার background.js পরিষেবা কর্মী থেকে অফস্ক্রিন নথি সেট আপ করুন৷
  8.     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 hasDocument())) {
            // create offscreen document
            if (creating) {
              await creating;
            } else {
              creating = chrome.offscreen.createDocument({
                url: path,
                reasons: [
                    chrome.offscreen.Reason.DOM_SCRAPING
                ],
                justification: 'authentication'
              });
              await creating;
              creating = null;
            }
          }
        }
    
        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;
        }
        

    এখন, যখন আপনি আপনার সার্ভিস ওয়ার্কার এর মধ্যে firebaseAuth() কল করবেন, এটি অফস্ক্রিন ডকুমেন্ট তৈরি করবে এবং সাইটটিকে একটি আইফ্রেমে লোড করবে। সেই iframe ব্যাকগ্রাউন্ডে প্রক্রিয়া করবে এবং Firebase স্ট্যান্ডার্ড প্রমাণীকরণ প্রবাহের মধ্য দিয়ে যাবে। একবার এটি সমাধান বা প্রত্যাখ্যান হয়ে গেলে, অফস্ক্রিন নথি ব্যবহার করে প্রমাণীকরণ বস্তুটি আপনার আইফ্রেম থেকে আপনার পরিষেবা কর্মীকে প্রক্সি করা হবে।