Accounts (multi-server)
The accounts-base
package exports two constructors, called AccountsClient
and AccountsServer
, which are used to create the Accounts
object that is available on the client and the server, respectively.
This predefined Accounts
object (along with similar convenience methods of Meteor
, such as Meteor.logout
) is sufficient to implement most accounts-related logic in Meteor apps. Nevertheless, these two constructors can be instantiated more than once, to create multiple independent connections between different accounts servers and their clients, in more complicated authentication situations.
Anywhere new AccountsCommon(options)
import { AccountsCommon } from 'meteor/accounts-base'
(accounts-base/accounts_common.js, line 1)
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 common superclass, AccountsCommon
. Methods defined on AccountsCommon.prototype
will be available on both the client and the server, via the predefined Accounts
object (most common) or any custom accountsClientOrServer
object created using the AccountsClient
or AccountsServer
constructors (less common).
Here are a few of those methods:
Anywhere but publish functions AccountsCommon#userId()
Get the current user id, or null
if no user is logged in. A reactive data source.
Anywhere but publish functions AccountsCommon#user()
Get the current user record, or null
if no user is logged in. A reactive data source.
Anywhere AccountsCommon#config(options)
Set global accounts options.
Options
-
sendVerificationEmail
Boolean -
New users with an email address will receive an address verification email.
-
forbidClientAccountCreation
Boolean -
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. -
restrictCreationByEmailDomain
String 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' })
. -
loginExpirationInDays
Number -
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. -
oauthSecretKey
String -
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.
Anywhere AccountsCommon#onLogin(func)
Register a callback to be called after a login attempt succeeds.
Arguments
-
func
Function -
The callback to be called when login is successful.
See description of AccountsCommon#onLoginFailure for details.
Anywhere AccountsCommon#onLoginFailure(func)
Register a callback to be called after a login attempt fails.
Arguments
-
func
Function -
The callback to be called after the login has failed.
Either the onLogin
or the onLoginFailure
callbacks will be called for each login attempt. The onLogin
callbacks are called after the user has been successfully logged in. The onLoginFailure
callbacks are called after a login attempt is denied.
These functions return an object with a single method, stop
. Calling stop()
unregisters the callback.
On the server, the callbacks get a single argument, the same attempt info object as validateLoginAttempt
. On the client, no arguments are passed.
Anywhere AccountsCommon#onLogout(func)
Register a callback to be called after a logout attempt succeeds.
Arguments
-
func
Function -
The callback to be called when logout is successful.
Client new AccountsClient(options)
import { AccountsClient } from 'meteor/accounts-base'
(accounts-base/accounts_client.js, line 3)
import { AccountsClient } from 'meteor/accounts-base'
(accounts-base/accounts_client.js, line 3) Constructor for the Accounts
object on the client.
Options
-
connection
Object -
Optional DDP connection to reuse.
-
ddpUrl
String -
Optional URL for creating a new DDP connection.
At most one of options.connection
and options.ddpUrl
should be provided in any instantiation of AccountsClient
. If neither is provided, Meteor.connection
will be used as the .connection
property of the AccountsClient
instance.
Note that AccountsClient
is currently available only on the client, due to its use of browser APIs such as window.localStorage
. In principle, though, it might make sense to establish a client connection from one server to another remote accounts server. Please let us know if you find yourself needing this server-to-server functionality.
These methods are defined on AccountsClient.prototype
, and are thus available only on the client:
Client AccountsClient#loggingIn()
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])
Log the user out.
Arguments
-
callback
Function -
Optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
Client AccountsClient#logoutOtherClients([callback])
Log out other clients logged in as the current user, but does not log out the client that calls this function.
Arguments
-
callback
Function -
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 5)
import { AccountsServer } from 'meteor/accounts-base'
(accounts-base/accounts_server.js, line 5) Constructor for the Accounts
namespace on the server.
Arguments
-
server
Object -
A server object such as
Meteor.server
.
These methods are defined on AccountsServer.prototype
, and are thus available only on the server:
Server AccountsServer#validateNewUser(func)
Set restrictions on new user creation.
Arguments
-
func
Function -
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
or throw an error, the new user creation is aborted. To set a specific error message (which will be displayed by accounts-ui
), throw a new Meteor.Error
.
Example:
// Validate username, sending a specific error message on failure. Accounts.validateNewUser(function (user) { if (user.username && user.username.length >= 3) return true; throw new Meteor.Error(403, "Username must have at least 3 characters"); }); // Validate username, without a specific error message. Accounts.validateNewUser(function (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, or logging in for the first time with an external service), these callbacks are called before the Accounts.validateLoginAttempt
callbacks. If these callbacks succeed but those fail, the user will still be created but the connection will not be logged in as that user.
Server AccountsServer#onCreateUser(func)
Customize new user creation.
Arguments
-
func
Function -
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 user creation. With this function you can programatically control the contents of new user documents.
The function you pass will be called with two arguments: options
and user
. The options
argument comes from Accounts.createUser
for password-based users or from an external service login flow. options
may come from an untrusted client so make sure to validate any values you read from it. The user
argument is created on the server and contains a proposed user object with all the automatically generated fields required for the user to log in, including the _id
.
The function should return the user document (either the one passed in or a newly-created object) with whatever modifications are desired. The returned document is inserted directly into the Meteor.users
collection.
The default create user function simply copies options.profile
into the new user document. Calling onCreateUser
overrides the default hook. This can only be called once.
Example:
// Support for playing D&D: Roll 3d6 for dexterity Accounts.onCreateUser(function(options, user) { var d6 = function () { return Math.floor(Random.fraction() * 6) + 1; }; user.dexterity = d6() + d6() + d6(); // We still want the default hook's 'profile' behavior. if (options.profile) user.profile = options.profile; return user; });
Server AccountsServer#validateLoginAttempt(func)
Validate login attempts.
Arguments
-
func
Function -
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 login attempts. It returns an object with a single method, stop
. Calling stop()
unregisters the callback.
When a login attempt is made, the registered validate login callbacks are 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 aborted by any of the validateLoginAttempt callbacks). False if the login will not succeed (for example, an invalid password or the login was aborted by a previous validateLoginAttempt callback).
- errorException
-
When
allowed
is false, the exception describing why the login failed. It will be aMeteor.Error
for failures reported to the user (such as invalid password), and can be a another kind of exception 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 to proceed. If the callback returns a falsy value or throws an exception, the login is aborted. Throwing a Meteor.Error
will report the error reason to the user.
All registered validate login callbacks are called, even if one of the callbacks aborts the login. The later callbacks will see the allowed
field set to false
since the login will now not be successful. This allows later callbacks to override an error from a previous callback; for example, you could override the “Incorrect password” error with a different message.
Validate login callbacks that aren’t explicitly trying to override a previous error generally have no need to run if the attempt has already been determined to 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 a limit of 5 requests per 10 seconds per session. These are a basic solution to dictionary attacks where a malicious user attempts to guess the passwords of legitimate users by attempting all possible passwords.
These rate limiting rules can be removed by calling Accounts.removeDefaultRateLimit()
. Please see the DDPRateLimiter
docs for more information.
© 2011–2017 Meteor Development Group, Inc.
Licensed under the MIT License.
https://docs.meteor.com/v1.3.5/api/accounts-multi.html