-
Notifications
You must be signed in to change notification settings - Fork 0
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
Conversation
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 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. WalkthroughThe pull request introduces a utility function, Changes
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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
29cbfeb
to
650dd71
Compare
There was a problem hiding this 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 forgetDecodedToken
.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
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 theorg_codes
field. Returningnull
whenorg_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 thejwtDecoder
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 thevalues
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 orundefined
.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 theSessionManager
interface.
lib/utils/token/index.ts
: Update the import statement toimport { 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)
650dd71
to
2221169
Compare
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ 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
|
f3d8331
to
56dbdc8
Compare
56dbdc8
to
0789079
Compare
fd8d007
to
0b03912
Compare
There was a problem hiding this 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
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 thegetDecodedToken
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 thegetClaim
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 returningnull
.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
andV
) 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 typeV
, 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 returningnull
.- 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 thevalue
property of the retrieved flags, which prevents runtime errors when thefeature_flags
claim is missing.- The function uses a logical OR operator (
||
) to returnnull
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 thefeature_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 withisGranted
set tofalse
andorgCode
set tonull
when the token is not present.- It checks for the presence of the
permissionKey
in thepermissions
array of the token.- It constructs and returns a
PermissionAccess
object with the correct values based on the token andpermissionKey
.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 theidToken
tonull
, and expects thegetCurrentOrganization
function to returnnull
, 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 theaccessToken
to a mock access token containing the organization codeorg_123456
, and expects thegetCurrentOrganization
function to return the organization codeorg_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 theSessionManager
instance.
21-26
: LGTM!The
getActiveStorage
function is implemented correctly, providing controlled access to theSessionManager
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 thegetUserProfile
function!The test suite provides comprehensive coverage for the
getUserProfile
function by testing different scenarios:
- When no ID token is present in the storage.
- When a basic ID token with minimal information is provided.
- 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. ThebeforeEach
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 theidToken
tonull
in session storage and expects the result to be an object withorgCode
set tonull
and an emptypermissions
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 theorgCode
and the "canEdit" permission in thepermissions
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, callsgetPermissions
with a generic type parameterPermissionEnum
, and expects the result to include theorgCode
and thePermissionEnum.canEdit
value in thepermissions
array.
54-65
: LGTM!The test case correctly verifies the behavior of
getPermissions
when thepermissions
array is explicitly set tonull
in the access token. It sets a mock access token withpermissions
set tonull
in session storage, callsgetPermissions
with a generic type parameterPermissionEnum
, and expects the result to include theorgCode
and an emptypermissions
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 theidToken
tonull
, calls the function with a flag name, and asserts that the returned value isnull
.
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 theaccessToken
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 theaccessToken
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 theaccessToken
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 theaccessToken
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 isnull
.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 theidToken
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 theidToken
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 theaccessToken
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 theaccessToken
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 theaccessToken
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.
test: Correct test descriptions Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this 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
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 thestorage
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. ThebeforeEach
block ensures a clean state before each test case. The test cases use thecreateMockAccessToken
utility function for creating mock data and theexpect
function for making assertions, which are good practices. The test case names are descriptive and clearly convey the scenario being tested.
There was a problem hiding this 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 toTools
LanguageTool
[uncategorized] ~77-~77: Do not mix variants of the same word (‘organization’ and ‘organisation’) within a single text.
Context: ...sgetUserOrganizations
- get all the organizations the user has access to `getUserProfile...(EN_WORD_COHERENCY)
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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: ...sgetUserOrganizations
- 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: ...sgetUserOrganizations
- get all the organizations the user has access to `getUserProfile...(EN_WORD_COHERENCY)
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.