Repository navigation
feat(auth) expose name and picture in useSession() user - #184
Conversation
|
@artahian @omegascorp Please Guide, how may i make it better? |
…ject. Added User name and picture update in try catch block
omegascorp
left a comment
There was a problem hiding this comment.
Thank you for the PR, I've added some comments, there are also some form the bot
| emails: { address: string; verified: boolean }[]; | ||
| authMethods: string[]; | ||
| name?: string; | ||
| picture?: string; |
There was a problem hiding this comment.
avatarUrl - is more common name for this
| handle: string; | ||
| emails: { address: string; verified: boolean }[]; | ||
| authMethods: string[]; | ||
| name?: string; |
There was a problem hiding this comment.
I would suggest having firstName and lastName instead.
There was a problem hiding this comment.
For github we can just split for now (it might be wrong in some cases, but I don't see a better solution)
…tarUrl instead of picture
…tarUrl instead of picture
|
The documentation mentions that the User object contains these attributes, and I’ve updated the docs accordingly to show I have a question regarding the Do we need the Alternatively, I think GitHub username for GitHub OAuth I’d like to clarify the real role of I reviewed the same for |
Good question - and we've intentionally picked Ideally I'd like
@omegascorp I'm not sure about this part, deferring to you. But @AtulYadav25 what's the use case for having |
|
@AtulYadav25, the documentation is wrong there; the GitHub ID is stored in |
|
@omegascorp While these are the current updates
This can be an inconsistency in user data Possible Improvements
However, even with this, developers still wouldn’t have a clean way to: That makes the framework feel a bit rigid.
This function would allow updating: Also, we could update This:
Introduce a For example: auth: {
validateSignUp: ({ firstName, lastName, handle }) => {
if (!firstName) {
throw new Error("FirstName is required");
}
}
}This callback would be executed inside NEXT?To move forward, I have two approaches: Add only the OR I’m open to suggestions if there’s a better way to do this or more improvements. |
…ser in object as RawUserData and case insensitive checks
|
I’ve here completed the improvements that i comment, to make the authentication and profile system more consistent and flexible. What I Added1. Full Profile Support for All Users
2. updateProfile Mutation
3. Extended signupWithPassword
4. generateHandle Callback
5. validateSignUp Callback
6. validateProfileUpdate Callback
Testing DoneI tested all flows locally:
Everything is working as expected. This PR has large changes in the auth layer, so I understand it needs careful review. I’m fully open to adjustments, suggestions, or improvements to refine this further before merging. Please Let me know If you all like to proceed and thn I will update the documentations as well. |
omegascorp
left a comment
There was a problem hiding this comment.
Thank you, added some comments
| lastName?: string; | ||
| }; | ||
|
|
||
| type signUpArgs = { |
There was a problem hiding this comment.
Should be SignUpProps to match other types
| import { AuthErrorProps, AuthSuccessProps, User } from '@/auth/types'; | ||
| import { UpdateProfileArgs } from '@/methods/types'; | ||
|
|
||
| type GenerateHandleInput = { |
There was a problem hiding this comment.
Should be GenerateHandleProps
| */ | ||
| export type AuthConfig = { | ||
| // Optional pre-signup validation hook. | ||
| validateSignUp?: (props: signUpArgs) => void | Promise<void>; |
There was a problem hiding this comment.
Signup as a noun in other places with lowercase u, let's keep it consistent
| }; | ||
| } | ||
|
|
||
| export async function handleUpdateProfile(_args: UpdateProfileArgs, { user }: Context) { |
There was a problem hiding this comment.
There should be no underscore before args here, also args should be renamed to props for consistancy
There was a problem hiding this comment.
Should I replace all occurrences of Args with Props ?
Here , export type Args = Record<string, unknown>; in file modelence/src/methods/types.ts
There was a problem hiding this comment.
I would suggest replacing only the parts that are changed. Args is used in many places.
| import { resolveUniqueHandle } from './utils'; | ||
|
|
||
| export async function handleSignupWithPassword( | ||
| args: Args, |
There was a problem hiding this comment.
Let's rename this to props and set a proper type here
|
|
||
| export type Args = Record<string, unknown>; | ||
|
|
||
| export type UpdateProfileArgs = { |
There was a problem hiding this comment.
Let's rename to UpdateProfileProps
…lidation functions, auth hooks.
| password: string; | ||
| handle?: string; | ||
| avatarUrl?: string; | ||
| }; |
There was a problem hiding this comment.
Duplicate SignupProps type defined in two files
Low Severity
A local SignupProps type in authConfig.ts is structurally identical to the exported SignupProps from methods/types.ts. The file already imports UpdateProfileProps from that same module, so SignupProps could be imported too. Having two separate definitions risks them silently diverging if one is updated without the other, causing the validateSignup hook's type to mismatch the actual data shape passed to it.
Additional Locations (1)
| ): Promise<string> { | ||
| if (rawHandle !== undefined && rawHandle !== null && String(rawHandle).trim() !== '') { | ||
| // Caller explicitly provided a handle – validate it. | ||
| const handle = validateHandle(String(rawHandle)); |
There was a problem hiding this comment.
Handle not trimmed before validation in signup path
Low Severity
resolveUniqueHandle checks String(rawHandle).trim() !== '' to detect blank handles, but then passes the untrimmed value to validateHandle. In contrast, validateProfileFields trims handles before validation and storage. This means a handle like " abc " would be stored with whitespace during signup but trimmed to "abc" on profile update, causing inconsistent behavior across the two code paths.
|
|
||
| await getAuthConfig().validateProfileUpdate?.(props); | ||
|
|
||
| const update = validateProfileFields(props); |
There was a problem hiding this comment.
Validation hook runs before sanitization in profile update
Medium Severity
The validateProfileUpdate hook is called with raw, untrimmed props before validateProfileFields sanitizes them. This means the hook validates data that differs from what's actually persisted. For example, firstName: ' ' passes the hook as a 3-character string, but validateProfileFields then trims it to ''. In contrast, signup.ts correctly calls validateSignup after validateProfileFields, so the hook sees the sanitized data there. This inconsistency can cause custom validation logic in the hook to be silently bypassed.
Additional Locations (1)
|
|
||
| // Derive handle from the email local-part (everything before '@'). | ||
| const baseHandle = email.split('@')[0]; | ||
| return findAvailableHandle(baseHandle); |
There was a problem hiding this comment.
Email-derived handles bypass minimum length validation
Medium Severity
When no handle is supplied, resolveUniqueHandle derives one from the email local part without calling validateHandle. This means short email prefixes (e.g., [email protected]) produce handles like 'ab' that violate the 3-character minimum enforced by validateHandle and validateProfileFields. Worse, those users would later be unable to keep their own auto-assigned handle during a profile update, since validateProfileFields would reject it as too short.
|
@omegascorp Now documentation includes
|
| * | ||
| * @returns An object containing only the validated, trimmed fields that were provided. | ||
| */ | ||
| export function validateProfileFields( |
There was a problem hiding this comment.
Can we replace this via zod validation?
There was a problem hiding this comment.
@AtulYadav25, could you check this comment?
yes, I used zod and made this more clean in the latest commit 😅
|
@AtulYadav25 thank you, I've added one more comment |
…es for auto filling of missing fields from providers, in oauth-common test file
| profile = { ...profile, ...update } as typeof profile; | ||
| } catch (error) { | ||
| throw new Error('Failed to update profile.'); | ||
| } |
There was a problem hiding this comment.
Profile update catches and discards original database error
Medium Severity
The catch block around usersCollection.updateOne discards the original error and throws a generic 'Failed to update profile.' message. This hides critical diagnostic information — for example, if a TOCTOU race condition on handle uniqueness causes a MongoDB duplicate key error, the user sees a generic message instead of something actionable like "Handle already taken." It also makes server-side debugging of connection timeouts, validation failures, and other DB errors much harder.
| password, | ||
| handle, | ||
| ...profileFields, | ||
| }); |
There was a problem hiding this comment.
validateSignup receives raw handle unlike validated profile fields
Low Severity
The validateSignup hook receives handle as raw user input (untrimmed, unvalidated) while firstName, lastName, and avatarUrl are already validated and trimmed via validateProfileFields. A developer writing a validateSignup hook would see inconsistent data quality — trimmed profile fields but a raw handle with potential leading/trailing whitespace. The handle is only validated later by resolveUniqueHandle.
…ds. Fix: Throw original error from profile.ts on profile update fail. Fix: Do not return undefined values from func in auth/client/index.ts
| const generated = await authConfig.generateHandle({ | ||
| email, | ||
| ...profileFields, | ||
| }); |
There was a problem hiding this comment.
Extra props leaked to generateHandle callback in signup
Low Severity
The generateHandle callback in the signup flow receives { email, ...profileFields }, where profileFields can include avatarUrl (and other UpdateProfileProps fields) not present in GenerateHandleProps. The OAuth flow in oauth-common.ts correctly passes only { email, firstName, lastName }. A callback that iterates over all received props (e.g., using Object.values) would inadvertently incorporate avatarUrl into the handle.
Additional Locations (1)
There was a problem hiding this comment.
@AtulYadav25, could you check the cursor comments? This one is relevant.
There was a problem hiding this comment.
@AtulYadav25, could you check the cursor comments? This one is relevant.
Yup, I did a fix on this, maybe it is not visible because you might be seeing some limited last commits.
Could you please check through this all commits

For a quick review
What i made changes:
From this:
const generated = await authConfig.generateHandle({
email,
...profileFields,
});To this
const generated = await authConfig.generateHandle({
email,
firstName: profileFields.firstName,
lastName: profileFields.lastName,
});|
|
||
| suffix++; | ||
| } | ||
| } |
There was a problem hiding this comment.
Handle suffix generation can exceed max length limit
Low Severity
findAvailableHandle appends _2, _3, etc. to a base handle without enforcing the 50-character max that validateHandle requires. A generateHandle hook returning a 48+ char handle that conflicts would produce a suffixed handle exceeding 50 chars. Similarly, the email-derived path (email.split('@')[0].padEnd(3, '_')) applies no max-length check at all — RFC 5321 allows local parts up to 64 characters. These oversized handles get stored in the DB but would fail validateProfileFields validation if the user later updates their profile.
Additional Locations (1)
…: Handle suffix generation can exceed max length limit
| }; | ||
| } | ||
|
|
||
| export async function handleUpdateProfile(props: UpdateProfileProps, { user }: Context) { |
There was a problem hiding this comment.
Handler parameter type breaks mutation handler contract
Medium Severity
handleUpdateProfile declares its first parameter as UpdateProfileProps instead of Args, which is the type all other handlers use. The framework invokes every handler with handler(args, context) where args is Args (Record<string, unknown>). Every other handler in the codebase (handleSignupWithPassword, handleLoginWithPassword, getOwnProfile, handleLogout, etc.) correctly types its first parameter as Args and then narrows internally. This inconsistency gives a false sense of type safety — TypeScript treats the parameter values as string | undefined, but at runtime they are unknown — and may cause a type error when the function is assigned to the Mutations record under strict: true.
Additional Locations (1)
| await callMethod('_system.user.signupWithPassword', { | ||
| email, | ||
| password, | ||
| ...(handle ? { handle } : {}), |
There was a problem hiding this comment.
Client signupWithPassword uses inconsistent check for handle
Low Severity
The handle field uses a truthiness check (handle ?) while firstName, lastName, and avatarUrl use !== undefined. This means passing handle: '' silently omits it and the server auto-generates a handle, whereas passing firstName: '' correctly sends the empty string to the server (which then validates it). The check for handle is inconsistent with the other fields in the same function.
|
@AtulYadav25 could you check the bot's comments and resolve the conflict with main? |
…ient signupWithPassword uses inconsistent check for handle
| }); | ||
| } else { | ||
| handle = await resolveUniqueHandle(undefined, userData.email); | ||
| } |
There was a problem hiding this comment.
Config not cached; getAuthConfig() called twice for generateHandle
Low Severity
The new generateHandle integration calls getAuthConfig() twice — once to check existence and once to invoke — without caching the result. In the same PR, signup.ts properly caches it with const authConfig = getAuthConfig(). The inconsistency is a readability issue and, since getAuthConfig() returns a frozen snapshot that can be replaced by setAuthConfig, the two calls could theoretically return different objects if setAuthConfig is invoked between them by asynchronous scheduling.
| hasRole: (role: string) => boolean; | ||
| /** Throws an error if the user does not have the given role. */ | ||
| requireRole: (role: string) => void; | ||
| firstName?: string; |
There was a problem hiding this comment.
User interface missing new profile fields
Medium Severity
The User interface in types.ts is missing firstName, lastName, and avatarUrl optional fields. These fields were added to the DB schema, UserInfo, client types, and session schema, but not to the User document interface. Code across oauth-common.ts, login.ts, index.ts, and profile.ts accesses these fields on User-typed objects. This only compiles because User extends Document (MongoDB's permissive Record<string, any>), so all accesses silently resolve to any, eliminating type safety — typos like existingUser.fistName would go undetected.
Additional Locations (2)
| import { getAuthConfig } from '@/app/authConfig'; | ||
|
|
||
| export async function getOwnProfile(_args: Args, { user }: Context) { | ||
| export async function getOwnProfile(props: Args, { user }: Context) { |
There was a problem hiding this comment.
Unused parameter renamed, drops unused-variable convention
Low Severity
getOwnProfile renamed its first parameter from _args to props but never reads it. The underscore prefix was a deliberate convention to signal an intentionally unused parameter. Removing the prefix makes it look like the parameter is meant to be used, losing that intent signal.
|
@omegascorp Conflicts with main have been resolved. Apologies for so delayed updates on PR.. For resolving the conflicts,
|
| .trim() | ||
| .max(opts.max, { message: `must be at most ${opts.max} characters` }) | ||
| .transform((val) => (val === '' ? undefined : val)) | ||
| .optional(); |
There was a problem hiding this comment.
Transform converts empty strings to undefined, mismatching tests and intent
Medium Severity
The trimmedOptionalString schema includes .transform((val) => (val === '' ? undefined : val)) which converts empty strings to undefined. This contradicts the test expectations at lines 91–93 and 96–98, which expect { firstName: '' } to remain after validation. In production, this means updateProfile({ firstName: '' }) would pass { firstName: undefined } to MongoDB's $set, which stores null — creating inconsistency with backfill checks that use === undefined.
Additional Locations (1)
| .string() | ||
| .trim() | ||
| .min(opts.min ?? 1, { message: `must be at least ${opts.min ?? 1} characters` }) | ||
| .max(opts.max, { message: `must be at most ${opts.max} characters` }); |
There was a problem hiding this comment.
Handle empty-string error message doesn't match test expectations
Medium Severity
When handle is '' or whitespace-only, the trimmedNonEmptyString min-length check produces the error "handle: must be at least 3 characters" via the generic formatting in validateProfileFields. The tests expect the error message "handle cannot be empty.", which is not a substring of the actual error, causing test failures. The validator lacks a distinct empty-input error path.
Additional Locations (1)
|
|
||
| await authenticateUser(res, existingUser._id); | ||
| //Add User FirstName,LastName, AvatarURL if not exists | ||
| const update: Partial<OAuthUserData> = {}; |
There was a problem hiding this comment.
Overly broad type allows non-profile fields in $set
Low Severity
The update and profileUpdate variables are typed as Partial<OAuthUserData>, which includes id, email, emailVerified, and providerName — fields that must never be part of a user document $set operation. While the runtime code currently only assigns profile fields, this loose typing doesn't prevent accidental assignment of dangerous fields like email or providerName directly onto the user document. A narrower type like Partial<Pick<OAuthUserData, 'firstName' | 'lastName' | 'avatarUrl'>> would make the intent explicit and prevent misuse.
Additional Locations (1)
| if (Object.keys(update).length > 0) { | ||
| try { | ||
| await usersCollection.updateOne({ _id: profile._id }, { $set: update }); | ||
| profile = { ...profile, ...update } as typeof profile; |
There was a problem hiding this comment.
Empty string clearing produces undefined values in MongoDB $set
Medium Severity
When a user tries to clear a profile field by passing an empty string (e.g., updateProfile({ firstName: '' })), validateProfileFields transforms it to { firstName: undefined }. This object then passes the Object.keys(update).length > 0 check and gets sent to MongoDB as $set: { firstName: undefined }. With the MongoDB Node.js driver v6, undefined is serialized as BSON null, so the field ends up as null instead of being properly removed with $unset. The in-memory merge profile = { ...profile, ...update } also applies the undefined value, so the API response may diverge from the database state depending on BSON serialization settings.
…et. Fix: Overly broad type allows non-profile fields in oauth-common.ts
| } | ||
|
|
||
| suffix++; | ||
| } |
There was a problem hiding this comment.
Unbounded loop in handle suffix generation
Low Severity
findAvailableHandle uses a while (true) loop that increments a suffix and queries the database on each iteration with no upper bound. If many handles share the same base (e.g., via automated signups), this could issue a large number of sequential DB queries, degrading performance or effectively hanging the signup request. A maximum iteration limit with a fallback (or random suffix) would make this resilient.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
|
|
||
| throw new Error( | ||
| `Could not generate a unique handle for base "${baseHandle}" after exhausting all attempts.` | ||
| ); |
There was a problem hiding this comment.
Handle resolution performs many sequential DB queries
Low Severity
findAvailableHandle checks handle availability one candidate at a time via sequential findOne calls — up to 1 + 50 + 10 = 61 round trips in the worst case. This runs during user-facing signup (both OAuth and password). For popular base handles, this could add significant latency. A single batch query using $in to check multiple candidates at once would be much more efficient.
|
Thank you @AtulYadav25, testing |
omegascorp
left a comment
There was a problem hiding this comment.
Thank you @AtulYadav25, appoved.
Thanks @omegascorp ! 🤝 |



This PR fixes the authentication flow by exposing
nameandpicturefields on theuserobject returned from:Previously, although OAuth providers (Google/GitHub) returned profile data such as name and avatar, these fields were not:
UserInfoTypeScript typeAs a result, accessing
user.nameoruser.picturecaused TypeScript errors.This PR resolves that issue.
1. OAuth Providers (Google & GitHub)
nameand avatar (picture/avatar_url) from provider APIsI tried doing console log of users data fetched from the providers


Result
2. Database Schema Update
nameandpicturefields to user schema3. Authentication Flow Update
authenticatenow returnsnameandpicturealsogetOwnProfileincludes profile fields ofnameandpicture4. Type Updates
Updated
UserInfotype:5. Client Session Update
packages/modelence/src/client/session.tsnameandpictureoptionallyuseSession()now properly exposes them6. auth-ui Update
UserProfilecomponentTesting
pnpm buildpnpm packnameandpicturenameandavatar_urluseSession()includes required fieldsScreenshot are attached: useSession() use returns the

nameandpicture:Note
Medium Risk
Touches core authentication/signup/OAuth linking and introduces new DB fields and handle resolution logic, which could affect account creation/login behavior and uniqueness constraints if edge cases aren’t covered.
Overview
Modelence auth now persists and exposes user profile fields (
firstName,lastName,avatarUrl) end-to-end: stored in_modelenceUsers, returned fromauthenticate/login, included ingetOwnProfile, and surfaced inuseSession()/clientUserInfo.OAuth (Google/GitHub) now extracts these fields from provider responses and backfills missing profile fields for existing users on login/auto-link, while new users get a unique handle via a new
AuthConfig.generateHandlehook (with automatic conflict suffixing) or email-derived fallback.Email/password signup is extended to accept optional profile fields + custom
handle, runs a newAuthConfig.validateSignuphook, resolves unique handles via newauth/utils.ts, and a newupdateProfilemutation/client API adds validated profile edits with optionalvalidateProfileUpdate. Docs and@modelence/auth-uiUserProfileare updated to reflect/show these profile fields.Written by Cursor Bugbot for commit 80c4ebd. This will update automatically on new commits. Configure here.