Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: token utility helper #8

Merged
merged 8 commits into from
Sep 20, 2024
Merged

feat: token utility helper #8

merged 8 commits into from
Sep 20, 2024

Conversation

DanielRivers
Copy link
Contributor

@DanielRivers DanielRivers commented Sep 12, 2024

Explain your changes

Adding token helpers linking to the session manager

Checklist

🛟 If you need help, consider asking for advice over in the Kinde community.

@DanielRivers DanielRivers marked this pull request as draft September 12, 2024 21:21
Copy link
Contributor

coderabbitai bot commented Sep 12, 2024

Warning

Rate limit exceeded

@DanielRivers has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 31 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 60387bf and 4ec8d5f.

Walkthrough

The pull request introduces a utility function, getUserProfile, along with its corresponding test suite to manage user profile information retrieval from ID tokens stored in session storage. It includes a new module for session management, encapsulating functionalities such as setting and getting active storage. The changes also enhance documentation by detailing token-related helper functions.

Changes

Files Change Summary
lib/utils/token/getUserProfile.ts Added getUserProfile function to extract user profile information from a decoded token and defined UserProfile type. Added setActiveStorage function for managing active storage.
lib/utils/token/getUserProfile.test.ts Added unit tests for the getUserProfile function to ensure correct extraction of user profile data under various scenarios.
lib/utils/token/index.ts Established a module for session management, including setActiveStorage and getActiveStorage functions, and exported various utility functions and types.
readme.md Added a section titled "Token Helpers" documenting various token-related helper functions.

Possibly related PRs


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>, please review it.
    -- 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

Copy link
Contributor

@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.

Caution

Inline review comments failed to post

Actionable comments posted: 14

Outside diff range and nitpick comments (1)
lib/utils/token/getUserOrganistaions.ts (1)

10-12: Consider explicitly defining the parameter type for getDecodedToken.

The parameter type for getDecodedToken is not explicitly defined, relying on type inference. To improve code readability and maintainability, consider explicitly defining the parameter type.

Apply this diff to explicitly define the parameter type:

-await getDecodedToken<{
+await getDecodedToken<{ org_codes: string[] }>("idToken")
-  org_codes: string[];
-}>("idToken")
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8dbb5fc and 29cbfeb.

