- Accounts (multi-server)
- new AccountsServer(server)
- AccountsServer#validateNewUser(func)
- AccountsServer#onCreateUser(func)
- AccountsServer#validateLoginAttempt(func)
- Rate Limiting
Accounts (multi-server)
Documentation of how to use the Accounts client to connect to other servers.
The accounts-base
package exports two constructors, calledAccountsClient
and AccountsServer
, which are used to create theAccounts
object that is available on the client and the server,respectively.
This predefined Accounts
object (along with similar convenience methodsof Meteor
, such as Meteor.logout
) is sufficient toimplement most accounts-related logic in Meteor apps. Nevertheless, thesetwo constructors can be instantiated more than once, to create multipleindependent connections between different accounts servers and theirclients, in more complicated authentication situations.
Anywhere
new AccountsCommon(options)
import { AccountsCommon } from 'meteor/accounts-base' (accounts-base/accounts_common.js, line 1)
Super-constructor for AccountsClient and AccountsServer.
The AccountsClient
and AccountsServer
classes share a commonsuperclass, AccountsCommon
. Methods defined onAccountsCommon.prototype
will be available on both the client and theserver, via the predefined Accounts
object (most common) or any customaccountsClientOrServer
object created using the AccountsClient
orAccountsServer
constructors (less common).
Here are a few of those methods:
Anywhere
AccountsCommon#userId()
(accounts-base/accounts_common.js, line 76)
Get the current user id, or null
if no user is logged in. A reactive data source.
Anywhere
AccountsCommon#user()
(accounts-base/accounts_common.js, line 84)
Get the current user record, or null
if no user is logged in. A reactive data source.
Anywhere
AccountsCommon#config(options)
(accounts-base/accounts_common.js, line 136)
Set global accounts options.
Options
- sendVerificationEmailBoolean
New users with an email address will receive an address verification email.
forbidClientAccountCreationBoolean
Calls to
createUser
from the client will be rejected. In addition, if you are using accounts-ui, the "Create account" link will not be available.restrictCreationByEmailDomainString or Function
If set to a string, only allows new users if the domain part of their email address matches the string. If set to a function, only allows new users if the function returns true. The function is passed the full email address of the proposed new user. Works with password-based sign-in and external services that expose email addresses (Google, Facebook, GitHub). All existing users still can log in after enabling this option. Example:
Accounts.config({ restrictCreationByEmailDomain: 'school.edu' })
.loginExpirationInDaysNumber
The number of days from when a user logs in until their token expires and they are logged out. Defaults to 90. Set to
null
to disable login expiration.oauthSecretKeyString
When using the
oauth-encryption
package, the 16 byte key using to encrypt sensitive account credentials in the database, encoded in base64. This option may only be specifed on the server. See packages/oauth-encryption/README.md for details.passwordResetTokenExpirationInDaysNumber
The number of days from when a link to reset password is sent until token expires and user can't reset password with the link anymore. Defaults to 3.
passwordEnrollTokenExpirationInDaysNumber
The number of days from when a link to set inital password is sent until token expires and user can't set password with the link anymore. Defaults to 30.
ambiguousErrorMessagesBoolean
- Return ambiguous error messages from login failures to prevent user enumeration. Defaults to false.
Anywhere
AccountsCommon#onLogin(func)
(accounts-base/accounts_common.js, line 198)
Register a callback to be called after a login attempt succeeds.
Arguments
- funcFunction
- The callback to be called when login is successful. The callback receives a single object that holds login details. This object contains the login result type (password, resume, etc.) on both the client and server.
onLogin
callbacks registered on the server also receive extra data, such as user details, connection information, etc.
See description of AccountsCommon#onLoginFailurefor details.
Anywhere
AccountsCommon#onLoginFailure(func)
(accounts-base/accounts_common.js, line 210)
Register a callback to be called after a login attempt fails.
Arguments
- funcFunction
- The callback to be called after the login has failed.
Either the onLogin
or the onLoginFailure
callbacks will be calledfor each login attempt. The onLogin
callbacks are called after theuser has been successfully logged in. The onLoginFailure
callbacks arecalled after a login attempt is denied.
These functions return an object with a single method, stop
. Callingstop()
unregisters the callback.
On the server, the callbacks get a single argument, the same attempt infoobject as validateLoginAttempt
. On theclient, the callback argument is an object containing a single error
property set to the Error
-object which was received from the failed login attempt.
Anywhere
AccountsCommon#onLogout(func)
(accounts-base/accounts_common.js, line 219)
Register a callback to be called after a logout attempt succeeds.
Arguments
- funcFunction
- The callback to be called when logout is successful.
On the server, the func
callback receives a single argument with the object below. On theclient, no arguments are passed.
- userObject
The Meteor user object of the user which just logged out.
connectionObject
- The
connection
object the request came in on. SeeMeteor.onConnection
for details.
Client
new AccountsClient(options)
import { AccountsClient } from 'meteor/accounts-base' (accounts-base/accounts_client.js, line 3)
Constructor for the Accounts
object on the client.
Options
- connectionObject
Optional DDP connection to reuse.
ddpUrlString
- Optional URL for creating a new DDP connection.
At most one of options.connection
and options.ddpUrl
should beprovided in any instantiation of AccountsClient
. If neither is provided,Meteor.connection
will be used as the .connection
property of theAccountsClient
instance.
Note that AccountsClient
is currently available only on the client, dueto its use of browser APIs such as window.localStorage
. In principle,though, it might make sense to establish a client connection from oneserver to another remote accounts server. Please let usknowif you find yourself needing this server-to-server functionality.
These methods are defined on AccountsClient.prototype
, and are thusavailable only on the client:
Client
AccountsClient#loggingIn()
(accounts-base/accounts_client.js, line 56)
True if a login method (such as Meteor.loginWithPassword
, Meteor.loginWithFacebook
, or Accounts.createUser
) is currently in progress. A reactive data source.
Client
AccountsClient#logout([callback])
(accounts-base/accounts_client.js, line 116)
Log the user out.
Arguments
- callbackFunction
- Optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
Client
AccountsClient#logoutOtherClients([callback])
(accounts-base/accounts_client.js, line 136)
Log out other clients logged in as the current user, but does not log out the client that calls this function.
Arguments
- callbackFunction
- Optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
Server
new AccountsServer(server)
import { AccountsServer } from 'meteor/accounts-base' (accounts-base/accounts_server.js, line 10)
Constructor for the Accounts
namespace on the server.
Arguments
- serverObject
- A server object such as
Meteor.server
.
These methods are defined on AccountsServer.prototype
, and are thusavailable only on the server:
Server
AccountsServer#validateNewUser(func)
(accounts-base/accounts_server.js, line 116)
Set restrictions on new user creation.
Arguments
- funcFunction
- Called whenever a new user is created. Takes the new user object, and returns true to allow the creation or false to abort.
This can be called multiple times. If any of the functions return false
orthrow an error, the new user creation is aborted. To set a specific errormessage (which will be displayed by accounts-ui
), throw a newMeteor.Error
.
Example:
// Validate username, sending a specific error message on failure.
Accounts.validateNewUser((user) => {
if (user.username && user.username.length >= 3) {
return true;
} else {
throw new Meteor.Error(403, 'Username must have at least 3 characters');
}
});
// Validate username, without a specific error message.
Accounts.validateNewUser((user) => {
return user.username !== 'root';
});
If the user is being created as part of a login attempt from a client (eg,calling Accounts.createUser
from the client, orlogging in for the first time with an externalservice), these callbacks are called _before_the Accounts.validateLoginAttempt
callbacks. If these callbacks succeed but those fail, the user will still becreated but the connection will not be logged in as that user.
Server
AccountsServer#onCreateUser(func)
(accounts-base/accounts_server.js, line 129)
Customize new user creation.
Arguments
- funcFunction
- Called whenever a new user is created. Return the new user object, or throw an
Error
to abort the creation.
Use this when you need to do more than simply accept or reject new usercreation. With this function you can programatically control thecontents of new user documents.
The function you pass will be called with two arguments: options
anduser
. The options
argument comesfrom Accounts.createUser
forpassword-based users or from an external service login flow. options
may comefrom an untrusted client so make sure to validate any values you read fromit. The user
argument is created on the server and contains aproposed user object with all the automatically generated fieldsrequired for the user to log in, including the _id
.
The function should return the user document (either the one passed in or anewly-created object) with whatever modifications are desired. The returneddocument is inserted directly into the Meteor.users
collection.
The default create user function simply copies options.profile
intothe new user document. Calling onCreateUser
overrides the defaulthook. This can only be called once.
Example:
// Support for playing D&D: Roll 3d6 for dexterity.
Accounts.onCreateUser((options, user) => {
const customizedUser = Object.assign({
dexterity: _.random(1, 6) + _.random(1, 6) + _.random(1, 6),
}, user);
// We still want the default hook's 'profile' behavior.
if (options.profile) {
customizedUser.profile = options.profile;
}
return customizedUser;
});
Server
AccountsServer#validateLoginAttempt(func)
(accounts-base/accounts_server.js, line 106)
Validate login attempts.
Arguments
- funcFunction
- Called whenever a login is attempted (either successful or unsuccessful). A login can be aborted by returning a falsy value or throwing an exception.
Call validateLoginAttempt
with a callback to be called on loginattempts. It returns an object with a single method, stop
. Callingstop()
unregisters the callback.
When a login attempt is made, the registered validate login callbacksare called with a single argument, the attempt info object:
- typeString
The service name, such as “password” or “twitter”.
allowedBoolean
Whether this login is allowed and will be successful (if not abortedby any of the validateLoginAttempt callbacks). False if the loginwill not succeed (for example, an invalid password or the login wasaborted by a previous validateLoginAttempt callback).
errorException
When
allowed
is false, the exception describing why the loginfailed. It will be aMeteor.Error
for failures reported to theuser (such as invalid password), and can be a another kind ofexception for internal errors.userObject
When it is known which user was attempting to login, the Meteor user object.This will always be present for successful logins.
connectionObject
The
connection
object the request came in on. SeeMeteor.onConnection
for details.methodNameString
The name of the Meteor method being used to login.
methodArgumentsArray
- An array of the arguments passed to the login method.
A validate login callback must return a truthy value for the login toproceed. If the callback returns a falsy value or throws anexception, the login is aborted. Throwing a Meteor.Error
willreport the error reason to the user.
All registered validate login callbacks are called, even if one of the callbacksaborts the login. The later callbacks will see the allowed
field set tofalse
since the login will now not be successful. This allows later callbacksto override an error from a previous callback; for example, you could overridethe “Incorrect password” error with a different message.
Validate login callbacks that aren’t explicitly trying to override a previouserror generally have no need to run if the attempt has already been determinedto fail, and should start with
if (!attempt.allowed) {
return false;
}
Rate Limiting
By default, there are rules added to the DDPRateLimiter
that rate limit logins, new user registration and password reset calls to alimit of 5 requests per 10 seconds per session. These are a basic solutionto dictionary attacks where a malicious user attempts to guess the passwordsof legitimate users by attempting all possible passwords.
These rate limiting rules can be removed by callingAccounts.removeDefaultRateLimit()
. Please see theDDPRateLimiter
docs for more information.