diff --git a/spec/ParseUser.spec.js b/spec/ParseUser.spec.js index 0380589057..c76a28ec6f 100644 --- a/spec/ParseUser.spec.js +++ b/spec/ParseUser.spec.js @@ -193,6 +193,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 241edf9771..55aca93891 100644 --- a/src/Config.js +++ b/src/Config.js @@ -123,6 +123,7 @@ export class Config { pages, security, enforcePrivateUsers, + autoSignupOnLogin, enableInsecureAuthAdapters, schema, requestKeywordDenylist, @@ -165,6 +166,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); @@ -218,6 +220,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 66c1d8bcea..6dc4fddbc5 100644 --- a/src/Options/Definitions.js +++ b/src/Options/Definitions.js @@ -491,6 +491,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 9569239ef7..d0c3e2c225 100644 --- a/src/Options/docs.js +++ b/src/Options/docs.js @@ -87,6 +87,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 {Union} publicServerURL Optional. The public URL to Parse Server. This URL will be used to reach Parse Server publicly for features like password reset and email verification links. The option can be set to a string or a function that can be asynchronously resolved. The returned URL string must start 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 cdeb7cd846..5623dac445 100644 --- a/src/Options/index.js +++ b/src/Options/index.js @@ -193,6 +193,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 3828e465e7..3b048ec15e 100644 --- a/src/Routers/UsersRouter.js +++ b/src/Routers/UsersRouter.js @@ -201,8 +201,51 @@ 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. + 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 Auth.checkIfUserHasProvidedConfiguredProvidersForLogin( req, @@ -256,10 +299,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.' + ); + } } } @@ -287,7 +332,6 @@ export class UsersRouter extends ClassesRouter { {} ); } - const { sessionData, createSession } = RestWrite.createSession(req.config, { userId: user.objectId, createdWith: { @@ -319,6 +363,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 @@ -664,7 +785,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, diff --git a/types/Options/index.d.ts b/types/Options/index.d.ts index ad11050648..56c626af8a 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);