Files ignored due to path filters (2)
  • package.json is excluded by !**/*.json
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/*.yaml
Files selected for processing (7)
  • lib/utils/base64UrlEncode.ts (1 hunks)
  • lib/utils/token/getDecodedToken.test.ts (1 hunks)
  • lib/utils/token/getDecodedToken.ts (1 hunks)
  • lib/utils/token/getUserOrganistaions.test.ts (1 hunks)
  • lib/utils/token/getUserOrganistaions.ts (1 hunks)
  • lib/utils/token/index.ts (1 hunks)
  • lib/utils/token/testUtils/index.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • lib/utils/base64UrlEncode.ts
Additional context used
Biome
lib/utils/token/getDecodedToken.test.ts

[error] 7-7: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)


[error] 15-15: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)


[error] 25-25: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)


[error] 40-40: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

Additional comments not posted (4)
lib/utils/token/getUserOrganistaions.ts (1)

3-15: LGTM!

The function aligns with the PR objective of introducing token helpers to retrieve user organizations. It correctly uses the getDecodedToken function to decode the ID token and extract the org_codes field. Returning null when org_codes is not present is a safe approach to handle missing data.

The JSDoc comment accurately describes the function's purpose and return type.

lib/utils/token/index.ts (1)

12-14: LGTM!

The getActiveStorage function is correctly implemented and returns the active session manager.

lib/utils/token/getDecodedToken.ts (1)

1-31: LGTM!

The getDecodedToken function is well-implemented and follows a clear logic flow. It properly handles the case when the active storage is not found by throwing an error. The use of the jwtDecoder library for decoding the token is a good choice. The function is also properly typed using TypeScript, which enhances code quality and maintainability.

lib/utils/token/testUtils/index.ts (1)

1-39: LGTM!

The function correctly generates a mock JWT access token with the expected structure. The use of the crypto module for creating the signature is appropriate, and the function allows overriding default payload values through the values parameter, which provides flexibility for testing different scenarios.

Comments failed to post (14)
lib/utils/token/getUserOrganistaions.ts (2)

7-15: Handle potential errors during token decoding.

The function does not handle potential errors that may occur during token decoding. It assumes that the getDecodedToken function always returns a valid decoded token or undefined.

Consider adding a try-catch block to handle potential errors and return an appropriate value or throw an error if needed. For example:

export const getUserOrganisations = async (): Promise<string[] | null> => {
  try {
    return (
      (await getDecodedToken<{ org_codes: string[] }>("idToken"))?.org_codes || null
    );
  } catch (error) {
    console.error("Error decoding token:", error);
    return null; // or throw an error if needed
  }
};

7-7: Fix the typo in the function name.

The function name has a typo: "Organisataions" instead of "Organisations".

Apply this diff to fix the typo:

-export const getUserOrganizations = async (): Promise<string[] | null> => {
+export const getUserOrganisations = async (): Promise<string[] | null> => {
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.

export const getUserOrganisations = async (): Promise<string[] | null> => {
lib/utils/token/index.ts (2)

3-10: Remove the console log statement.

The console log statement at line 9 is used for debugging purposes and should be removed before production.

Apply this diff to remove the console log statement:

-  console.log("store", store);
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.

const storage = {
  value: null as SessionManager | null,
};

export const setActiveStorage = (store: SessionManager) => {
  storage.value = store;
};

1-1: > [!TIP]

Codebase Verification

Update the import path for the SessionManager module.

The import path in lib/utils/token/index.ts should be updated to ../../sessionManager/types to correctly reference the SessionManager interface.

  • lib/utils/token/index.ts: Update the import statement to import { SessionManager } from "../../sessionManager/types";
Analysis chain

Verify the import path for the SessionManager module.

Please ensure that the path to the SessionManager module is correct and replace the placeholder comment with the actual path.

Run the following script to verify the import path:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the import path for the `SessionManager` module.

# Test: Search for the `SessionManager` module. Expect: A single occurrence of the module.
rg --type typescript $'SessionManager'

Length of output: 72


Script:

#!/bin/bash
# Description: Verify the import path for the `SessionManager` module.

# Test: Search for the `SessionManager` module in TypeScript files.
rg -t ts 'SessionManager'

Length of output: 1082

lib/utils/token/getDecodedToken.ts (1)

25-25: Remove console log statement.

Please remove the console log statement before merging to production. Console logs should not be present in production code.

Apply this diff to remove the console log statement:

-  console.log("token", token);
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.


lib/utils/token/testUtils/index.ts (2)

24-24: Move the secret key to an environment variable.

The secret key is currently hardcoded as a string literal, which is not recommended for production use. Consider moving the secret key to an environment variable to improve security and allow for easy rotation of the key.


3-39: Add input validation for the values parameter.

The function does not validate the input values object, which could lead to unexpected behavior if invalid values are provided. Consider adding input validation to ensure that only valid properties are merged into the payload object.

lib/utils/token/getUserOrganistaions.test.ts (3)

26-26: Update the test description to match the test implementation.

The test description "error when no active storage is set" does not match the test implementation. The test is actually verifying the successful case when multiple org codes are present in the id token.

Consider updating the test description to something like:

-it("error when no active storage is set", async () => {
+it("returns all the org codes from the id token", async () => {
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.

  it("returns all the org codes from the id token", async () => {

39-39: Update the test description to match the test implementation.

The test description "error when no active storage is set" does not match the test implementation. The test is verifying the case when org codes are null in the id token.

Consider updating the test description to something like:

-it("error when no active storage is set", async () => {
+it("returns null when org codes are null in the id token", async () => {
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.

  it("returns null when org codes are null in the id token", async () => {

13-13: Update the test description to match the test implementation.

The test description "error when no active storage is set" does not match the test implementation. The test is actually verifying the successful case when an org code is present in the id token.

Consider updating the test description to something like:

-it("error when no active storage is set", async () => {
+it("returns the org codes from the id token", async () => {
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.

  it("returns the org codes from the id token", async () => {
lib/utils/token/getDecodedToken.test.ts (4)

40-40: Remove the focus from the test suite.

Focused tests are often used for debugging and should be removed before merging to ensure all tests are executed.

Apply this diff to remove the focus:

-describe.only("getDecodedToken accessToken", () => {
+describe("getDecodedToken accessToken", () => {
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.

describe("getDecodedToken accessToken", () => {
Tools
Biome

[error] 40-40: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)


15-15: Remove the focus from the test suite.

Focused tests are often used for debugging and should be removed before merging to ensure all tests are executed.

Apply this diff to remove the focus:

-describe.only("getDecodedToken", () => {
+describe("getDecodedToken", () => {
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.

describe("getDecodedToken", () => {
Tools
Biome

[error] 15-15: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)


25-25: Remove the focus from the test suite.

Focused tests are often used for debugging and should be removed before merging to ensure all tests are executed.

Apply this diff to remove the focus:

-describe.only("getDecodedToken idToken", () => {
+describe("getDecodedToken idToken", () => {
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.

describe("getDecodedToken idToken", () => {
Tools
Biome

[error] 25-25: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)


7-7: Remove the focus from the test suite.

Focused tests are often used for debugging and should be removed before merging to ensure all tests are executed.

Apply this diff to remove the focus:

-describe.only("getDecodedToken", () => {
+describe("getDecodedToken", () => {
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.

describe("getDecodedToken", () => {
Tools
Biome

[error] 7-7: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

Copy link

codecov bot commented Sep 12, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 76.27%. Comparing base (c7fcaa7) to head (4ec8d5f).
Report is 9 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             main       #8       +/-   ##
===========================================
+ Coverage   59.30%   76.27%   +16.96%     
===========================================
  Files          15       27       +12     
  Lines         344      531      +187     
  Branches       37       82       +45     
===========================================
+ Hits          204      405      +201     
+ Misses        140      126       -14     
Files with missing lines Coverage Δ
lib/utils/base64UrlEncode.ts 100.00% <ø> (ø)
lib/utils/token/getClaim.ts 100.00% <100.00%> (ø)
lib/utils/token/getClaims.ts 100.00% <100.00%> (ø)
lib/utils/token/getCurrentOrganization.ts 100.00% <100.00%> (ø)
lib/utils/token/getDecodedToken.ts 100.00% <100.00%> (ø)
lib/utils/token/getFlag.ts 100.00% <100.00%> (ø)
lib/utils/token/getPermission.ts 100.00% <100.00%> (ø)
lib/utils/token/getPermissions.ts 100.00% <100.00%> (ø)
lib/utils/token/getRoles.ts 100.00% <100.00%> (ø)
lib/utils/token/getUserOrganistaions.ts 100.00% <100.00%> (ø)
... and 3 more

... and 2 files with indirect coverage changes

@DanielRivers DanielRivers marked this pull request as ready for review September 19, 2024 22:09
Copy link
Contributor

@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: 6

Outside diff range and nitpick comments (1)
lib/utils/token/getUserOrganistaions.ts (1)

7-7: Fix the typo in the function name.

There is a typo in the function name "getUserOrganistaions". It should be "getUserOrganizations".

Apply this diff to fix the typo:

-export const getUserOrganistaions = async (): Promise<string[] | null> => {
+export const getUserOrganizations = async (): Promise<string[] | null> => {

Also, ensure that the file is renamed to match the function name.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 29cbfeb and 0b03912.

Files ignored due to path filters (2)
  • package.json is excluded by !**/*.json
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/*.yaml
Files selected for processing (22)
  • lib/utils/base64UrlEncode.ts (1 hunks)
  • lib/utils/generateRandomString-nocrypto.test.ts (1 hunks)
  • lib/utils/token/getClaim.ts (1 hunks)
  • lib/utils/token/getClaims.ts (1 hunks)
  • lib/utils/token/getCurrentOrganization.test.ts (1 hunks)
  • lib/utils/token/getCurrentOrganization.ts (1 hunks)
  • lib/utils/token/getDecodedToken.test.ts (1 hunks)
  • lib/utils/token/getDecodedToken.ts (1 hunks)
  • lib/utils/token/getFlag.test.ts (1 hunks)
  • lib/utils/token/getFlag.ts (1 hunks)
  • lib/utils/token/getPermission.test.ts (1 hunks)
  • lib/utils/token/getPermission.ts (1 hunks)
  • lib/utils/token/getPermissions.test.ts (1 hunks)
  • lib/utils/token/getPermissions.ts (1 hunks)
  • lib/utils/token/getRoles.test.ts (1 hunks)
  • lib/utils/token/getRoles.ts (1 hunks)
  • lib/utils/token/getUserOrganistaions.test.ts (1 hunks)
  • lib/utils/token/getUserOrganistaions.ts (1 hunks)
  • lib/utils/token/getUserProfile.test.ts (1 hunks)
  • lib/utils/token/getUserProfile.ts (1 hunks)
  • lib/utils/token/index.ts (1 hunks)
  • lib/utils/token/testUtils/index.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • lib/utils/base64UrlEncode.ts
Additional comments not posted (46)
lib/utils/token/getClaims.ts (1)

1-10: LGTM!

The getClaims function is a well-designed utility that encapsulates the logic for retrieving claims from the "accessToken". It promotes code reuse and modularity by leveraging the getDecodedToken function.

The use of TypeScript generics allows for flexibility and type safety, enabling better integration with the type system. The function's asynchronous nature aligns with the likely asynchronous behavior of getDecodedToken.

The JSDoc comment provides a clear description of the function's purpose and return type, enhancing the code's readability and maintainability.

Overall, this is a useful addition to the codebase that can streamline the process of extracting claims from JWTs in a type-safe manner.

lib/utils/token/getCurrentOrganization.ts (1)

1-12: LGTM!

The getCurrentOrganization function is well-structured, follows a clear logic flow, and provides a convenient way to access organization-related information from the token. The use of the getClaim utility function promotes code reuse and modularity. The function handles the case when the claim is not present by returning null, ensuring predictable behavior. The JSDoc comments provide a clear description of the function's purpose and return type. Overall, the implementation is clean, concise, and easy to understand.

lib/utils/token/getUserOrganistaions.ts (1)

1-15: LGTM!

The getUserOrganizations function is well-structured and follows good practices:

  • It uses getDecodedToken to fetch the decoded token, keeping the token decoding logic separate.
  • It uses a type assertion to specify the expected structure of the decoded token, which helps with type safety.
  • It handles the case when org_codes is not present in the token by returning null.
lib/utils/token/getClaim.ts (1)

1-23: LGTM!

The getClaim function is well-implemented and provides a useful utility for retrieving a specific claim from a decoded token. Here are some observations:

  • The function is well-documented with JSDoc comments, providing clear information about the purpose, parameters, and return value.
  • The use of generics (T and V) allows for type safety and flexibility in the types of the decoded token and claim value.
  • The function handles the case where the claims are not found by returning null, providing a clear indication of the absence of claims.
  • The function uses type assertion (as V) to cast the claim value to the expected type V, ensuring type safety in the returned value.

Overall, the code is clean, readable, and follows best practices. Great job!

lib/utils/token/getFlag.ts (1)

8-23: LGTM!

The getFlag function is well-implemented and provides a convenient way to retrieve feature flags from a token. Here are some positive aspects of the implementation:

  • The function correctly handles the case when the specified name does not exist within the retrieved flags by returning null.
  • The function uses a generic type parameter T to specify the expected type of the flag value, which is inferred from the usage. This makes the function more type-safe and self-documenting.
  • The function uses optional chaining (?.) to safely access the value property of the retrieved flags, which prevents runtime errors when the feature_flags claim is missing.
  • The function uses a logical OR operator (||) to return null if the flag value is undefined, providing a fallback value.
  • The function uses a type assertion (as { feature_flags: string }) to specify the expected type of the feature_flags claim, which helps catch type mismatches early.
  • The function uses a type alias (Record<string, { t: "b" | "i" | "s"; v: T }>) to specify the expected structure of the feature flags record, which makes the code more readable and maintainable.

Overall, the getFlag function is a solid addition to the codebase and aligns well with the PR objectives of introducing token helpers for feature flag management.

lib/utils/token/getPermissions.ts (1)

1-23: LGTM!

The getPermissions function is well-implemented and provides a clean and reusable way to retrieve user permissions from a decoded token. Here are some key points:

  • The function handles the case when the token is not present by returning a default object with a null organization code and an empty permissions array.
  • It uses the getDecodedToken function to decode the token, which is a good practice to separate concerns.
  • The use of a generic type Permissions<T> allows for flexible handling of permissions, accommodating various types as specified by the generic type parameter.
  • The function correctly extracts the organization code and permissions from the decoded token.
  • The function is well-documented with JSDoc comments.

Overall, the implementation looks solid and provides a useful utility for retrieving user permissions from a decoded token.

lib/utils/token/getRoles.ts (1)

9-24: LGTM!

The getRoles function is well-implemented and handles various scenarios related to retrieving user roles from a decoded JWT token. It provides a robust mechanism for obtaining roles while ensuring appropriate warnings are issued when roles are not available or configured correctly.

The function logic is correct, and the implementation is accurate. The code is clean, readable, and follows best practices.

lib/utils/token/getUserProfile.ts (1)

3-9: LGTM!

The UserProfile type covers the essential fields for a user profile, and the field names follow a consistent naming convention. The use of string types for all fields is appropriate.

lib/utils/token/getDecodedToken.ts (1)

1-28: LGTM!

The getDecodedToken function is well-structured, follows a clear logical flow, and provides a convenient and secure way to decode JWT tokens. The function is modular, reusable, and well-documented, making it easy for other developers to understand and use.

Some key points:

  • The function uses appropriate type annotations and generics to ensure type safety.
  • The function handles the case when the token is not found in the session storage by returning null.
  • The function uses the jwtDecoder function from the @kinde/jwt-decoder library to decode the token, which is a reliable and secure way to decode JWT tokens.
  • The function encapsulates the token retrieval and decoding logic, making it modular and reusable.

Great job on this implementation! 👍

lib/utils/token/getPermission.ts (3)

3-7: LGTM!

The PermissionAccess type definition is clear, concise, and accurately captures the required properties and their types.


14-16: LGTM!

The getPermission function signature is well-defined, with appropriate use of asynchronous syntax, generic type parameter, and accurate return type.


17-33: LGTM!

The getPermission function implementation is well-structured and handles different scenarios appropriately:

  • It retrieves the decoded token using the getDecodedToken function.
  • It returns a PermissionAccess object with isGranted set to false and orgCode set to null when the token is not present.
  • It checks for the presence of the permissionKey in the permissions array of the token.
  • It constructs and returns a PermissionAccess object with the correct values based on the token and permissionKey.

The implementation is clear, concise, and effectively manages permission access based on the provided permissionKey and token.

lib/utils/token/getCurrentOrganization.test.ts (2)

12-17: LGTM!

The test case correctly tests the scenario when no access token is present in the session storage. It uses the MemoryStorage class to simulate the session storage behavior, sets the idToken to null, and expects the getCurrentOrganization function to return null, which is the correct behavior.


19-27: LGTM!

The test case correctly tests the scenario when a valid access token containing an organization code is present in the session storage. It uses the MemoryStorage class to simulate the session storage behavior, sets the accessToken to a mock access token containing the organization code org_123456, and expects the getCurrentOrganization function to return the organization code org_123456, which is the correct behavior.

lib/utils/token/getUserOrganistaions.test.ts (3)

12-20: LGTM!

The test case is well-structured and correctly verifies the behavior of the getUserOrganizations function when a single organization code is stored in the session.


22-30: LGTM!

The test case is well-structured and correctly verifies the behavior of the getUserOrganizations function when multiple organization codes are stored in the session.


32-40: LGTM!

The test case is well-structured and correctly verifies the behavior of the getUserOrganizations function when no organization codes are stored in the session.

lib/utils/token/index.ts (4)

13-15: LGTM!

The storage object is implemented correctly with proper type annotation and initialization.


17-19: LGTM!

The setActiveStorage function is implemented correctly, allowing for proper initialization of the SessionManager instance.


21-26: LGTM!

The getActiveStorage function is implemented correctly, providing controlled access to the SessionManager instance and ensuring proper initialization.


28-43: LGTM!

The exported utility functions and types are relevant and enhance the modularity, reusability, and type safety of the codebase.

lib/utils/token/getUserProfile.test.ts (1)

8-56: Excellent test coverage for the getUserProfile function!

The test suite provides comprehensive coverage for the getUserProfile function by testing different scenarios:

  1. When no ID token is present in the storage.
  2. When a basic ID token with minimal information is provided.
  3. When a more complete ID token containing user details is provided.

The use of a mock storage mechanism (MemoryStorage) ensures that the tests are isolated and do not depend on external storage systems. The beforeEach hook helps maintain a clean state between tests, preventing any potential side effects.

Overall, the test suite is well-structured and effectively validates the behavior of the getUserProfile function.

lib/utils/generateRandomString-nocrypto.test.ts (5)

11-15: LGTM!

The test case correctly verifies that the generated string matches the specified length.


17-25: LGTM!

The test case correctly verifies that the generated string contains only valid characters.


27-32: LGTM!

The test case correctly verifies that subsequent calls to the function generate different strings.


34-38: LGTM!

The test case correctly verifies that the function handles a length of 0 by returning an empty string.


40-44: LGTM!

The test case correctly verifies that the function handles a large length by generating a string of the specified length.

lib/utils/token/getRoles.test.ts (4)

14-19: LGTM!

This test case correctly verifies the behavior of the getRoles function when no token is present in the session storage. It's an important edge case to cover.


21-28: LGTM!

This test case correctly verifies the behavior of the getRoles function when the access token is present but does not contain any roles. It's an important scenario to cover.


30-43: LGTM!

This test case correctly verifies that a warning is logged to the console when the access token lacks roles. It's a good practice to inform developers about potential issues like this.


45-53: LGTM!

This test case correctly verifies that the getRoles function returns the roles from the access token when they are present. It's an important positive test case to ensure the core functionality works as expected.

lib/utils/token/getDecodedToken.test.ts (1)

7-13: LGTM!

The test case correctly asserts the expected error when no active storage is set.

lib/utils/token/getPermissions.test.ts (4)

18-26: LGTM!

The test case correctly verifies the behavior of getPermissions when no access token is available. It sets the idToken to null in session storage and expects the result to be an object with orgCode set to null and an empty permissions array.


28-39: LGTM!

The test case correctly verifies the behavior of getPermissions when a valid access token with a permission is present. It sets a mock access token with a "canEdit" permission in session storage and expects the result to include the orgCode and the "canEdit" permission in the permissions array.


41-52: LGTM!

The test case correctly verifies the behavior of getPermissions when a valid access token with a permission is present and the permissions are typed using an enum. It sets a mock access token with a "canEdit" permission in session storage, calls getPermissions with a generic type parameter PermissionEnum, and expects the result to include the orgCode and the PermissionEnum.canEdit value in the permissions array.


54-65: LGTM!

The test case correctly verifies the behavior of getPermissions when the permissions array is explicitly set to null in the access token. It sets a mock access token with permissions set to null in session storage, calls getPermissions with a generic type parameter PermissionEnum, and expects the result to include the orgCode and an empty permissions array.

lib/utils/token/getFlag.test.ts (5)

13-18: LGTM!

The test case correctly verifies the behavior of the getFlag function when no token is present in the session storage. It sets the idToken to null, calls the function with a flag name, and asserts that the returned value is null.


20-35: LGTM!

The test case correctly verifies the behavior of the getFlag function when the feature flag value is a boolean. It sets up the accessToken with a mock token containing a boolean feature flag, calls the function with the flag name and a type parameter, and asserts that the returned value matches the expected boolean value.


37-52: LGTM!

The test case correctly verifies the behavior of the getFlag function when the feature flag value is a string. It sets up the accessToken with a mock token containing a string feature flag, calls the function with the flag name and a type parameter, and asserts that the returned value matches the expected string value.


54-69: LGTM!

The test case correctly verifies the behavior of the getFlag function when the feature flag value is an integer. It sets up the accessToken with a mock token containing an integer feature flag, calls the function with the flag name and a type parameter, and asserts that the returned value matches the expected integer value.


71-86: LGTM!

The test case correctly verifies the behavior of the getFlag function when the requested feature flag does not exist in the token. It sets up the accessToken with a mock token containing a feature flag, calls the function with a non-existent flag name and a type parameter, and asserts that the returned value is null.

lib/utils/token/getPermission.test.ts (5)

16-25: LGTM!

The test case correctly verifies the behavior of the getPermission function when there is no access token. It sets the idToken to null, calls the function with a permission key, and expects the function to return an object indicating that permission is not granted.


27-36: LGTM!

The test case correctly verifies the behavior of the getPermission function when there is no access token and the permission key is an enum. It sets the idToken to null, calls the function with the enum permission key, and expects the function to return an object indicating that permission is not granted.


38-50: LGTM!

The test case correctly verifies the behavior of the getPermission function when there is an access token with the "canEdit" permission. It sets the accessToken using a mock token, calls the function with the enum permission key, and expects the function to return an object indicating that permission is granted and the correct organization code.


52-67: LGTM!

The test case correctly verifies the behavior of the getPermission function when there is an access token with the "canEdit" permission from a different organization. It sets the accessToken using a mock token with a different organization code, calls the function with the enum permission key, and expects the function to return an object indicating that permission is granted and the correct organization code from the token.


69-81: LGTM!

The test case correctly verifies the behavior of the getPermission function when there is an access token with a null permissions array. It sets the accessToken using a mock token with null permissions, calls the function with the enum permission key, and expects the function to return an object indicating that permission is not granted and the correct organization code from the token.

lib/utils/token/getUserProfile.ts Outdated Show resolved Hide resolved
lib/utils/token/testUtils/index.ts Show resolved Hide resolved
lib/utils/token/index.ts Outdated Show resolved Hide resolved
lib/utils/token/getDecodedToken.test.ts Outdated Show resolved Hide resolved
lib/utils/token/getDecodedToken.test.ts Outdated Show resolved Hide resolved
lib/utils/token/getDecodedToken.test.ts Outdated Show resolved Hide resolved
DanielRivers and others added 2 commits September 20, 2024 11:37
test: Correct test descriptions

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@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: 0

Outside diff range and nitpick comments (2)
lib/utils/token/getUserProfile.test.ts (2)

36-36: Consider renaming the test case description to avoid duplication.

The test case description "when has basic stuff" is duplicated from the previous test case at line range 20-34. Consider renaming it to something more specific to the scenario being tested, such as "when token has additional claims".


69-69: Consider renaming the test case description to avoid duplication.

The test case description "when no sub, return null" is duplicated from the previous test case at line range 57-67. Consider renaming it to something more specific to the scenario being tested, such as "when no sub, log error message".

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4ccd0bb and d34ee6e.

Files selected for processing (2)
  • lib/utils/token/getUserProfile.test.ts (1 hunks)
  • lib/utils/token/getUserProfile.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • lib/utils/token/getUserProfile.ts
Additional comments not posted (3)
lib/utils/token/getUserProfile.test.ts (3)

1-4: LGTM!

The imports are well-structured and follow the best practices. The utility function createMockAccessToken is correctly imported from a dedicated test utilities file.


6-7: LGTM!

The MemoryStorage instance is created correctly, and the storage variable is declared at the top level, making it accessible to all test cases.


8-83: Comprehensive test coverage!

The test cases cover a good range of scenarios, including edge cases like missing token or sub claim. The beforeEach block ensures a clean state before each test case. The test cases use the createMockAccessToken utility function for creating mock data and the expect function for making assertions, which are good practices. The test case names are descriptive and clearly convey the scenario being tested.

Copy link
Contributor

@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: 0

Outside diff range and nitpick comments (1)
readme.md (1)

77-77: Maintain consistency in spelling.

Please ensure consistent spelling of "organization" throughout the document. Currently, both "organization" and "organisation" are used.

Apply this change:

-`getUserOrganizations` - get all the organizations the user has access to
+`getUserOrganizations` - get all the organisations the user has access to
Tools
LanguageTool

[uncategorized] ~77-~77: Do not mix variants of the same word (‘organization’ and ‘organisation’) within a single text.
Context: ...s getUserOrganizations - get all the organizations the user has access to `getUserProfile...

(EN_WORD_COHERENCY)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d34ee6e and 60387bf.

Files selected for processing (2)
  • lib/utils/token/index.ts (1 hunks)
  • readme.md (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • lib/utils/token/index.ts
Additional context used
LanguageTool
readme.md

[uncategorized] ~77-~77: Do not mix variants of the same word (‘organization’ and ‘organisation’) within a single text.
Context: ...s getUserOrganizations - get all the organizations the user has access to `getUserProfile...

(EN_WORD_COHERENCY)

Additional comments not posted (1)
readme.md (1)

51-80: Great addition to the documentation!

The new "Token Helpers" section provides a comprehensive overview of the available token-related helper functions. The descriptions are clear and concise, making it easy for developers to understand the purpose of each function.

Tools
LanguageTool

[uncategorized] ~77-~77: Do not mix variants of the same word (‘organization’ and ‘organisation’) within a single text.
Context: ...s getUserOrganizations - get all the organizations the user has access to `getUserProfile...

(EN_WORD_COHERENCY)

@DanielRivers DanielRivers changed the title feat: add activeStorage, getDecodedToken and getUserOrganisations feat: token utility helper Sep 20, 2024
@DanielRivers DanielRivers merged commit 11852c7 into main Sep 20, 2024
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants