Skip to content
This repository has been archived by the owner on Sep 26, 2024. It is now read-only.

[MOC-203] mocksi-lite-next authentication #152

Merged
merged 1 commit into from
Aug 22, 2024
Merged

Conversation

fitzk
Copy link
Contributor

@fitzk fitzk commented Aug 22, 2024

dep PR: https://github.com/Mocksi/nest/pull/21

Summary by CodeRabbit

  • New Features

    • Introduced a new authentication retrieval process for improved user login experiences.
    • Added an event listener for extension installation to guide users to a specific URL.
    • Enhanced message handling to manage different states (ANALYZING, RECORDING) and update local storage dynamically.
  • Bug Fixes

    • Improved error handling during authentication retrieval to enhance reliability and user feedback.

@fitzk fitzk requested review from elg0nz and jonathankap August 22, 2024 02:10
Copy link

coderabbitai bot commented Aug 22, 2024

Walkthrough

Walkthrough

The changes enhance the functionality of the background and content scripts within the extension. The background script introduces an authentication retrieval process and manages external messages, while the content script adds a listener for storage changes and expands message handling related to iframe states. These modifications improve the interactivity and user experience of the extension.

Changes

File Path Change Summary
apps/mocksi-lite-next/src/pages/background/index.ts Replaced console.debug with console.log, added getAuth function for authentication, introduced "install" event listener, and modified message handling for async responses.
apps/mocksi-lite-next/src/pages/content/mocksi-extension.tsx Added event listener for window storage changes, defined STORAGE_CHANGE_EVENT, and expanded message listener for iframe state handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant BackgroundScript
    participant Storage
    participant ContentScript
    
    User ->> BackgroundScript: Install Extension
    BackgroundScript -->> User: Open URL for onboarding
    User ->> ContentScript: Send STORAGE_CHANGE_EVENT
    ContentScript ->> Storage: Update Local Storage
    Storage -->> ContentScript: Confirm Update
    ContentScript -->> User: Log Update Confirmation
Loading

🐇 In the code, I hop and play,
New features sprout, hooray, hooray!
With logs that shine and flows that glide,
My furry friends, come take a ride!
Together we'll explore, so bright,
In our extension's joyful flight! ✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@fitzk fitzk changed the title store token and email in local storage then pass to extension on nest server [MOC-203] mocksi-lite-next authentication Aug 22, 2024
Copy link

linear bot commented Aug 22, 2024

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (1)
apps/mocksi-lite-next/src/pages/background/index.ts (1)

43-73: Add comments for clarity in message handling.

Consider adding comments to explain the purpose of each conditional branch for better readability.

Apply this diff to add comments:

    if (request.message === "UNAUTHORIZED") {
+     // Handle unauthorized requests by retrieving authentication details
      const auth = await getAuth();
      if (auth) {
        const { accessToken, email } = auth;
        sendResponse({
          message: { accessToken, email },
          status: "ok",
        });
      } else {
+       // Open authentication URL if auth details are not found
        chrome.tabs.create({
          url: "https://nest-auth-ts-merge.onrender.com",
        });
        sendResponse({
          message: "authenticating",
          status: "ok",
        });
      }
    } else {
+     // Handle other messages by querying active tabs
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        if (tabs[0].id) {
          chrome.tabs.sendMessage(tabs[0].id, { message: request.message });
        } else {
          console.log("No active tab found, could not send message");
        }
      });
      sendResponse({ message: request.message, status: "ok" });
      return true;
    }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2cf462b and 5479880.

Files selected for processing (2)
  • apps/mocksi-lite-next/src/pages/background/index.ts (2 hunks)
  • apps/mocksi-lite-next/src/pages/content/mocksi-extension.tsx (2 hunks)
Additional comments not posted (1)
apps/mocksi-lite-next/src/pages/background/index.ts (1)

18-23: Verify cross-browser compatibility for the "install" event.

Ensure that the chrome.tabs.create function works as expected on browsers other than Chrome.

Run the following script to check for compatibility issues:

Comment on lines +1 to +16
console.log("background script loaded");

