Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
135 changes: 128 additions & 7 deletions src/Routers/UsersRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,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,
Expand Down Expand Up @@ -254,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.'
);
}
}
}

Expand Down Expand Up @@ -285,7 +330,6 @@ export class UsersRouter extends ClassesRouter {
{}
);
}

const { sessionData, createSession } = RestWrite.createSession(req.config, {
userId: user.objectId,
createdWith: {
Expand Down Expand Up @@ -317,6 +361,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
Expand Down Expand Up @@ -620,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,
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