From 486a4056240d0120b14ee45efa0d69c8de383134 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Tue, 7 Oct 2025 21:49:45 +0700 Subject: [PATCH 1/2] feat: added autosignuponlogin --- spec/ParseUser.spec.js | 26 +++++++++ src/Config.js | 8 +++ src/Options/Definitions.js | 7 +++ src/Options/docs.js | 1 + src/Options/index.js | 5 ++ src/Routers/UsersRouter.js | 106 ++++++++++++++++++++++++++++++++++++- types/Options/index.d.ts | 1 + 7 files changed, 153 insertions(+), 1 deletion(-) diff --git a/spec/ParseUser.spec.js b/spec/ParseUser.spec.js index ba34fbf6e9..611c260fe0 100644 --- a/spec/ParseUser.spec.js +++ b/spec/ParseUser.spec.js @@ -186,6 +186,32 @@ describe('Parse.User testing', () => { }); }); + it('auto signs up user on login when enabled', async () => { + await reconfigureServer({ autoSignupOnLogin: true }); + const username = 'autoLoginUser'; + const password = 'autoLoginPass'; + const response = await request({ + method: 'POST', + url: 'http://localhost:8378/1/login', + headers: { + 'X-Parse-Application-Id': Parse.applicationId, + 'X-Parse-REST-API-Key': 'rest', + 'Content-Type': 'application/json', + }, + body: { + username, + password, + }, + }); + expect(response.data.username).toBe(username); + expect(response.data.sessionToken).toBeDefined(); + + const user = await Parse.User.logIn(username, password); + expect(user).toBeDefined(); + await Parse.User.logOut(); + await reconfigureServer({ autoSignupOnLogin: false }); + }); + it('user login', async done => { await Parse.User.signUp('asdf', 'zxcv'); const user = await Parse.User.logIn('asdf', 'zxcv'); diff --git a/src/Config.js b/src/Config.js index bf6d50626c..674ae748bd 100644 --- a/src/Config.js +++ b/src/Config.js @@ -85,6 +85,7 @@ export class Config { pages, security, enforcePrivateUsers, + autoSignupOnLogin, enableInsecureAuthAdapters, schema, requestKeywordDenylist, @@ -131,6 +132,7 @@ export class Config { this.validateSecurityOptions(security); this.validateSchemaOptions(schema); this.validateEnforcePrivateUsers(enforcePrivateUsers); + this.validateAutoSignupOnLogin(autoSignupOnLogin); this.validateEnableInsecureAuthAdapters(enableInsecureAuthAdapters); this.validateAllowExpiredAuthDataToken(allowExpiredAuthDataToken); this.validateRequestKeywordDenylist(requestKeywordDenylist); @@ -183,6 +185,12 @@ export class Config { } } + static validateAutoSignupOnLogin(autoSignupOnLogin) { + if (typeof autoSignupOnLogin !== 'boolean') { + throw 'Parse Server option autoSignupOnLogin must be a boolean.'; + } + } + static validateAllowExpiredAuthDataToken(allowExpiredAuthDataToken) { if (typeof allowExpiredAuthDataToken !== 'boolean') { throw 'Parse Server option allowExpiredAuthDataToken must be a boolean.'; diff --git a/src/Options/Definitions.js b/src/Options/Definitions.js index ab25b1017d..3438996263 100644 --- a/src/Options/Definitions.js +++ b/src/Options/Definitions.js @@ -482,6 +482,13 @@ module.exports.ParseServerOptions = { action: parsers.booleanParser, default: false, }, + autoSignupOnLogin: { + env: 'PARSE_SERVER_AUTO_SIGNUP_ON_LOGIN', + help: + 'Set to `true` to automatically create a user when calling the login endpoint with username/email and password if no matching user exists.

Default is `false`.', + action: parsers.booleanParser, + default: false, + }, protectedFields: { env: 'PARSE_SERVER_PROTECTED_FIELDS', help: 'Protected fields that should be treated with extra security when fetching details.', diff --git a/src/Options/docs.js b/src/Options/docs.js index 0a8df6d137..f7a0e81845 100644 --- a/src/Options/docs.js +++ b/src/Options/docs.js @@ -86,6 +86,7 @@ * @property {Boolean} preserveFileName Enable (or disable) the addition of a unique hash to the file names * @property {Boolean} preventLoginWithUnverifiedEmail Set to `true` to prevent a user from logging in if the email has not yet been verified and email verification is required.

Default is `false`.
Requires option `verifyUserEmails: true`. * @property {Boolean} preventSignupWithUnverifiedEmail If set to `true` it prevents a user from signing up if the email has not yet been verified and email verification is required. In that case the server responds to the sign-up with HTTP status 400 and a Parse Error 205 `EMAIL_NOT_FOUND`. If set to `false` the server responds with HTTP status 200, and client SDKs return an unauthenticated Parse User without session token. In that case subsequent requests fail until the user's email address is verified.

Default is `false`.
Requires option `verifyUserEmails: true`. + * @property {Boolean} autoSignupOnLogin Set to `true` to automatically create a user when calling the login endpoint with username/email and password if no matching user exists. Default is `false`. * @property {ProtectedFields} protectedFields Protected fields that should be treated with extra security when fetching details. * @property {String} publicServerURL Public URL to your parse server with http:// or https://. * @property {Any} push Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications diff --git a/src/Options/index.js b/src/Options/index.js index 9f70700345..d21cdfe57b 100644 --- a/src/Options/index.js +++ b/src/Options/index.js @@ -190,6 +190,11 @@ export interface ParseServerOptions { Requires option `verifyUserEmails: true`. :DEFAULT: false */ preventSignupWithUnverifiedEmail: ?boolean; + /* Set to `true` to automatically create a user when calling the login endpoint with username/email and password if no matching user exists. +

+ Default is `false`. + :DEFAULT: false */ + autoSignupOnLogin: ?boolean; /* Set the validity duration of the email verification token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.

For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours). diff --git a/src/Routers/UsersRouter.js b/src/Routers/UsersRouter.js index 7668562965..4a36224742 100644 --- a/src/Routers/UsersRouter.js +++ b/src/Routers/UsersRouter.js @@ -199,8 +199,23 @@ export class UsersRouter extends ClassesRouter { } async handleLogIn(req) { - const user = await this._authenticateUserFromRequest(req); const authData = req.body && req.body.authData; + let user; + let signupSessionToken; + + try { + user = await this._authenticateUserFromRequest(req); + } catch (error) { + const autoSignupCredentials = this._prepareAutoSignupCredentials(req, error); + if (!autoSignupCredentials) { + throw error; + } + // Create the missing user but continue through the standard login path so + // that all login-time policies, triggers, and session metadata remain unchanged. + signupSessionToken = await this._autoSignupOnLogin(req, autoSignupCredentials); + user = await this._authenticateUserFromRequest(req); + } + // Check if user has provided their required auth providers Auth.checkIfUserHasProvidedConfiguredProvidersForLogin( req, @@ -299,6 +314,18 @@ export class UsersRouter extends ClassesRouter { await createSession(); + if (signupSessionToken) { + // Discard the session issued by the signup shortcut; the login session we just + // created is the single source of truth for the client. + try { + await req.config.database.destroy('_Session', { sessionToken: signupSessionToken }); + } catch (sessionError) { + if (sessionError && sessionError.code !== Parse.Error.OBJECT_NOT_FOUND) { + logger.warn('Failed to clean up auto sign-up session token', sessionError); + } + } + } + const afterLoginUser = Parse.User.fromJSON(Object.assign({ className: '_User' }, user)); await maybeRunTrigger( TriggerTypes.afterLogin, @@ -317,6 +344,83 @@ export class UsersRouter extends ClassesRouter { return { response: user }; } + + _getLoginPayload(req) { + let source = req.body || {}; + if ( + (!source.username && req.query && req.query.username) || + (!source.email && req.query && req.query.email) + ) { + source = req.query; + } + return { + username: source.username, + email: source.email, + password: source.password, + }; + } + + // Returns data for auto-signup if autoSignupOnLogin is true and the error is that the user doesn't exist. + // If the conditions don't match, we return `null`. + // This gathers minimal credentials so that the signup path can rely on RestWrite's own validation. + _prepareAutoSignupCredentials(req, error) { + if (!req.config.autoSignupOnLogin) { + return null; + } + if (!(error instanceof Parse.Error) || error.code !== Parse.Error.OBJECT_NOT_FOUND) { + return null; + } + if (req.body && req.body.authData) { + return null; + } + const payload = this._getLoginPayload(req); + const rawUsername = typeof payload.username === 'string' ? payload.username.trim() : ''; + const rawEmail = typeof payload.email === 'string' ? payload.email.trim() : ''; + const password = payload.password; + const hasUsername = rawUsername.length > 0; + const hasEmail = rawEmail.length > 0; + if (!hasUsername && !hasEmail) { + return null; + } + if (typeof password !== 'string') { + return null; + } + return { + username: hasUsername ? rawUsername : rawEmail, + email: hasEmail ? rawEmail : undefined, + password, + }; + } + + async _autoSignupOnLogin(req, credentials) { + const userData = { + username: credentials.username, + password: credentials.password, + }; + if (credentials.email !== undefined) { + userData.email = credentials.email; + } + // Just call the existing user creation flow so we get all schema checks, triggers, + // adapters, and side effects exactly once. + // As for params validation, RestWrite's validateAuthData will handle the validation of the params internally anyway. + const result = await rest.create( + req.config, + req.auth, + '_User', + userData, + req.info.clientSDK, + req.info.context + ); + const user = result?.response; + if (!user) { + throw new Parse.Error( + Parse.Error.INTERNAL_SERVER_ERROR, + 'Unable to automatically sign up user.' + ); + } + return user.sessionToken; + } + /** * This allows master-key clients to create user sessions without access to * user credentials. This enables systems that can authenticate access another diff --git a/types/Options/index.d.ts b/types/Options/index.d.ts index ac1c71e886..99d4045ad6 100644 --- a/types/Options/index.d.ts +++ b/types/Options/index.d.ts @@ -77,6 +77,7 @@ export interface ParseServerOptions { verifyUserEmails?: (boolean | void); preventLoginWithUnverifiedEmail?: boolean; preventSignupWithUnverifiedEmail?: boolean; + autoSignupOnLogin?: boolean; emailVerifyTokenValidityDuration?: number; emailVerifyTokenReuseIfValid?: boolean; sendUserEmailVerification?: (boolean | void); From 3dbb398e8ca3c119ebbb7b2c22114b9c6c2f96da Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Thu, 9 Oct 2025 19:01:44 +0700 Subject: [PATCH 2/2] followed suggestions to some degree --- src/Routers/UsersRouter.js | 59 ++++++++++++++++++++++++-------------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/src/Routers/UsersRouter.js b/src/Routers/UsersRouter.js index 4a36224742..fbc9a8a303 100644 --- a/src/Routers/UsersRouter.js +++ b/src/Routers/UsersRouter.js @@ -212,8 +212,36 @@ export class UsersRouter extends ClassesRouter { } // Create the missing user but continue through the standard login path so // that all login-time policies, triggers, and session metadata remain unchanged. - signupSessionToken = await this._autoSignupOnLogin(req, autoSignupCredentials); - user = await this._authenticateUserFromRequest(req); + try { + signupSessionToken = await this._autoSignupOnLogin(req, autoSignupCredentials); + } catch (signupError) { + // Another request created the user or user exists with wrong password + // we try authenticating again in that case; if it works then it works. + // and we continue with the "usual" login flow. + if (signupError.code === Parse.Error.DUPLICATE_VALUE || + signupError.code === Parse.Error.USERNAME_TAKEN || + signupError.code === Parse.Error.EMAIL_TAKEN) { + user = await this._authenticateUserFromRequest(req); + } else { + throw signupError; + } + } + if (signupSessionToken) { + // Discard the session issued by the signup shortcut; the login session we just + // created is the single source of truth for the client. + try { + await req.config.database.destroy('_Session', { sessionToken: signupSessionToken }); + } catch (sessionError) { + if (sessionError && sessionError.code !== Parse.Error.OBJECT_NOT_FOUND) { + logger.warn('Failed to clean up auto sign-up session token', sessionError); + } + } + } + // If no user was set from the catch-clause (no race condition) + // then we simply authenticate the user as usual. + if (!user) { + user = await this._authenticateUserFromRequest(req); + } } // Check if user has provided their required auth providers @@ -269,10 +297,12 @@ export class UsersRouter extends ClassesRouter { ); if (expiresAt < new Date()) // fail of current time is past password expiry time - { throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Your password has expired. Please reset your password.' - ); } + { + throw new Parse.Error( + Parse.Error.OBJECT_NOT_FOUND, + 'Your password has expired. Please reset your password.' + ); + } } } @@ -300,7 +330,6 @@ export class UsersRouter extends ClassesRouter { {} ); } - const { sessionData, createSession } = RestWrite.createSession(req.config, { userId: user.objectId, createdWith: { @@ -314,18 +343,6 @@ export class UsersRouter extends ClassesRouter { await createSession(); - if (signupSessionToken) { - // Discard the session issued by the signup shortcut; the login session we just - // created is the single source of truth for the client. - try { - await req.config.database.destroy('_Session', { sessionToken: signupSessionToken }); - } catch (sessionError) { - if (sessionError && sessionError.code !== Parse.Error.OBJECT_NOT_FOUND) { - logger.warn('Failed to clean up auto sign-up session token', sessionError); - } - } - } - const afterLoginUser = Parse.User.fromJSON(Object.assign({ className: '_User' }, user)); await maybeRunTrigger( TriggerTypes.afterLogin, @@ -359,7 +376,7 @@ export class UsersRouter extends ClassesRouter { password: source.password, }; } - + // Returns data for auto-signup if autoSignupOnLogin is true and the error is that the user doesn't exist. // If the conditions don't match, we return `null`. // This gathers minimal credentials so that the signup path can rely on RestWrite's own validation. @@ -724,7 +741,7 @@ export class UsersRouter extends ClassesRouter { const userString = req.auth && req.auth.user ? req.auth.user.id : undefined; logger.error( `Failed running auth step challenge for ${provider} for user ${userString} with Error: ` + - JSON.stringify(e), + JSON.stringify(e), { authenticationStep: 'challenge', error: e,