const getAuth = async (): Promise<null | {
accessToken: string;
email: string;
}> => {
const MOCKSI_AUTH = "mocksi-auth";
try {
const storageAuth = await chrome.storage.local.get(MOCKSI_AUTH);
const mocksiAuth = JSON.parse(storageAuth[MOCKSI_AUTH]);
return mocksiAuth;
} catch (err) {
console.error(err);
return null;
}
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve error handling in getAuth.

Consider providing more context in the error message to aid debugging.

Apply this diff to improve error handling:

  } catch (err) {
-   console.error(err);
+   console.error("Error retrieving authentication from local storage:", err);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log("background script loaded");
const getAuth = async (): Promise<null | {
accessToken: string;
email: string;
}> => {
const MOCKSI_AUTH = "mocksi-auth";
try {
const storageAuth = await chrome.storage.local.get(MOCKSI_AUTH);
const mocksiAuth = JSON.parse(storageAuth[MOCKSI_AUTH]);
return mocksiAuth;
} catch (err) {
console.error(err);
return null;
}
};
console.log("background script loaded");
const getAuth = async (): Promise<null | {
accessToken: string;
email: string;
}> => {
const MOCKSI_AUTH = "mocksi-auth";
try {
const storageAuth = await chrome.storage.local.get(MOCKSI_AUTH);
const mocksiAuth = JSON.parse(storageAuth[MOCKSI_AUTH]);
return mocksiAuth;
} catch (err) {
console.error("Error retrieving authentication from local storage:", err);
return null;
}
};

Comment on lines +8 to +27
const STORAGE_CHANGE_EVENT = "MOCKSI_STORAGE_CHANGE";

const div = document.createElement("div");
div.id = "__root";
document.body.appendChild(div);
let mounted = false;
const reactor = new Reactor();

window.addEventListener("message", (event: MessageEvent) => {
const eventData = event.data;
if (event.source !== window || !eventData || !eventData.type) {
return;
}

if (eventData.type.toUpperCase() === STORAGE_CHANGE_EVENT.toUpperCase()) {
chrome.storage.local.set({ [eventData.key]: eventData.value }).then(() => {
console.debug(eventData.key, " set.");
});
}
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add type checks for event data in the message listener.

Ensure eventData.key and eventData.value are of expected types before using them to update local storage.

Apply this diff to add type checks:

  if (eventData.type.toUpperCase() === STORAGE_CHANGE_EVENT.toUpperCase()) {
+   if (typeof eventData.key === "string" && typeof eventData.value !== "undefined") {
      chrome.storage.local.set({ [eventData.key]: eventData.value }).then(() => {
        console.debug(eventData.key, " set.");
      });
+   } else {
+     console.error("Invalid event data:", eventData);
+   }
  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const STORAGE_CHANGE_EVENT = "MOCKSI_STORAGE_CHANGE";
const div = document.createElement("div");
div.id = "__root";
document.body.appendChild(div);
let mounted = false;
const reactor = new Reactor();
window.addEventListener("message", (event: MessageEvent) => {
const eventData = event.data;
if (event.source !== window || !eventData || !eventData.type) {
return;
}
if (eventData.type.toUpperCase() === STORAGE_CHANGE_EVENT.toUpperCase()) {
chrome.storage.local.set({ [eventData.key]: eventData.value }).then(() => {
console.debug(eventData.key, " set.");
});
}
});
const STORAGE_CHANGE_EVENT = "MOCKSI_STORAGE_CHANGE";
const div = document.createElement("div");
div.id = "__root";
document.body.appendChild(div);
let mounted = false;
const reactor = new Reactor();
window.addEventListener("message", (event: MessageEvent) => {
const eventData = event.data;
if (event.source !== window || !eventData || !eventData.type) {
return;
}
if (eventData.type.toUpperCase() === STORAGE_CHANGE_EVENT.toUpperCase()) {
if (typeof eventData.key === "string" && typeof eventData.value !== "undefined") {
chrome.storage.local.set({ [eventData.key]: eventData.value }).then(() => {
console.debug(eventData.key, " set.");
});
} else {
console.error("Invalid event data:", eventData);
}
}
});

Comment on lines +59 to +73
// reactor
if (request.message === "EDITING") {
reactor.attach(document, getHighlighter());
}
if (request.message === "STOP_EDITING") {
reactor.detach();
}
// resize iframe
if (iframeRef.current) {
let styles = {};
switch (request.message) {
case "ANALYZING":
case "EDITING":
case "PLAY":
case "RECORDING":
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extract style objects into constants for better readability.

Consider defining the style objects as constants outside the switch statement to improve readability and maintainability.

Apply this diff to extract style objects:

+const STYLES = {
+  ANALYZING: { bottom: "auto", height: "150px", top: "0px", width: "400px" },
+  MINIMIZED: { bottom: "10px", height: "100px", top: "auto", width: "100px" },
+  DEFAULT: { bottom: "10px", height: "600px", top: "auto", width: "500px" },
+};

...

              switch (request.message) {
                case "ANALYZING":
                case "EDITING":
                case "PLAY":
                case "RECORDING":
-                 styles = {
-                   bottom: "auto",
-                   height: "150px",
-                   top: "0px",
-                   width: "400px",
-                 };
+                 styles = STYLES.ANALYZING;
                  break;
                case "MINIMIZED":
-                 styles = {
-                   bottom: "10px",
-                   height: "100px",
-                   top: "auto",
-                   width: "100px",
-                 };
+                 styles = STYLES.MINIMIZED;
                  break;
                default:
-                 styles = {
-                   bottom: "10px",
-                   height: "600px",
-                   top: "auto",
-                   width: "500px",
-                 };
+                 styles = STYLES.DEFAULT;
              }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// reactor
if (request.message === "EDITING") {
reactor.attach(document, getHighlighter());
}
if (request.message === "STOP_EDITING") {
reactor.detach();
}
// resize iframe
if (iframeRef.current) {
let styles = {};
switch (request.message) {
case "ANALYZING":
case "EDITING":
case "PLAY":
case "RECORDING":
// reactor
if (request.message === "EDITING") {
reactor.attach(document, getHighlighter());
}
if (request.message === "STOP_EDITING") {
reactor.detach();
}
// resize iframe
if (iframeRef.current) {
const STYLES = {
ANALYZING: { bottom: "auto", height: "150px", top: "0px", width: "400px" },
MINIMIZED: { bottom: "10px", height: "100px", top: "auto", width: "100px" },
DEFAULT: { bottom: "10px", height: "600px", top: "auto", width: "500px" },
};
let styles = {};
switch (request.message) {
case "ANALYZING":
case "EDITING":
case "PLAY":
case "RECORDING":
styles = STYLES.ANALYZING;
break;
case "MINIMIZED":
styles = STYLES.MINIMIZED;
break;
default:
styles = STYLES.DEFAULT;
}

} else {
console.log("No active tab found, could not send message");
chrome.tabs.create({
url: "https://nest-auth-ts-merge.onrender.com",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's change this to use env variables so we can easily switch between local and production

@fitzk fitzk merged commit aac7b2b into main Aug 22, 2024
3 checks passed
@elg0nz elg0nz deleted the MOC-203_authentication branch September 12, 2024 21:00
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants