Skip to content

Conversation

@tsl-ps2
Copy link
Collaborator

@tsl-ps2 tsl-ps2 commented Apr 22, 2025

This allows us to customize the MinimalProfile.

Summary by CodeRabbit

  • New Features

    • Added support for customizable profile transformation when logging in and updating profile settings.
    • Introduced utility functions to extract and transform profile data for flexible integration.
    • Extended publicly available profile-related type definitions.
  • Improvements

    • Enhanced type safety and flexibility for profile management, allowing components and hooks to work with extended or minimal profile types.
    • Profile-related hooks and components now accept optional customization functions for profile data handling.
  • Bug Fixes

    • Improved handling of profile image URLs to ensure consistent absolute paths.
  • Refactor

    • Centralized profile transformation logic, reducing code duplication and enabling easier customization.

@changeset-bot
Copy link

changeset-bot bot commented Apr 22, 2025

⚠️ No Changeset found

Latest commit: ed61088

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Apr 22, 2025

Walkthrough

This update introduces a more flexible and extensible approach to handling user profile data within the authentication and profile modules. The core changes include the addition of customizable utility functions for transforming user and profile data, the introduction of a generic profile hook, and the expansion of type definitions to support arbitrary profile properties. Several components and hooks now accept optional transformation functions as props or options, allowing for tailored profile data extraction and manipulation. Type safety and modularity are improved throughout, with explicit support for custom and minimal profile representations.

Changes

Files/Paths Change Summary
packages/authentication/index.ts, types/profile.ts Added export of all types from ./types/profile and introduced CustomProfile type as an extension of MinimalProfile with arbitrary properties.
packages/authentication/modules/access/useLogin/index.ts, types.ts, utils.ts Refactored useLogin hook to use an injectable getCustomProfile function for profile transformation; updated types to support this; added utility function for constructing custom profiles from users.
packages/authentication/modules/access/index.ts Added named export of getCustomProfile utility function.
packages/authentication/modules/profile/index.ts Removed export of type MinimalProfile.
packages/authentication/modules/profile/useCurrentProfile/index.ts Changed internal and exported types from MinimalProfile to generic/custom profiles; made the useCurrentProfile hook generic for flexible profile typing; updated atom and setter logic accordingly.
packages/components/modules/profiles/web/ProfileSettingsComponent/index.tsx, types.ts, utils.ts Updated component to accept an optional getMinimalProfile prop; replaced inline minimal profile construction with utility function; expanded prop types and added new utility for extracting minimal profile.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant useLogin
    participant getCustomProfile
    participant setCurrentProfile

    User->>useLogin: Initiate login
    useLogin->>getCustomProfile: Transform User to CustomProfile
    getCustomProfile-->>useLogin: Return CustomProfile
    useLogin->>setCurrentProfile: Save CustomProfile
Loading
sequenceDiagram
    participant ProfileSettingsComponent
    participant getMinimalProfile
    participant updateProfileIfActive

    ProfileSettingsComponent->>getMinimalProfile: Transform Profile data
    getMinimalProfile-->>ProfileSettingsComponent: Return MinimalProfile
    ProfileSettingsComponent->>updateProfileIfActive: Update profile with MinimalProfile
Loading

Poem

In the warren of code where profiles reside,
Now bunnies can shape them with functions applied.
Custom or minimal, just pick what you need—
With types that expand and utilities freed.
From login to settings, the logic’s more neat,
So hop on, dear dev, and enjoy this new treat!
🥕✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/authentication/modules/access/index.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /packages/authentication/.eslintrc.js
Error: Cannot find module '@baseapp-frontend/config/.eslintrc.js'
Require stack:

  • /packages/authentication/.eslintrc.js
  • /node_modules/.pnpm/@eslint+eslintrc@2.1.4/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Module._load (node:internal/modules/cjs/loader:1074:27)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/packages/authentication/.eslintrc.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a3782f and fa8f3c4.

📒 Files selected for processing (1)
  • packages/authentication/modules/access/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/authentication/modules/access/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Component Test Packages
  • GitHub Check: Build and Lint Packages

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this 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

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

🔭 Outside diff range comments (1)
packages/authentication/modules/profile/useCurrentProfile/index.ts (1)

48-60: ⚠️ Potential issue

Parameter type of saveCurrentProfile is too wide

saveCurrentProfile currently requires CustomProfile | null, yet we call it with TProfile | null.
When TProfile is narrower than CustomProfile (e.g. plain MinimalProfile), TypeScript will error because the argument is not guaranteed to satisfy the index signature of Record<string, any>.

-  const saveCurrentProfile = (newProfile: CustomProfile | null) => {
+  const saveCurrentProfile = (newProfile: TProfile | null) => {

This simple change aligns the helper with the public contract of the hook and removes the need for unsafe casts in the caller.

🧹 Nitpick comments (5)
packages/authentication/modules/access/useLogin/utils.ts (1)

5-6: Consider adding error handling for missing environment variable.

While the optional chaining (?.) protects against undefined NEXT_PUBLIC_API_BASE_URL, if it's undefined, this would result in concatenating "undefined" with the image path, creating an invalid URL.

-  const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace('/v1', '')
+  const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace('/v1', '') || ''
packages/components/modules/profiles/web/ProfileSettingsComponent/index.tsx (1)

113-114: Consider adding a null check before applying transformation.

While the outer if (profile) check prevents calling the transformation on null profiles, including an explicit null check before using the result would make the code more defensive.

-      const minimalProfileData = getMinimalProfile(profile)
-      updateProfileIfActive(minimalProfileData)
+      const minimalProfileData = getMinimalProfile(profile)
+      if (minimalProfileData) {
+        updateProfileIfActive(minimalProfileData)
+      }
packages/authentication/modules/profile/useCurrentProfile/index.ts (3)

26-26: profileAtom should store TProfile, not always CustomProfile

Because the hook is now generic, keeping the atom fixed to CustomProfile forces a down‑cast every time we read or write the value.
Parameterising the atom eliminates unnecessary casts and prevents accidental property leakage.

-export const profileAtom = atom<CustomProfile | null>(initialProfile)
+export const profileAtom = atom<TProfile | null>(initialProfile)

Note: this requires profileAtom to be declared inside the generic hook or moved to a factory helper, otherwise TProfile is out of scope.


64-67: updateProfileIfActive mutates the current profile but widens the type

Spreading two generics (currentProfile and newProfile) produces TProfile & Partial<TProfile>, which TypeScript simplifies to an anonymous object.
Subsequently passing that object to saveCurrentProfile (after the fix above) may fail to satisfy TProfile if optional fields become required again.

Consider enforcing the return type explicitly:

saveCurrentProfile({ ...currentProfile, ...newProfile } as TProfile)

or, even better, use a utility like deepMerge<TProfile>() that preserves the original type.


70-78: typeof window === typeof undefined is a fragile SSR check

The conventional pattern is typeof window === 'undefined'.
Comparing to typeof undefined works but is obscure and might confuse future maintainers.

-  const isSSR = typeof window === typeof undefined
+  const isSSR = typeof window === 'undefined'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 25921df and 6a3782f.

📒 Files selected for processing (10)
  • packages/authentication/index.ts (1 hunks)
  • packages/authentication/modules/access/useLogin/index.ts (3 hunks)
  • packages/authentication/modules/access/useLogin/types.ts (2 hunks)
  • packages/authentication/modules/access/useLogin/utils.ts (1 hunks)
  • packages/authentication/modules/profile/index.ts (0 hunks)
  • packages/authentication/modules/profile/useCurrentProfile/index.ts (3 hunks)
  • packages/authentication/types/profile.ts (1 hunks)
  • packages/components/modules/profiles/web/ProfileSettingsComponent/index.tsx (2 hunks)
  • packages/components/modules/profiles/web/ProfileSettingsComponent/types.ts (1 hunks)
  • packages/components/modules/profiles/web/ProfileSettingsComponent/utils.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/authentication/modules/profile/index.ts
🧰 Additional context used
🧬 Code Graph Analysis (6)
packages/components/modules/profiles/web/ProfileSettingsComponent/types.ts (1)
packages/authentication/types/profile.ts (1)
  • CustomProfile (8-8)
packages/authentication/modules/access/useLogin/utils.ts (2)
packages/authentication/types/user.ts (1)
  • User (3-15)
packages/authentication/types/profile.ts (1)
  • CustomProfile (8-8)
packages/authentication/modules/access/useLogin/types.ts (2)
packages/authentication/types/user.ts (1)
  • User (3-15)
packages/authentication/types/profile.ts (1)
  • CustomProfile (8-8)
packages/components/modules/profiles/web/ProfileSettingsComponent/index.tsx (2)
packages/components/modules/profiles/web/ProfileSettingsComponent/types.ts (1)
  • ProfileSettingsComponentProps (8-11)
packages/components/modules/profiles/web/ProfileSettingsComponent/utils.ts (1)
  • getMinimalProfile (3-8)
packages/authentication/modules/access/useLogin/index.ts (1)
packages/authentication/modules/access/useLogin/utils.ts (1)
  • getCustomProfile (4-17)
packages/authentication/modules/profile/useCurrentProfile/index.ts (4)
packages/utils/types/server.ts (1)
  • ServerSideRenderingOption (1-8)
packages/utils/functions/cookie/index.ts (1)
  • getCookie (13-25)
packages/authentication/types/profile.ts (2)
  • CustomProfile (8-8)
  • MinimalProfile (1-6)
packages/authentication/modules/profile/useCurrentProfile/constants.ts (1)
  • CURRENT_PROFILE_KEY (1-1)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (12)
packages/authentication/types/profile.ts (1)

8-8: Good extension of MinimalProfile to support additional properties.

The new CustomProfile type allows for adding arbitrary properties to the base profile, enabling more flexible profile data handling across the application. Consider whether using Record<string, any> provides the right balance between flexibility and type safety for your use case.

packages/components/modules/profiles/web/ProfileSettingsComponent/utils.ts (1)

3-8: Well-structured utility function for profile extraction.

This utility function nicely encapsulates the logic for extracting minimal profile data from a larger profile object. The use of nullish coalescing operators (??) provides safe handling of optional fields, and the function's structure makes it easy to understand and maintain.

packages/authentication/modules/access/useLogin/types.ts (1)

11-12: Good addition of customizable profile transformation.

Adding the optional getCustomProfile function parameter allows consumers to customize how user data is transformed into profile data, improving the hook's flexibility while maintaining backward compatibility.

Also applies to: 22-22

packages/authentication/index.ts (1)

18-18: Good addition to the public API exports.

Exporting the profile types makes the new CustomProfile type and other profile-related types available to consumers of the package, completing the implementation of the customizable profile feature.

packages/authentication/modules/access/useLogin/utils.ts (2)

4-17: Nice implementation of the customizable profile utility function.

The function efficiently handles both relative and absolute image URLs, ensuring consistent profile image paths across the application. The approach of extracting this logic into a separate utility makes the code more modular and reusable.


5-5: Follow up on the TODO comment.

There's a comment about handling absolute image paths on the backend. Consider creating a ticket to track this improvement if it's not already being addressed.

This client-side URL manipulation might be unnecessary if the backend could consistently provide absolute image URLs.

packages/components/modules/profiles/web/ProfileSettingsComponent/types.ts (1)

1-11: Good addition of customizable profile transformation function.

Adding the optional getMinimalProfile prop creates a flexible extension point that allows consumers to customize how profile data is transformed and used, which aligns well with the JWT profile customization objective.

packages/authentication/modules/access/useLogin/index.ts (3)

35-35: Clear import with descriptive name.

Good practice to import the default implementation with a descriptive name that indicates its purpose.


45-45: Good implementation of optional parameter with default.

The addition of the optional getCustomProfile parameter with a default implementation follows good design patterns for customizable behavior.


64-65: Excellent refactoring to use the custom profile transformer.

Replacing the inline logic with a call to the configurable getCustomProfile function improves modularity and makes the code more maintainable. This change aligns well with the PR's objective of making JWT profiles customizable.

packages/components/modules/profiles/web/ProfileSettingsComponent/index.tsx (2)

39-44: Good implementation of customizable profile transformation.

The import of the default implementation and providing it as a default value for the optional prop follows best practices for creating extensible components.


111-116:

✅ Verification successful

Verify the useEffect dependency array consistency.

While the code now correctly uses the customizable profile transformation function, the dependency array lists individual profile properties that might not match what getMinimalProfile actually uses.

If getMinimalProfile accesses more properties than those listed in the dependency array, consider simplifying to just use [profile, getMinimalProfile, updateProfileIfActive] to avoid potential stale closures.


🏁 Script executed:

#!/bin/bash
# Check what properties getMinimalProfile accesses in its implementation
rg "getMinimalProfile.+\{" -A 10 "packages/components/modules/profiles/web/ProfileSettingsComponent/utils.ts"

Length of output: 319


Dependency array correctly reflects getMinimalProfile usage

The effect lists precisely the properties (id, name, urlPath?.path, image?.url) that getMinimalProfile reads, so there’s no mismatch between what’s accessed and what’s watched. You can keep the array as‑is or, if you prefer a more concise form, replace it with a single dependency on profile (the imported getMinimalProfile is static and doesn’t need to be listed).

Comment on lines 17 to 21
export const getProfileFromCookie = ({ noSSR = true }: ServerSideRenderingOption = {}) => {
const settings =
getCookie<MinimalProfile | undefined>(CURRENT_PROFILE_KEY, { noSSR, parseJSON: true }) ?? null
getCookie<CustomProfile | undefined>(CURRENT_PROFILE_KEY, { noSSR, parseJSON: true }) ?? null

return settings
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Cookie‑fetch should respect the generic profile (TProfile) you advertise

getProfileFromCookie is hard‑coded to return CustomProfile, yet the public hook advertises a generic TProfile.
If a caller narrows TProfile to something stricter than CustomProfile, we silently cast the broader cookie value down to the narrower type, losing type safety.

-  const settings =
-    getCookie<CustomProfile | undefined>(CURRENT_PROFILE_KEY, { noSSR, parseJSON: true }) ?? null
+  const settings =
+    getCookie<TProfile | undefined>(CURRENT_PROFILE_KEY, { noSSR, parseJSON: true }) ?? null

Applying the same generic here ensures compile‑time guarantees that the cookie really contains the profile shape the consumer expects.

📝 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
export const getProfileFromCookie = ({ noSSR = true }: ServerSideRenderingOption = {}) => {
const settings =
getCookie<MinimalProfile | undefined>(CURRENT_PROFILE_KEY, { noSSR, parseJSON: true }) ?? null
getCookie<CustomProfile | undefined>(CURRENT_PROFILE_KEY, { noSSR, parseJSON: true }) ?? null
return settings
export const getProfileFromCookie = ({ noSSR = true }: ServerSideRenderingOption = {}) => {
const settings =
getCookie<TProfile | undefined>(CURRENT_PROFILE_KEY, { noSSR, parseJSON: true }) ?? null
return settings
}

@anicioalexandre anicioalexandre force-pushed the fen-229-permissions-baseapp branch from fa8f3c4 to ed61088 Compare May 6, 2025 13:58
@sonarqubecloud
Copy link

sonarqubecloud bot commented May 6, 2025

@anicioalexandre anicioalexandre deleted the fen-229-permissions-baseapp branch May 7, 2025 14:23
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.

3 participants