Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions spec/ParseUser.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
8 changes: 8 additions & 0 deletions src/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export class Config {
pages,
security,
enforcePrivateUsers,
autoSignupOnLogin,
enableInsecureAuthAdapters,
schema,
requestKeywordDenylist,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.';
Expand Down
7 changes: 7 additions & 0 deletions src/Options/Definitions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.<br><br>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.',
Expand Down
1 change: 1 addition & 0 deletions src/Options/docs.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Options/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
<br><br>
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.
<br><br>
For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).
Expand Down
106 changes: 105 additions & 1 deletion src/Routers/UsersRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Comment on lines +407 to +410
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Consider validation implications of username fallback to email.

When only an email is provided (line 408), the username is set to the email address. This could cause issues:

  • Email format may not meet username validation requirements (e.g., special characters, length limits)
  • Could conflict with existing usernames if someone's username happens to match another user's email
  • May be unexpected behavior for users

Verify that this approach is validated correctly:

#!/bin/bash
# Check username validation rules that might conflict with email format
rg -n -C3 'username.*validation|validateUsername' --type=js

Consider requiring an explicit username for auto-signup, or document this behavior clearly in the option description.

🤖 Prompt for AI Agents
In src/Routers/UsersRouter.js around lines 407 to 410, the code falls back to
using the raw email as the username which can violate username validation rules
and create uniqueness/conflict issues; update the signup flow so that when
username is derived from email you (a) run the same username validation routine
(validateUsername/username validation rules) against the email-derived username
and reject the request with a clear error if it fails, or (b) instead require an
explicit username for auto-signup (document this option), or (c) if you prefer
auto-generation, create a sanitized/normalized username from the email (strip
invalid chars, enforce length) then check DB uniqueness and resolve collisions
(append numeric suffix) before saving; implement one of these fixes and ensure
the error path returns a descriptive message and the DB uniqueness check is
performed prior to persisting.

};
}

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
Expand Down
1 change: 1 addition & 0 deletions types/Options/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export interface ParseServerOptions {
verifyUserEmails?: (boolean | void);
preventLoginWithUnverifiedEmail?: boolean;
preventSignupWithUnverifiedEmail?: boolean;
autoSignupOnLogin?: boolean;
emailVerifyTokenValidityDuration?: number;
emailVerifyTokenReuseIfValid?: boolean;
sendUserEmailVerification?: (boolean | void);
Expand Down