Appearance
账户
¥Accounts
账户基础
¥Accounts-base
Meteor 账户系统建立在 publish
和 methods
中的 userId
支持之上。核心包添加了存储在数据库中的用户文档的概念,附加包添加了 安全密码验证、与第三方登录服务的集成 和 预构建的用户界面。
¥The Meteor Accounts system builds on top of the userId
support in publish
and methods
. The core packages add the concept of user documents stored in the database, and additional packages add secure password authentication, integration with third party login services, and a pre-built userinterface.
基本账户系统位于 accounts-base
包中,但应用通常通过添加其中一个登录提供程序包自动包含它:accounts-password
、accounts-facebook
、accounts-github
、accounts-google
、accounts-meetup
、accounts-twitter
或 accounts-weibo
。
¥The basic Accounts system is in the accounts-base
package, but applications typically include this automatically by adding one of the login provider packages: accounts-password
, accounts-facebook
, accounts-github
, accounts-google
, accounts-meetup
, accounts-twitter
, or accounts-weibo
.
在 Meteor 指南中的 账户 文章中阅读有关自定义用户账户的更多信息。
¥Read more about customizing user accounts in the Accounts article in the Meteor Guide.
具有会话存储的账户
¥Accounts with Session Storage
默认情况下,Meteor 使用本地存储来存储浏览器会话中的登录令牌等。但对于某些应用,使用会话存储是有意义的。你可以通过将其添加到你的设置来实现此目的:
¥By default, Meteor uses Local Storage to store, among other things, login tokens in your browser session. But, for some applications, it makes sense to use Session Storage instead. You can achieve this by adding this to your settings:
json
{
// ... all other settings,
"public": {
// ... all your public settings
"packages": {
"accounts": {
"clientStorage": "session"
}
}
}
}
Meteor.user
Summary:
Get the current user record, or null
if no user is logged in. A reactive data source.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | No |
从 Meteor.users
集合中检索当前用户的用户记录。
¥Retrieves the user record for the current user from the Meteor.users
collection.
在客户端上,可用字段将是从服务器发布的字段(其他字段在客户端上不可用)。默认情况下,服务器发布 username
、emails
和 profile
(用户可写)。有关用户文档中使用的字段的更多信息,请参阅 Meteor.users
。
¥On the client, the available fields will be those that are published from the server (other fields won't be available on the client). By default the server publishes username
, emails
, and profile
(writable by user). See Meteor.users
for more on the fields used in user documents.
在服务器上,这将从数据库中获取记录。要改善多次使用用户文档的方法的延迟,请将返回的记录保存到变量中,而不是重新调用 Meteor.user()
。
¥On the server, this will fetch the record from the database. To improve the latency of a method that uses the user document multiple times, save the returned record to a variable instead of re-calling Meteor.user()
.
获取完整的用户文档可能会导致服务器上不必要的数据库使用和客户端的过度反应,特别是如果你在其上存储了大量自定义数据。因此,建议使用 options
参数仅获取你需要的字段:
¥Fetching the full user document can cause unnecessary database usage on the server and over-reactivity on the client, particularly if you store lots of custom data on it. Therefore it is recommended to use the options
parameter to only fetch the fields you need:
js
import { Meteor } from "meteor/meteor";
const userName = Meteor.user({ fields: { "profile.name": 1 } }).profile.name;
Meteor.userAsync
Summary:
Get the current user record, or null
if no user is logged in. A reactive data source.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | No |
与 Meteor.user
相同,但返回 promise 并在服务器上可用。
¥Same as Meteor.user
, but returns a promise and is available on the server.
js
import { Meteor } from "meteor/meteor";
const user = await Meteor.userAsync();
Meteor.userId
Summary:
Get the current user id, or null
if no user is logged in. A reactive data source.
js
import { Meteor } from "meteor/meteor";
Meteor.userId();
此集合包含每个注册用户的一个文档。下面是示例用户文档:
¥This collection contains one document per registered user. Here's an example user document:
js
{
_id: 'QwkSmTCZiw5KDx3L6', // Meteor.userId()
username: 'cool_kid_13', // Unique name
emails: [
// Each email address can only belong to one user.
{ address: 'cool@example.com', verified: true },
{ address: 'another@different.com', verified: false }
],
createdAt: new Date('Wed Aug 21 2013 15:16:52 GMT-0700 (PDT)'),
profile: {
// The profile is writable by the user by default.
name: 'Joe Schmoe'
},
services: {
facebook: {
id: '709050', // Facebook ID
accessToken: 'AAACCgdX7G2...AbV9AZDZD'
},
resume: {
loginTokens: [
{ token: '97e8c205-c7e4-47c9-9bea-8e2ccc0694cd',
when: 1349761684048 }
]
}
}
}
用户文档可以包含你想要存储的有关用户的任何数据。Meteor 特殊处理以下字段:
¥A user document can contain any data you want to store about a user. Meteor treats the following fields specially:
username
:用于标识用户的唯一字符串。¥
username
: a unique String identifying the user.emails
:带有键address
和verified
的对象数组;一个电子邮件地址最多只能属于一个用户。verified
是一个布尔值,如果用户拥有通过电子邮件发送的带有令牌的 已验证的地址,则为真。¥
emails
: an Array of Objects with keysaddress
andverified
; an email address may belong to at most one user.verified
is a Boolean which is true if the user has verified the address with a token sent over email.createdAt
:创建用户文档的日期。¥
createdAt
: the Date at which the user document was created.profile
:用户可以使用任何数据创建和更新的对象。除非你对Meteor.users
集合有拒绝规则,否则不要在profile
上存储任何你不希望用户编辑的内容。¥
profile
: an Object which the user can create and update with any data. Do not store anything onprofile
that you wouldn't want the user to edit unless you have a deny rule on theMeteor.users
collection.services
:包含特定登录服务使用的数据的对象。例如,其reset
字段包含 忘记密码 链接使用的令牌,其resume
字段包含用于让你在会话之间保持登录状态的令牌。¥
services
: an Object containing data used by particular login services. For example, itsreset
field contains tokens used by forgot password links, and itsresume
field contains tokens used to keep you logged in between sessions.
与所有 Mongo.Collection 一样,你可以访问服务器上的所有文档,但只有服务器专门发布的文档才可在客户端上使用。你还可以使用所有 Collection 方法,例如服务器上的 Meteor.users.remove
来删除用户。
¥Like all Mongo.Collections, you can access all documents on the server, but only those specifically published by the server are available on the client. You can also use all Collection methods, for instance Meteor.users.remove
on the server to delete a user.
默认情况下,当前用户的 username
、emails
和 profile
将发布到客户端。你可以使用以下命令为当前用户发布其他字段:
¥By default, the current user's username
, emails
and profile
are published to the client. You can publish additional fields for the current user with:
js
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find(
{ _id: this.userId },
{
fields: { other: 1, things: 1 },
}
);
} else {
this.ready();
}
});
js
Meteor.subscribe("userData");
如果安装了 autopublish 包,则系统上所有用户的信息都将发布给所有客户端。这包括 username
、profile
和 services
中任何应该公开的字段(例如 services.facebook.id
、services.twitter.screenName
)。此外,使用自动发布时,会为当前登录的用户发布更多信息,包括访问令牌。这允许直接从客户端对允许这样做的服务进行 API 调用。
¥If the autopublish package is installed, information about all users on the system is published to all clients. This includes username
, profile
, and any fields in services
that are meant to be public (eg services.facebook.id
, services.twitter.screenName
). Additionally, when using autopublish more information is published for the currently logged in user, including access tokens. This allows making API calls directly from the client for services that allow this.
默认情况下,用户可以使用 Accounts.createUser
指定自己的 profile
字段,并使用 Meteor.users.update
对其进行修改。要允许用户编辑其他字段,请使用 Meteor.users.allow
。要禁止用户对其用户文档进行任何修改:
¥Users are by default allowed to specify their own profile
field with Accounts.createUser
and modify it with Meteor.users.update
. To allow users to edit additional fields, use Meteor.users.allow
. To forbid users from making any modifications to their user document:
js
import { Meteor } from "meteor/meteor";
Meteor.users.deny({ update: () => true });
Meteor.loggingIn Client only
Client only
Summary:
True if a login method (such as Meteor.loginWithPassword
,
Meteor.loginWithFacebook
, or Accounts.createUser
) is currently in
progress. A reactive data source.
js
import { Meteor } from "meteor/meteor";
Meteor.loggingIn();
例如,accounts-ui
包 使用它在处理登录请求时显示动画。
¥For example, the accounts-ui
package uses this to display an animation while the login request is being processed.
Meteor.loggingOut Client only
Client only
Summary:
True if a logout method (such as Meteor.logout
) is currently in
progress. A reactive data source.
js
import { Meteor } from "meteor/meteor";
Meteor.loggingOut();
Meteor.logout Client only
Client only
Summary:
Log the user out.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
import { Meteor } from "meteor/meteor";
Meteor.logout(
() => {}
);
Meteor.logoutOtherClients Client only
Client only
Summary:
Log out other clients logged in as the current user, but does not log out the client that calls this function.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
import { Meteor } from "meteor/meteor";
Meteor.logoutOtherClients(
() => {}
);
例如,在用户的浏览器中调用时,该浏览器中的连接保持登录状态,但以该用户身份登录的任何其他浏览器或 DDP 客户端都将被注销。
¥For example, when called in a user's browser, connections in that browser remain logged in, but any other browsers or DDP clients logged in as that user will be logged out.
Meteor.loginWithPassword Client only
Client only
Summary:
Log the user in with a password.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
selector | Object or String | Either a string interpreted as a username or an email; or an object with a
single key: | Yes |
password | String | The user's password. | Yes |
callback | function | Optional callback.
Called with no arguments on success, or with a single | No |
js
import { Meteor } from "meteor/meteor";
Meteor.loginWithPassword(
selector,
"password",
() => {}, // this param is optional
);
如果有多个用户的用户名或电子邮件仅在大小写上不同,则需要区分大小写匹配。虽然 createUser
不允许你创建具有模糊用户名或电子邮件的用户,但这可能会发生在现有数据库中或你直接修改用户集合时。
¥If there are multiple users with a username or email only differing in case, a case sensitive match is required. Although createUser
won't let you create users with ambiguous usernames or emails, this could happen with existing databases or if you modify the users collection directly.
此方法可能会失败并引发以下错误之一:
¥This method can fail throwing one of the following errors:
如果
user
或password
未定义,则为 "无法识别的登录请求选项 [400]"。¥"Unrecognized options for login request [400]" if
user
orpassword
is undefined.如果
user
不是对象或字符串,或者password
不是字符串,则为 "匹配失败 [400]"。¥"Match failed [400]" if
user
isn't an Object or String, orpassword
isn't a String.如果
user
中提供的电子邮件或用户名不属于注册用户,则为 "未找到用户 [403]"。¥"User not found [403]" if the email or username provided in
user
doesn't belong to a registered user.如果提供的密码不正确,则为 "密码不正确 [403]"。
¥"Incorrect password [403]" if the password provided is incorrect.
如果
user
没有密码,则为 "用户未设置密码 [403]"。¥"User has no password set [403]" if
user
doesn't have a password.
此功能由 accounts-password
包提供。请参阅下面的 密码 部分。
¥This function is provided by the accounts-password
package. See the Passwords section below.
Meteor.loginWith<ExternalService> Client only
Client only
Summary:
Log the user in using an external service.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | No | |
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
import { Meteor } from "meteor/meteor";
Meteor.loginWith<ExternalService>(
options, // this param is optional
() => {}, // this param is optional
);
可用功能包括:
¥Available functions are:
Meteor.loginWithMeteorDeveloperAccount
Meteor.loginWithFacebook
options
也可能包括 Facebook 的auth_type
参数¥
options
may also include Facebook'sauth_type
parameter
Meteor.loginWithGithub
Meteor.loginWithGoogle
options
也可能包括 Google 的附加 URI 参数¥
options
may also include Google's additional URI parameters
Meteor.loginWithMeetup
Meteor.loginWithTwitter
options
也可能包括 Twitter 的force_login
参数¥
options
may also include Twitter'sforce_login
parameter
Meteor.loginWithWeibo
这些函数使用 OAuth 启动外部服务(例如 Facebook、Google 等)的登录过程。当被调用时,它们会打开一个新的弹出窗口,加载提供商的登录页面。用户使用提供商登录后,弹出窗口关闭,Meteor 客户端使用外部服务提供的信息登录 Meteor 服务器。
¥These functions initiate the login process with an external service (eg: Facebook, Google, etc), using OAuth. When called they open a new pop-up window that loads the provider's login page. Once the user has logged in with the provider, the pop-up window is closed and the Meteor client logs in to the Meteor server with the information provided by the external service.
请求权限
除了向你的应用识别用户之外,某些服务还具有允许你代表用户采取行动的 API。要向用户请求特定权限,请将 requestPermissions
选项传递给登录函数。这将导致在弹出对话框中向用户显示一个附加页面,以允许访问他们的数据。用户的 accessToken
— 具有访问服务 API 的权限 — 存储在用户文档的 services
字段中。每个登录服务对 requestPermissions
的支持值不同,并在各自的开发者网站上有记录:
¥In addition to identifying the user to your application, some services have APIs that allow you to take action on behalf of the user. To request specific permissions from the user, pass the requestPermissions
option the login function. This will cause the user to be presented with an additional page in the pop-up dialog to permit access to their data. The user's accessToken
— with permissions to access the service's API — is stored in the services
field of the user document. The supported values for requestPermissions
differ for each login service and are documented on their respective developer sites:
Facebook:http://developers.facebook.com/docs/authentication/permissions
Google:https://developers.google.com/identity/protocols/googlescopes
聚会:http://www.meetup.com/meetup_api/auth/#oauth2-scopes
¥Meetup: http://www.meetup.com/meetup_api/auth/#oauth2-scopes
Twitter、微博、Meteor 开发者账号:
requestPermissions
目前不支持¥Twitter, Weibo, Meteor developer accounts:
requestPermissions
currently not supported
外部登录服务通常需要在使用前注册和配置你的应用。最简单的方法是使用 accounts-ui
包,它提供了配置每个服务的分步指南。但是,也可以手动将数据输入到 ServiceConfiguration.configurations
集合中,该集合由 service-configuration
包导出。
¥External login services typically require registering and configuring your application before use. The easiest way to do this is with the accounts-ui
package which presents a step-by-step guide to configuring each service. However, the data can be also be entered manually in the ServiceConfiguration.configurations
collection, which is exported by the service-configuration
package.
配置服务
¥Configuring Services
首先,添加服务配置包:
¥First, add the service configuration package:
bash
meteor add service-configuration
然后,在你的应用的服务器内(此示例适用于 Weebo 服务),导入 ServiceConfiguration
:
¥Then, inside the server of your app (this example is for the Weebo service), import ServiceConfiguration
:
js
import { ServiceConfiguration } from "meteor/service-configuration";
ServiceConfiguration.configurations.upsert(
{ service: "weibo" },
{
$set: {
loginStyle: "popup",
clientId: "1292962797", // See table below for correct property name!
secret: "75a730b58f5691de5522789070c319bc",
},
}
);
从 Meteor 2.7 开始,你不再需要手动设置配置,而是可以通过在 Meteor.settings.packages.service-configuration.<service>
下设置服务来使用 Meteor 设置。所有属性都可以在服务下设置,并将按原样添加到数据库中,因此请确保它们正确无误。对于上述示例,设置如下所示:
¥Since Meteor 2.7 you no longer need to manually set the configuration and instead can use Meteor settings by setting your services under Meteor.settings.packages.service-configuration.<service>
. All the properties can be set under the service and will be added to the database as is, so make sure that they are correct. For the example above, the settings would look like:
json
{
"packages": {
"service-configuration": {
"weibo": {
"loginStyle": "popup",
"clientId": "1292962797",
"secret": "75a730b58f5691de5522789070c319bc"
}
}
}
}
用于 API 标识符的正确属性名称(即上例中的 clientId
)取决于所使用的登录服务,因此请确保使用正确的名称:
¥The correct property name to use for the API identifier (i.e. clientId
in the above example) depends on the login service being used, so be sure to use the correct one:
属性名称 | 服务 |
---|---|
appId | |
clientId | Github、Google、Meetup、Meteor 开发者账户、微博 |
consumerKey |
此外,每个外部服务都有自己的登录提供程序包和登录功能。例如,要支持 GitHub 登录,请在终端中运行以下命令:
¥Additionally, each external service has its own login provider package and login function. For example, to support GitHub login, run the following in your terminal:
bash
meteor add accounts-github
并使用 Meteor.loginWithGithub
函数:
¥and use the Meteor.loginWithGithub
function:
js
import { Meteor } from "meteor/meteor";
Meteor.loginWithGithub(
{
requestPermissions: ["user", "public_repo"],
},
(error) => {
if (error) {
Session.set("errorMessage", error.reason || "Unknown error");
}
}
);
当你的应用启动时,登录服务配置通过 DDP 从服务器发送到客户端;在配置加载之前,你可能无法调用登录函数。函数 Accounts.loginServicesConfigured()
是一个反应性数据源,一旦配置了登录服务,它将返回 true;在它为真之前,你不应使登录按钮可见或处于活动状态。
¥Login service configuration is sent from the server to the client over DDP when your app starts up; you may not call the login function until the configuration is loaded. The function Accounts.loginServicesConfigured()
is a reactive data source that will return true once the login service is configured; you should not make login buttons visible or active until it is true.
确保你的 $ROOT_URL
与你使用外部服务配置的授权域和回调 URL 相匹配(例如,如果你在代理服务器后面运行 Meteor,则 $ROOT_URL
应该是外部可访问的 URL,而不是代理内的 URL)。
¥Ensure that your $ROOT_URL
matches the authorized domain and callback URL that you configure with the external service (for instance, if you are running Meteor behind a proxy server, $ROOT_URL
should be the externally-accessible URL, not the URL inside your proxy).
手动服务配置
¥Manual service configuration
你可以使用 Accounts.loginServiceConfiguration
查看和编辑设置集合:
¥You can use Accounts.loginServiceConfiguration
to view and edit the settings collection:
js
import { Accounts } from "meteor/accounts-base";
Accounts.loginServiceConfiguration.find();
弹出窗口与重定向流程
¥Popup versus redirect flow
当使用提供商(例如 Facebook 或 Google)配置 OAuth 登录时,Meteor 允许你选择基于弹出窗口或重定向的流程。在基于弹出窗口的流程中,当用户登录时,系统会在弹出窗口中提示他们登录提供商。在基于重定向的流程中,用户的整个浏览器窗口将被重定向到登录提供程序,登录完成后窗口将重定向回你的应用。
¥When configuring OAuth login with a provider (such as Facebook or Google), Meteor lets you choose a popup- or redirect-based flow. In a popup-based flow, when a user logs in, they will be prompted to login at the provider in a popup window. In a redirect-based flow, the user's whole browser window will be redirected to the login provider, and the window will redirect back to your app when the login is completed.
你还可以通过将选项传递给 Meteor.loginWith<ExternalService>
来选择要执行的登录类型
¥You can also pick which type of login to do by passing an option to Meteor.loginWith<ExternalService>
通常,基于弹出窗口的流程是首选,因为用户不必在登录流程结束时重新加载整个应用。但是,基于弹出窗口的流程需要浏览器功能(例如 window.close
和 window.opener
),而这些功能并非在所有移动环境中都可用。特别是,我们建议在以下环境中使用 Meteor.loginWith<ExternalService>({ loginStyle: 'redirect' })
:
¥Usually, the popup-based flow is preferable because the user will not have to reload your whole app at the end of the login flow. However, the popup-based flow requires browser features such as window.close
and window.opener
that are not available in all mobile environments. In particular, we recommend using Meteor.loginWith<ExternalService>({ loginStyle: 'redirect' })
in the following environments:
在 UIWebViews 内部(当你的应用加载到移动应用中时)
¥Inside UIWebViews (when your app is loaded inside a mobile app)
在 iOS8 上的 Safari 中(由于错误,不支持
window.close
)¥In Safari on iOS8 (
window.close
is not supported due to a bug)
{{ currentUser }}
Summary:
Calls Meteor.user(). Use {{#if currentUser}}
to check whether the user is logged in.
Accounts.ui.config Client only
Client only
Summary:
Configure the behavior of {{> loginButtons}}
.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | Yes |
示例:
¥Example:
js
import { Accounts } from "meteor/accounts-base";
Accounts.ui.config({
requestPermissions: {
facebook: ["user_likes"],
github: ["user", "repo"],
},
requestOfflineToken: {
google: true,
},
passwordSignupFields: "USERNAME_AND_OPTIONAL_EMAIL",
});
从 Meteor 2.7 开始,你可以在 Meteor.settings.public.packages.accounts-ui-unstyled
下的 Meteor 设置中配置这些。
¥Since Meteor 2.7 you can configure these in your Meteor settings under Meteor.settings.public.packages.accounts-ui-unstyled
.
多服务器
¥Multi-server
accounts-base
包导出两个构造函数,分别称为 AccountsClient
和 AccountsServer
,用于创建客户端和服务器上可用的 Accounts
对象。
¥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.
此预定义的 Accounts
对象(以及 Meteor
的类似便捷方法,例如 Meteor.logout
)足以在 Meteor 应用中实现大多数与账户相关的逻辑。尽管如此,在更复杂的身份验证情况下,这两个构造函数可以多次实例化,以在不同的账户服务器及其客户端之间创建多个独立连接。
¥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.
AccountsCommon
Summary:
Super-constructor for AccountsClient and AccountsServer.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | an object with fields:
| Yes |
js
import { AccountsCommon } from "meteor/accounts-base"";
const accountsCommon = new AccountsCommon(
options
);
AccountsClient
和 AccountsServer
类共享一个公共超类 AccountsCommon
。在 AccountsCommon.prototype
上定义的方法将在客户端和服务器上可用,通过预定义的 Accounts
对象(最常见)或使用 AccountsClient
或 AccountsServer
构造函数创建的任何自定义 accountsClientOrServer
对象(不太常见)。
¥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:
accountsCommon.userId
Summary:
Get the current user id, or null
if no user is logged in. A reactive data source.
js
// accountsCommon is an instance of AccountsCommon
accountsCommon.userId();
accountsCommon.user
Summary:
Get the current user record, or null
if no user is logged in. A reactive data source. In the server this fuction returns a promise.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | No |
js
// accountsCommon is an instance of AccountsCommon
accountsCommon.user(
options
);
accountsCommon.config
Summary:
Set global accounts options. You can also set these in Meteor.settings.packages.accounts
without the need to call this function.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | Yes |
js
// accountsCommon is an instance of AccountsCommon
accountsCommon.config(
options
);
从 Meteor 2.5 开始,你可以在 Meteor.settings.packages.accounts-base
下的 Meteor 设置中设置这些。请注意,由于设置文件的性质,你将无法设置需要函数的参数。
¥From Meteor 2.5 you can set these in your Meteor settings under Meteor.settings.packages.accounts-base
. Note that due to the nature of settings file you won't be able to set parameters that require functions.
accountsCommon.onLogin
Summary:
Register a callback to be called after a login attempt succeeds.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
func | function | 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. | Yes |
js
// accountsCommon is an instance of AccountsCommon
accountsCommon.onLogin(
() => {}
);
有关详细信息,请参阅 AccountsCommon#onLoginFailure 的描述。
¥See description of AccountsCommon#onLoginFailure for details.
accountsCommon.onLoginFailure
Summary:
Register a callback to be called after a login attempt fails.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
func | function | The callback to be called after the login has failed. | Yes |
js
// accountsCommon is an instance of AccountsCommon
accountsCommon.onLoginFailure(
() => {}
);
每次登录尝试都会调用 onLogin
或 onLoginFailure
回调。用户成功登录后,将调用 onLogin
回调。登录尝试被拒绝后,将调用 onLoginFailure
回调。
¥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.
这些函数返回一个具有单一方法 stop
的对象。调用 stop()
可取消注册回调。
¥These functions return an object with a single method, stop
. Calling stop()
unregisters the callback.
在服务器上,回调获得一个参数,即与 validateLoginAttempt
相同的尝试信息对象。在客户端上,回调参数是一个对象,其中包含一个设置为从失败的登录尝试中收到的 Error
对象的 error
属性。
¥On the server, the callbacks get a single argument, the same attempt info object as validateLoginAttempt
. On the client, the callback argument is an object containing a single error
property set to the Error
-object which was received from the failed login attempt.
accountsCommon.onLogout
Summary:
Register a callback to be called after a logout attempt succeeds.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
func | function | The callback to be called when logout is successful. | Yes |
在服务器上,func
回调接收一个带有以下对象的参数。在客户端上,没有传递任何参数。
¥On the server, the func
callback receives a single argument with the object below. On the client, no arguments are passed.
js
import { AccountsCommon } from "meteor/accounts-base";
const options = {
//...
};
const accountsCommon = new AccountsCommon(options);
accountsCommon.onLogout(({ user, connection, collection }) => {
console.log(user);
// ˆˆˆˆˆˆ The Meteor user object of the user which just logged out
console.log(connection);
// ˆˆˆˆˆˆ The connection object the request came in on. See
// `Meteor.onConnection` for details.
console.log(collection);
// ˆˆˆˆˆˆ The `collection` The name of the Mongo.Collection or the
// Mongo.Collection object to hold the users.
});
AccountsClient Client only
Client only
Summary:
Constructor for the Accounts
object on the client.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | an object with fields: | Yes |
js
import { AccountsClient } from "meteor/accounts-base"";
const accountsClient = new AccountsClient(
options
);
在 AccountsClient
的任何实例中,最多应提供 options.connection
和 options.ddpUrl
中的一个。如果两者都未提供,Meteor.connection
将用作 AccountsClient
实例的 .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.
请注意,由于使用浏览器 API(例如 window.localStorage
),AccountsClient
目前仅在客户端上可用。但原则上,建立从一台服务器到另一台远程账户服务器的客户端连接可能是有意义的。如果你发现自己需要此服务器到服务器功能,请使用 让我们知道。
¥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.
这些方法是在 AccountsClient.prototype
上定义的,因此仅在客户端上可用:
¥These methods are defined on AccountsClient.prototype
, and are thus available only on the client:
accountsClient.loggingIn Client only
Client only
Summary:
True if a login method (such as Meteor.loginWithPassword
, Meteor.loginWithFacebook
, or Accounts.createUser
) is currently in progress. A reactive data source.
js
// accountsClient is an instance of AccountsClient
accountsClient.loggingIn();
accountsClient.logout Client only
Client only
Summary:
Log the user out.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
// accountsClient is an instance of AccountsClient
accountsClient.logout(
() => {}
);
accountsClient.logoutOtherClients Client only
Client only
Summary:
Log out other clients logged in as the current user, but does not log out the client that calls this function.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
// accountsClient is an instance of AccountsClient
accountsClient.logoutOtherClients(
() => {}
);
AccountsServer Server only
Server only
Summary:
Constructor for the Accounts
namespace on the server.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
server | Object | A server object such as | Yes |
js
import { AccountsServer } from "meteor/accounts-base"";
const accountsServer = new AccountsServer(
server
);
这些方法是在 AccountsServer.prototype
上定义的,因此仅在服务器上可用:
¥These methods are defined on AccountsServer.prototype
, and are thus available only on the server:
accountsServer.validateNewUser Server only
Server only
Summary:
Set restrictions on new user creation.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
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. | Yes |
js
// accountsServer is an instance of AccountsServer
accountsServer.validateNewUser(
() => {}
);
这可以多次调用。如果任何函数返回 false
或抛出错误,则新用户创建将被中止。要设置特定的错误消息(将由 accounts-ui
显示),请抛出一个新的 Meteor.Error
。
¥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:
js
import { Accounts } from "meteor/accounts-base";
// 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";
});
如果用户是作为客户端登录尝试的一部分创建的(例如,从客户端调用 Accounts.createUser
或 首次使用外部服务登录),则在 Accounts.validateLoginAttempt
回调之前调用这些回调。如果这些回调成功但那些回调失败,则仍将创建用户,但连接将不会以该用户身份登录。
¥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.
accountsServer.onCreateUser Server only
Server only
Summary:
Customize new user creation.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
func | function | Called whenever a new user is created. Return the new user object, or throw an | Yes |
当你需要做的不仅仅是接受或拒绝新用户创建时,请使用它。使用此功能,你可以以编程方式控制新用户文档的内容。
¥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.
你传递的函数将使用两个参数调用:options
和 user
。options
参数来自基于密码的用户的 Accounts.createUser
或来自外部服务登录流程。options
可能来自不受信任的客户端,因此请确保验证从中读取的任何值。user
参数是在服务器上创建的,包含一个建议的用户对象,其中包含用户登录所需的所有自动生成的字段,包括 _id
。
¥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
.
该函数应返回用户文档(传入的文档或新创建的对象),并进行所需的任何修改。返回的文档直接插入到 Meteor.users
集合中。
¥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.
默认的创建用户函数只是将 options.profile
复制到新用户文档中。调用 onCreateUser
可覆盖默认钩子。这只能调用一次。
¥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:
js
import { Accounts } from "meteor/accounts-base";
// 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;
});
accountsServer.validateLoginAttempt Server only
Server only
Summary:
Validate login attempts.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
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. | Yes |
使用回调调用 validateLoginAttempt
以在登录尝试时调用。它返回一个具有单一方法 stop
的对象。调用 stop()
可取消注册回调。
¥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, you can check the example:
js
import { AccountsServer } from "meteor/accounts-base";
const options = {
//...
};
const accountsServer = new AccountsServer(options);
accountsServer.validateLoginAttempt(
({
type, // String
allowed, // Boolean
error, // Error
user, // Object
connection, // Object
collection, // Object
methodName, // String
methodArguments, // Array<String>
}) => {
console.log(type);
// ˆˆˆˆˆˆ The service name, such as "password" or "twitter".
console.log(allowed);
// ˆˆˆˆˆˆ 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).
console.log(error);
// ˆˆˆˆˆˆ When `allowed` is false, the exception describing why the login
// failed. It will be a `Meteor.Error` for failures reported to the
// user (such as invalid password), and can be a another kind of
// exception for internal errors.
console.log(user);
// ˆˆˆˆˆˆ When it is known which user was attempting to login,
// the Meteor user object. This will always be present for successful logins.
console.log(connection);
// ˆˆˆˆˆˆ The `connection` object the request came in on. See
// [`Meteor.onConnection`](#meteor_onconnection) for details.
console.log(collection);
// ˆˆˆˆˆˆ The `collection` The name of the Mongo.Collection or the
// Mongo.Collection object to hold the users.
console.log(methodName);
// ˆˆˆˆˆˆ The name of the Meteor method being used to login.
// For example, "login", "loginWithPassword", or "loginWith<ExternalService>".
console.log(methodArguments);
// ˆˆˆˆˆˆ An array of the arguments passed to the login method.
// For example, `["username", "password"]`
}
);
验证登录回调必须返回真值才能继续登录。如果回调返回假值或引发异常,则登录中止。抛出 Meteor.Error
会向用户报告错误原因。
¥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.
所有已注册的验证登录回调都会被调用,即使其中一个回调中止登录。由于登录现在不会成功,因此后续回调将看到 allowed
字段设置为 false
。这允许后续回调覆盖前一个回调的错误;例如,你可以用不同的消息覆盖 "密码不正确" 错误。
¥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
js
if (!attempt.allowed) {
return false;
}
accountsServer.beforeExternalLogin Server only
Server only
Summary:
Validate login from external service
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
func | function | Called whenever login/user creation from external service is attempted. Login or user creation based on this login can be aborted by passing a falsy value or throwing an exception. | Yes |
如果你需要验证来自外部服务的用户是否应该被允许登录或创建账户,请使用此钩子。
¥Use this hook if you need to validate that user from an external service should be allowed to login or create account.
js
import { AccountsServer } from "meteor/accounts-base";
const options = {
//...
};
const accountsServer = new AccountsServer(options);
accountsServer.beforeExternalLogin(({ type, data, user }) => {
console.log(type);
// ˆˆˆˆˆˆ The service name, such as "google" or "twitter". Is a String
console.log(data);
// ˆˆˆˆˆˆ Data retrieved from the service (eg: email, name, etc)
// Is an Object.
console.log(user);
// ˆˆˆˆˆˆ If user was found in the database that matches the criteria from the service,
// their data will be provided here. Is an Object.
});
你应该返回 Boolean
值,如果登录/注册应该继续,则返回 true
,如果应该终止,则返回 false
。如果终止,登录尝试将抛出错误 403
,并显示以下消息:Login forbidden
。
¥You should return a Boolean
value, true
if the login/registration should proceed or false
if it should terminate. In case of termination the login attempt will throw an error 403
, with the message: Login forbidden
.
accountsServer.setAdditionalFindUserOnExternalLogin Server only
Server only
Summary:
Customize user selection on external logins
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
func | function | Called whenever a user is logged in via oauth and a user is not found with the service id. Return the user or undefined. | Yes |
当允许你的用户使用外部服务进行身份验证时,该过程最终将调用 Accounts.updateOrCreateUserFromExternalService
。默认情况下,这将搜索具有 service.<servicename>.id
的用户,如果未找到,则创建新用户。由于这并不总是可取的,你可以将此钩子用作应急方案,使用不同的选择器(可能是 emails.address
或 username
)查找用户。请注意,只有在使用 service.<servicename>.id
选择器未找到用户时,才会调用该函数。
¥When allowing your users to authenticate with an external service, the process will eventually call Accounts.updateOrCreateUserFromExternalService
. By default, this will search for a user with the service.<servicename>.id
, and if not found will create a new user. As that is not always desirable, you can use this hook as an escape hatch to look up a user with a different selector, probably by emails.address
or username
. Note the function will only be called if no user was found with the service.<servicename>.id
selector.
该函数将使用单个参数(信息对象)调用:
¥The function will be called with a single argument, the info object:
js
import { AccountsServer } from "meteor/accounts-base";
const options = {
//...
};
const accountsServer = new AccountsServer(options);
accountsServer.setAdditionalFindUserOnExternalLogin(
({ serviceName, serviceData, options }) => {
// serviceName: String
// The external service name, such as "google" or "twitter".
// serviceData: Object
// The data returned by the service oauth request.
// options: Object
// An optional arugment passed down from the oauth service that may contain
// additional user profile information. As the data in `options` comes from an
// external source, make sure you validate any values you read from it.
}
);
该函数应返回用户文档或 undefined
。返回用户将导致在你的用户文档中填充 service.<servicename>
,而返回 undefined
将导致创建新的用户账户。如果你不希望创建新账户,你可以抛出错误而不是返回。
¥The function should return either a user document or undefined
. Returning a user will result in the populating the service.<servicename>
in your user document, while returning undefined
will result in a new user account being created. If you would prefer that a new account not be created, you could throw an error instead of returning.
示例:
¥Example:
js
// If a user has already been created, and used their Google email, this will
// allow them to sign in with the Meteor.loginWithGoogle method later, without
// creating a new user.
Accounts.setAdditionalFindUserOnExternalLogin(
({ serviceName, serviceData }) => {
if (serviceName === "google") {
// Note: Consider security implications. If someone other than the owner
// gains access to the account on the third-party service they could use
// the e-mail set there to access the account on your app.
// Most often this is not an issue, but as a developer you should be aware
// of how bad actors could play.
return Accounts.findUserByEmail(serviceData.email);
}
}
);
accountsServer.registerLoginHandler Server only
Server only
Summary:
Registers a new login handler.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
name | String | The type of login method like oauth, password, etc. | No |
handler | function | A function that receives an options object
(as passed as an argument to the | Yes |
js
// accountsServer is an instance of AccountsServer
accountsServer.registerLoginHandler(
"name", // this param is optional
() => {},
);
使用它来注册你自己的自定义身份验证方法。这也被所有其他内置账户包用于与账户系统集成。
¥Use this to register your own custom authentication method. This is also used by all of the other inbuilt accounts packages to integrate with the accounts system.
可以注册多个登录处理程序。当发出登录请求时,它将遍历所有这些处理程序以找到自己的处理程序。
¥There can be multiple login handlers that are registered. When a login request is made, it will go through all these handlers to find its own handler.
已注册的处理程序回调使用单个参数调用,即来自登录方法的 options
对象。例如,如果你希望使用纯文本密码登录,options
可以是 { user: { username: <username> }, password: <password> }
或 { user: { email: <email> }, password: <password> }
。
¥The registered handler callback is called with a single argument, the options
object which comes from the login method. For example, if you want to login with a plaintext password, options
could be { user: { username: <username> }, password: <password> }
,or { user: { email: <email> }, password: <password> }
.
如果登录处理程序不处理登录请求,则应返回 undefined
,否则返回登录结果对象。
¥The login handler should return undefined
if it's not going to handle the login request or else the login result object.
速率限制
默认情况下,DDPRateLimiter
中添加了规则,限制登录、新用户注册和密码重置调用的速率,每个会话每 10 秒最多可请求 5 次。这些是字典攻击的基本解决方案,恶意用户会尝试通过尝试所有可能的密码来猜测合法用户的密码。
¥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.
可以通过调用 Accounts.removeDefaultRateLimit()
来删除这些速率限制规则。有关更多信息,请参阅 DDPRateLimiter
文档。
¥These rate limiting rules can be removed by calling Accounts.removeDefaultRateLimit()
. Please see the DDPRateLimiter
docs for more information.
accountsServer.addDefaultRateLimit Server only
Server only
Summary:
Add a default rule of limiting logins, creating new users and password reset to 5 times every 10 seconds per connection.
js
// accountsServer is an instance of AccountsServer
accountsServer.addDefaultRateLimit();
accountsServer.removeDefaultRateLimit Server only
Server only
Summary:
Removes default rate limiting rule
js
// accountsServer is an instance of AccountsServer
accountsServer.removeDefaultRateLimit();
密码
¥Passwords
accounts-password
包包含一个基于密码的身份验证的完整系统。除了基本的基于用户名和密码的登录过程外,它还支持基于电子邮件的登录,包括地址验证和密码恢复电子邮件。
¥The accounts-password
package contains a full system for password-based authentication. In addition to the basic username and password-based sign-in process, it also supports email-based sign-in including address verification and password recovery emails.
Meteor 服务器使用 bcrypt 算法存储密码。如果服务器的数据库受到威胁,这有助于防止令人尴尬的密码泄露。
¥The Meteor server stores passwords using the bcrypt algorithm. This helps protect against embarrassing password leaks if the server's database is compromised.
要将密码支持添加到你的应用,请在你的终端中运行此命令:
¥To add password support to your application, run this command in your terminal:
bash
meteor add accounts-password
除了配置
MAIL_URL
之外,在Accounts.emailTemplates
中设置适当的值(特别是from
地址)以确保电子邮件正确送达也至关重要!¥In addition to configuring the
MAIL_URL
, it is critical that you set proper values (specifically thefrom
address) inAccounts.emailTemplates
to ensure proper delivery of e-mails!
你可以使用以下函数构建自己的用户界面,或者使用 accounts-ui
包 包含一个基于密码登录的交钥匙用户界面。
¥You can construct your own user interface using the functions below, or use the accounts-ui
package to include a turn-key user interface for password-based sign-in.
Accounts.createUser
Summary:
Create a new user.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | Yes | |
callback | function | Client only, optional callback. Called with no arguments on success, or with a single | No |
js
import { Accounts } from "meteor/accounts-base";
Accounts.createUser(
options,
() => {}, // this param is optional
);
在客户端,此功能在成功完成后以新创建的用户身份登录。在服务器上,它返回新创建的用户 ID。
¥On the client, this function logs in as the newly created user on successful completion. On the server, it returns the newly created user id.
在客户端,你必须传递 password
和至少一个 username
或 email
— 足够的信息,以便用户能够稍后再次登录。如果现有用户的用户名或电子邮件仅在大小写上不同,createUser
将失败。回调的 error.reason
将是 'Username already exists.'
或 'Email already exists.'
在后一种情况下,用户可以选择 login 或 重置密码。
¥On the client, you must pass password
and at least one of username
or email
— enough information for the user to be able to log in again later. If there are existing users with a username or email only differing in case, createUser
will fail. The callback's error.reason
will be 'Username already exists.'
or 'Email already exists.'
In the latter case, the user can then either login or reset their password.
在服务器上,你不需要指定 password
,但用户将无法登录,直到它拥有密码(例如,用 Accounts.setPasswordAsync
设置)。要在服务器上创建没有密码的账户,并且仍让用户选择自己的密码,请使用 email
选项调用 createUser
,然后调用 Accounts.sendEnrollmentEmail
。这将向用户发送一封电子邮件,其中包含设置其初始密码的链接。
¥On the server, you do not need to specify password
, but the user will not be able to log in until it has a password (eg, set with Accounts.setPasswordAsync
). To create an account without a password on the server and still let the user pick their own password, call createUser
with the email
option and then call Accounts.sendEnrollmentEmail
. This will send the user an email with a link to set their initial password.
默认情况下,profile
选项直接添加到新用户文档中。要覆盖此行为,请使用 Accounts.onCreateUser
。
¥By default the profile
option is added directly to the new user document. To override this behavior, use Accounts.onCreateUser
.
此功能仅用于创建具有密码的用户。外部服务登录流程不使用此功能。
¥This function is only used for creating users with passwords. The external service login flows do not use this function.
不要直接修改 Meteor.users
集合中的文档,而是使用这些便利函数,这些函数可以在更新之前正确检查不区分大小写的重复项。
¥Instead of modifying documents in the Meteor.users
collection directly, use these convenience functions which correctly check for case insensitive duplicates before updates.
Accounts.createUserAsync
Summary:
Create a new user and returns a promise of its result.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | Yes |
js
import { Accounts } from "meteor/accounts-base";
Accounts.createUserAsync(
options
);
Accounts.createUserVerifyingEmail Server only
Server only
Summary:
Creates an user asynchronously and sends an email if options.email
is informed.
Then if the sendVerificationEmail
option from the Accounts
package is
enabled, you'll send a verification email if options.password
is informed,
otherwise you'll send an enrollment email.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | The options object to be passed down when creating the user | Yes |
js
import { Accounts } from "meteor/accounts-base";
Accounts.createUserVerifyingEmail(
options
);
Accounts.setUsername Server only
Server only
Summary:
Change a user's username asynchronously. Use this instead of updating the database directly. The operation will fail if there is an existing user with a username only differing in case.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
userId | String | The ID of the user to update. | Yes |
newUsername | String | A new username for the user. | Yes |
js
import { Accounts } from "meteor/accounts-base";
Accounts.setUsername(
"userId",
"newUsername",
);
Accounts.addEmailAsync Server only
Server only
Summary:
Asynchronously add an email address for a user. Use this instead of directly updating the database. The operation will fail if there is a different user with an email only differing in case. If the specified user has an existing email only differing in case however, we replace it.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
userId | String | The ID of the user to update. | Yes |
newEmail | String | A new email address for the user. | Yes |
verified | Boolean | Optional - whether the new email address should be marked as verified. Defaults to false. | No |
js
import { Accounts } from "meteor/accounts-base";
Accounts.addEmailAsync(
"userId",
"newEmail",
false, // this param is optional
);
默认情况下,{ verified: false }
会添加一个电子邮件地址。使用 Accounts.sendVerificationEmail
发送带有链接的电子邮件,用户可以使用该链接来验证他们的电子邮件地址。
¥By default, an email address is added with { verified: false }
. Use Accounts.sendVerificationEmail
to send an email with a link the user can use to verify their email address.
Accounts.removeEmail Server only
Server only
Summary:
Remove an email address asynchronously for a user. Use this instead of updating the database directly.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
userId | String | The ID of the user to update. | Yes |
String | The email address to remove. | Yes |
js
import { Accounts } from "meteor/accounts-base";
Accounts.removeEmail(
"userId",
"email",
);
Accounts.verifyEmail Client only
Client only
Summary:
Marks the user's email address as verified. Logs the user in afterwards if the user doesn't have 2FA enabled.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
token | String | The token retrieved from the verification URL. | Yes |
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
import { Accounts } from "meteor/accounts-base";
Accounts.verifyEmail(
"token",
() => {}, // this param is optional
);
如果尝试验证电子邮件的用户启用了 2FA,则会抛出此错误:
¥If the user trying to verify the email has 2FA enabled, this error will be thrown:
"电子邮件已验证,但由于启用了 2FA,因此用户未登录 [2fa-enabled]":如果用户启用了 2FA,则不再自动登录用户。
¥"Email verified, but user not logged in because 2FA is enabled [2fa-enabled]": No longer signing in the user automatically if the user has 2FA enabled.
此函数接受传递到使用 Accounts.onEmailVerificationLink
注册的回调中的令牌。
¥This function accepts tokens passed into the callback registered with Accounts.onEmailVerificationLink
.
Accounts.findUserByUsername Server only
Server only
Summary:
Finds the user asynchronously with the specified username. First tries to match username case sensitively; if that fails, it tries case insensitively; but if more than one user matches the case insensitive search, it returns null.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
username | String | The username to look for | Yes |
options | Object | No |
js
import { Accounts } from "meteor/accounts-base";
/** @returns Promise<Object> */
const result = Accounts.findUserByUsername(
"username",
options, // this param is optional
);
Accounts.findUserByEmail Server only
Server only
Summary:
Finds the user asynchronously with the specified email. First tries to match email case sensitively; if that fails, it tries case insensitively; but if more than one user matches the case insensitive search, it returns null.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
String | The email address to look for | Yes | |
options | Object | No |
js
import { Accounts } from "meteor/accounts-base";
/** @returns Promise<Object> */
const result = Accounts.findUserByEmail(
"email",
options, // this param is optional
);
使用以下函数从服务器或客户端启动密码更改或重置。
¥Use the below functions to initiate password changes or resets from the server or the client.
Accounts.changePassword Client only
Client only
Summary:
Change the current user's password. Must be logged in.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
oldPassword | String | The user's current password. This is not sent in plain text over the wire. | Yes |
newPassword | String | A new password for the user. This is not sent in plain text over the wire. | Yes |
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
import { Accounts } from "meteor/accounts-base";
Accounts.changePassword(
"oldPassword",
"newPassword",
() => {}, // this param is optional
);
Accounts.forgotPassword Client only
Client only
Summary:
Request a forgot password email.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
options | Object | Yes | |
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
import { Accounts } from "meteor/accounts-base";
Accounts.forgotPassword(
options,
() => {}, // this param is optional
);
这会触发对服务器上 Accounts.sendResetPasswordEmail
的调用。当用户访问此电子邮件中的链接时,将调用使用 Accounts.onResetPasswordLink
注册的回调。
¥This triggers a call to Accounts.sendResetPasswordEmail
on the server. When the user visits the link in this email, the callback registered with Accounts.onResetPasswordLink
will be called.
如果你使用的是 accounts-ui
包,这将自动处理。否则,你有责任提示用户输入新密码并调用 resetPassword
。
¥If you are using the accounts-ui
package, this is handled automatically. Otherwise, it is your responsibility to prompt the user for the new password and call resetPassword
.
Accounts.resetPassword Client only
Client only
Summary:
Reset the password for a user using a token received in email. Logs the user in afterwards if the user doesn't have 2FA enabled.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
token | String | The token retrieved from the reset password URL. | Yes |
newPassword | String | A new password for the user. This is not sent in plain text over the wire. | Yes |
callback | function | Optional callback. Called with no arguments on success, or with a single | No |
js
import { Accounts } from "meteor/accounts-base";
Accounts.resetPassword(
"token",
"newPassword",
() => {}, // this param is optional
);
此函数接受传递到使用 AccountsClient#onResetPasswordLink
和 Accounts.onEnrollmentLink
注册的回调中的令牌。
¥This function accepts tokens passed into the callbacks registered with AccountsClient#onResetPasswordLink
and Accounts.onEnrollmentLink
.
如果尝试重置密码的用户启用了 2FA,则会抛出此错误:
¥If the user trying to reset the password has 2FA enabled, this error will be thrown:
"更改密码,但用户未登录,因为启用了 2FA [2fa-enabled]":如果用户启用了 2FA,则不再自动登录用户。
¥"Changed password, but user not logged in because 2FA is enabled [2fa-enabled]": No longer signing in the user automatically if the user has 2FA enabled.
Accounts.setPasswordAsync Server only
Server only
Summary:
Forcibly change the password for a user.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
userId | String | The id of the user to update. | Yes |
newPassword | String | A new password for the user. | Yes |
options | Object | No |
js
import { Accounts } from "meteor/accounts-base";
Accounts.setPasswordAsync(
"userId",
"newPassword",
options, // this param is optional
);
Accounts.sendResetPasswordEmail Server only
Server only
Summary:
Send an email asynchronously with a link the user can use to reset their password.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
userId | String | The id of the user to send email to. | Yes |
String | Optional. Which address of the user's to send the email to. This address must be in the user's | No | |
extraTokenData | Object | Optional additional data to be added into the token record. | No |
extraParams | Object | Optional additional params to be added to the reset url. | No |
js
import { Accounts } from "meteor/accounts-base";
/** @returns Promise<Object> */
const result = Accounts.sendResetPasswordEmail(
"userId",
"email", // this param is optional
extraTokenData, // this param is optional
extraParams, // this param is optional
);
当用户访问此电子邮件中的链接时,将调用使用 AccountsClient#onResetPasswordLink
注册的回调。
¥When the user visits the link in this email, the callback registered with AccountsClient#onResetPasswordLink
will be called.
要自定义电子邮件的内容,请参阅 Accounts.emailTemplates
。
¥To customize the contents of the email, see Accounts.emailTemplates
.
Accounts.sendEnrollmentEmail Server only
Server only
Summary:
Send an email asynchronously with a link the user can use to set their initial password.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
userId | String | The id of the user to send email to. | Yes |
String | Optional. Which address of the user's to send the email to. This address must be in the user's | No | |
extraTokenData | Object | Optional additional data to be added into the token record. | No |
extraParams | Object | Optional additional params to be added to the enrollment url. | No |
js
import { Accounts } from "meteor/accounts-base";
/** @returns Promise<Object> */
const result = Accounts.sendEnrollmentEmail(
"userId",
"email", // this param is optional
extraTokenData, // this param is optional
extraParams, // this param is optional
);
当用户访问此电子邮件中的链接时,将调用使用 Accounts.onEnrollmentLink
注册的回调。
¥When the user visits the link in this email, the callback registered with Accounts.onEnrollmentLink
will be called.
要自定义电子邮件的内容,请参阅 Accounts.emailTemplates
。
¥To customize the contents of the email, see Accounts.emailTemplates
.
Accounts.sendVerificationEmail Server only
Server only
Summary:
Send an email asynchronously with a link the user can use verify their email address.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
userId | String | The id of the user to send email to. | Yes |
String | Optional. Which address of the user's to send the email to. This address must be in the user's | No | |
extraTokenData | Object | Optional additional data to be added into the token record. | No |
extraParams | Object | Optional additional params to be added to the verification url. | No |
js
import { Accounts } from "meteor/accounts-base";
/** @returns Promise<Object> */
const result = Accounts.sendVerificationEmail(
"userId",
"email", // this param is optional
extraTokenData, // this param is optional
extraParams, // this param is optional
);
当用户访问此电子邮件中的链接时,将调用使用 Accounts.onEmailVerificationLink
注册的回调。
¥When the user visits the link in this email, the callback registered with Accounts.onEmailVerificationLink
will be called.
要自定义电子邮件的内容,请参阅 Accounts.emailTemplates
。
¥To customize the contents of the email, see Accounts.emailTemplates
.
Accounts.onResetPasswordLink Client only
Client only
Summary:
Register a function to call when a reset password link is clicked
in an email sent by
Accounts.sendResetPasswordEmail
.
This function should be called in top-level code, not inside
Meteor.startup()
.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
callback | function | The function to call. It is given two arguments:
| Yes |
js
import { Accounts } from "meteor/accounts-base";
Accounts.onResetPasswordLink(
() => {}
);
Accounts.onEnrollmentLink Client only
Client only
Summary:
Register a function to call when an account enrollment link is
clicked in an email sent by
Accounts.sendEnrollmentEmail
.
This function should be called in top-level code, not inside
Meteor.startup()
.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
callback | function | The function to call. It is given two arguments:
| Yes |
js
import { Accounts } from "meteor/accounts-base";
Accounts.onEnrollmentLink(
() => {}
);
Accounts.onEmailVerificationLink Client only
Client only
Summary:
Register a function to call when an email verification link is
clicked in an email sent by
Accounts.sendVerificationEmail
.
This function should be called in top-level code, not inside
Meteor.startup()
.
Arguments:
Source codeName | Type | Description | Required |
---|---|---|---|
callback | function | The function to call. It is given two arguments:
| Yes |
js
import { Accounts } from "meteor/accounts-base";
Accounts.onEmailVerificationLink(
() => {}
);
Accounts.emailTemplates Server only
Server only
Summary:
Options to customize emails sent from the Accounts system.
这是一个 Object
,其中包含几个字段,用于为 sendResetPasswordEmail
、sendEnrollmentEmail
和 sendVerificationEmail
发送的电子邮件生成文本/html。
¥This is an Object
with several fields that are used to generate text/html for the emails sent by sendResetPasswordEmail
, sendEnrollmentEmail
, and sendVerificationEmail
.
通过分配来设置对象的字段:
¥Set the fields of the object by assigning to them:
from
:(必需)带有 RFC5322 From 地址的String
。默认情况下,电子邮件是从no-reply@example.com
发送的。如果你希望电子邮件正确发送,应将其更改为你自己的域,因为大多数电子邮件提供商会拒绝从example.com
发送的邮件。¥
from
: (required) AString
with an RFC5322 From address. By default, the email is sent fromno-reply@example.com
. If you want e-mails to send correctly, this should be changed to your own domain as most e-mail providers will reject mail sent fromexample.com
.siteName
:应用的公共名称。默认为应用的 DNS 名称(例如:awesome.meteor.com
)。¥
siteName
: The public name of your application. Defaults to the DNS name of the application (eg:awesome.meteor.com
).headers
:Email.send
中描述的自定义电子邮件标题的Object
。¥
headers
: AnObject
for custom email headers as described inEmail.send
.resetPassword
:带有字段的Object
:¥
resetPassword
: AnObject
with the fields:from
:Function
用于覆盖emailTemplates.from
字段定义的from
地址。¥
from
: AFunction
used to override thefrom
address defined by theemailTemplates.from
field.subject
:Function
接受用户对象并返回String
作为重置密码电子邮件的主题行。¥
subject
: AFunction
that takes a user object and returns aString
for the subject line of a reset password email.text
:可选的Function
接受用户对象和 url,并返回重置密码电子邮件的正文。¥
text
: An optionalFunction
that takes a user object and a url, and returns the body text for a reset password email.html
:可选的Function
接受用户对象和 url,并返回重置密码电子邮件的正文 html。¥
html
: An optionalFunction
that takes a user object and a url, and returns the body html for a reset password email.enrollAccount
:与resetPassword
相同,但用于设置新账户的初始密码。¥
enrollAccount
: Same asresetPassword
, but for initial password setup for new accounts.verifyEmail
:与resetPassword
相同,但用于验证用户的电子邮件地址。¥
verifyEmail
: Same asresetPassword
, but for verifying the users email address.
示例:
¥Example:
js
import { Accounts } from "meteor/accounts-base";
Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <accounts@example.com>";
Accounts.emailTemplates.enrollAccount.subject = (user) => {
return `Welcome to Awesome Town, ${user.profile.name}`;
};
Accounts.emailTemplates.enrollAccount.text = (user, url) => {
return (
"You have been selected to participate in building a better future!" +
" To activate your account, simply click the link below:\n\n" +
url
);
};
Accounts.emailTemplates.resetPassword.from = () => {
// Overrides the value set in `Accounts.emailTemplates.from` when resetting
// passwords.
return "AwesomeSite Password Reset <no-reply@example.com>";
};
Accounts.emailTemplates.verifyEmail = {
subject() {
return "Activate your account now!";
},
text(user, url) {
return `Hey ${user}! Verify your e-mail by following this link: ${url}`;
},
};
为此包启用 2FA
你可以使用包 accounts-2fa 将 2FA 添加到你的登录流程中。你可以找到一个显示它看起来像 此处 的示例。
¥You can add 2FA to your login flow by using the package accounts-2fa. You can find an example showing how this would look like here.