From 1feda279afc8bebd9afd4d2ab573cb84640395fb Mon Sep 17 00:00:00 2001 From: Gabriel Grubba Date: Mon, 30 Mar 2026 20:52:30 -0300 Subject: [PATCH 1/3] DOCS: remove routing from core concepts docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This doc only covers FlowRouter and Blaze, I'm not sure how useful this doc can be for core in general(maybe we could have multiple sections about routers?) – I'll remove this one for now until we know how to proceed about these core concepts(what should be a core concept?) --- v3-docs/docs/.vitepress/config.mts | 4 - v3-docs/docs/tutorials/routing/routing.md | 505 ---------------------- 2 files changed, 509 deletions(-) delete mode 100644 v3-docs/docs/tutorials/routing/routing.md diff --git a/v3-docs/docs/.vitepress/config.mts b/v3-docs/docs/.vitepress/config.mts index 25eb149a16..5cd9edb97f 100644 --- a/v3-docs/docs/.vitepress/config.mts +++ b/v3-docs/docs/.vitepress/config.mts @@ -553,10 +553,6 @@ export default defineConfig({ text: "Accounts", link: "/tutorials/accounts/accounts", }, - { - text: "Routing", - link: "/tutorials/routing/routing", - }, ] }, { diff --git a/v3-docs/docs/tutorials/routing/routing.md b/v3-docs/docs/tutorials/routing/routing.md deleted file mode 100644 index 2f66c8e00f..0000000000 --- a/v3-docs/docs/tutorials/routing/routing.md +++ /dev/null @@ -1,505 +0,0 @@ -# URLs and Routing - -After reading this guide, you'll know: - -1. The role URLs play in a client-rendered app, and how it's different from a traditional server-rendered app. -2. How to define client and server routes for your app using Flow Router. -3. How to have your app display different content depending on the URL. -4. How to dynamically load application modules depending on the URL. -5. How to construct links to routes and go to routes programmatically. - -## Client-side Routing - -In a web application, _routing_ is the process of using URLs to drive the user interface (UI). URLs are a prominent feature in every single web browser, and have several main functions from the user's point of view: - -1. **Bookmarking** - Users can bookmark URLs in their web browser to save content they want to come back to later. -2. **Sharing** - Users can share content with others by sending a link to a certain page. -3. **Navigation** - URLs are used to drive the web browser's back/forward functions. - -In a traditional web application stack, where the server renders HTML one page at a time, the URL is the fundamental entry point for the user to access the application. Users navigate an application by clicking through URLs, which are sent to the server via HTTP, and the server responds appropriately via a server-side router. - -In contrast, Meteor operates on the principle of _data on the wire_, where the server doesn't think in terms of URLs or HTML pages. The client application communicates with the server over DDP. Typically as an application loads, it initializes a series of _subscriptions_ which fetch the data required to render the application. As the user interacts with the application, different subscriptions may load, but there's no technical need for URLs to be involved in this process - you could have a Meteor app where the URL never changes. - -However, most of the user-facing features of URLs listed above are still relevant for typical Meteor applications. Since the server is not URL-driven, the URL becomes a useful representation of the client-side state the user is currently looking at. However, unlike in a server-rendered application, it does not need to describe the entirety of the user's current state; it needs to contain the parts that you want to be linkable. For example, the URL should contain any search filters applied on a page, but not necessarily the state of a dropdown menu or popup. - -## Using Flow Router - -To add routing to your app, install the [`ostrio:flow-router-extra`](https://atmospherejs.com/ostrio/flow-router-extra) package: - -```bash -meteor add ostrio:flow-router-extra -``` - -Flow Router Extra is the community routing package for Meteor. It is a carefully extended `flow-router` package with additional features like `waitOn`, template context, and built-in `.render()`. The packages `arillo:flow-router-helpers` and `zimme:active-route` are already built into Flow Router Extra and updated to support the latest Meteor release. - -## Defining a simple route - -The basic purpose of a router is to match certain URLs and perform actions as a result. This all happens on the client side, in the app user's browser or mobile app container. Let's take an example from the Todos example app: - -```js -import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; - -FlowRouter.route('/lists/:_id', { - name: 'Lists.show', - action(params, queryParams) { - console.log("Looking at a list?"); - } -}); -``` - -This route handler will run in two situations: if the page loads initially at a URL that matches the URL pattern, or if the URL changes to one that matches the pattern while the page is open. Note that, unlike in a server-side-rendered app, the URL can change without any additional requests to the server. - -When the route is matched, the `action` method executes, and you can perform any actions you need to. The `name` property of the route is optional, but will let us refer to this route more conveniently later on. - -### URL pattern matching - -Consider the following URL pattern, used in the code snippet above: - -```js -'/lists/:_id' -``` - -The above pattern will match certain URLs. You may notice that one segment of the URL is prefixed by `:` - this means that it is a *url parameter*, and will match any string that is present in that segment of the path. Flow Router will make that part of the URL available on the `params` property of the current route. - -Additionally, the URL could contain an HTTP [*query string*](https://en.wikipedia.org/wiki/Query_string) (the part after an optional `?`). If so, Flow Router will also split it up into named parameters, which it calls `queryParams`. - -Here are some example URLs and the resulting `params` and `queryParams`: - -| URL | matches pattern? | params | queryParams | -| ---- | ---- | ---- | ---- | -| / | no | | | -| /about | no | | | -| /lists/ | no | | | -| /lists/eMtGij5AFESbTKfkT | yes | { _id: "eMtGij5AFESbTKfkT"} | { } | -| /lists/1 | yes | { _id: "1"} | { } | -| /lists/1?todoSort=top | yes | { _id: "1"} | { todoSort: "top" } | - -Note that all of the values in `params` and `queryParams` are always strings since URLs don't have any way of encoding data types. For example, if you wanted a parameter to represent a number, you might need to use `parseInt(value, 10)` to convert it when you access it. - -## Accessing Route information - -In addition to passing in the parameters as arguments to the `action` function on the route, Flow Router makes a variety of information available via (reactive and otherwise) functions on the global singleton `FlowRouter`. As the user navigates around your app, the values of these functions will change (reactively in some cases) correspondingly. - -Like any other global singleton in your application, it's best to limit your access to `FlowRouter`. That way the parts of your app will remain modular and more independent. In the case of `FlowRouter`, it's best to access it solely from the top of your component hierarchy, either in the "page" component, or the layouts that wrap it. - -### The current route - -It's useful to access information about the current route in your code. Here are some reactive functions you can call: - -* `FlowRouter.getRouteName()` gets the name of the route -* `FlowRouter.getParam(paramName)` returns the value of a single URL parameter -* `FlowRouter.getQueryParam(paramName)` returns the value of a single URL query parameter - -In our example of the list page from the Todos app, we access the current list's id with `FlowRouter.getParam('_id')`. - -### Highlighting the active route - -One situation where it is sensible to access the global `FlowRouter` singleton to access the current route's information deeper in the component hierarchy is when rendering links via a navigation component. It's often required to highlight the "active" route in some way (this is the route or section of the site that the user is currently looking at). - -In the Todos example app, we link to each list the user knows about in the `App_body` template: - -```html -{{#each list in lists}} - - ... - {{list.name}} - -{{/each}} -``` - -We can determine if the user is currently viewing the list with the `activeListClass` helper: - -```js -Template.App_body.helpers({ - activeListClass(list) { - const active = ActiveRoute.name('Lists.show') - && FlowRouter.getParam('_id') === list._id; - - return active && 'active'; - } -}); -``` - -## Rendering based on the route - -Now we understand how to define routes and access information about the current route, we are in a position to do what you usually want to do when a user accesses a route---render a user interface to the screen that represents it. - -### Rendering with Blaze - -When using Flow Router with Blaze, the simplest way to display different views on the page for different URLs is to use the complementary Blaze Layout package. First, make sure you have the Blaze Layout package installed: - -```bash -meteor add kadira:blaze-layout -``` - -To use this package, we need to define a "layout" component. In the Todos example app, that component is called `App_body`: - -```html - -``` - -Here, we are using a Blaze feature called `Template.dynamic` to render a template which is attached to the `main` property of the data context. Using Blaze Layout, we can change that `main` property when a route is accessed. - -We do that in the `action` function of our `Lists.show` route definition: - -```js -import { BlazeLayout } from 'meteor/kadira:blaze-layout'; -import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; - -FlowRouter.route('/lists/:_id', { - name: 'Lists.show', - action() { - BlazeLayout.render('App_body', { main: 'Lists_show_page' }); - } -}); -``` - -What this means is that whenever a user visits a URL of the form `/lists/X`, the `Lists.show` route will kick in, triggering the `BlazeLayout` call to set the `main` property of the `App_body` component. - -### Rendering with React - -When using React, you can render components directly in the route action. Here's how to set up React with Flow Router: - -```js -import React from 'react'; -import { createRoot } from 'react-dom/client'; -import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; - -// Create a root element for React -const rootElement = document.getElementById('react-root'); -const root = createRoot(rootElement); - -FlowRouter.route('/lists/:_id', { - name: 'Lists.show', - action(params) { - root.render(); - } -}); -``` - -Or you can use `react-mount` package for a more integrated approach: - -```bash -meteor npm install react-mounter -``` - -```js -import { mount } from 'react-mounter'; -import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; -import { MainLayout } from './layouts/MainLayout'; -import { ListsShowPage } from './pages/ListsShowPage'; - -FlowRouter.route('/lists/:_id', { - name: 'Lists.show', - action(params) { - mount(MainLayout, { - content: - }); - } -}); -``` - -## Components as pages - -Notice that we called the component to be rendered `Lists_show_page` (rather than `Lists_show`). This indicates that this template is rendered directly by a Flow Router action and forms the 'top' of the rendering hierarchy for this URL. - -The `Lists_show_page` template renders *without* arguments---it is this template's responsibility to collect information from the current route, and then pass this information down into its child templates. Correspondingly the `Lists_show_page` template is very tied to the route that rendered it, and so it needs to be a smart component. - -It makes sense for a "page" smart component like `Lists_show_page` to: - -1. Collect route information, -2. Subscribe to relevant subscriptions, -3. Fetch the data from those subscriptions, and -4. Pass that data into a sub-component. - -In this case, the HTML template for `Lists_show_page` will look very simple, with most of the logic in the JavaScript code: - -```html - -``` - -```js -Template.Lists_show_page.helpers({ - listIdArray() { - const instance = Template.instance(); - const listId = instance.getListId(); - return Lists.findOne(listId) ? [listId] : []; - }, - async listArgs(listId) { - const instance = Template.instance(); - return { - todosReady: instance.subscriptionsReady(), - list() { - return Lists.findOne(listId); - }, - todos: await Lists.findOneAsync(listId, { fields: { _id: true } }).todos() - }; - } -}); -``` - -### Changing page when logged out - -There are types of rendering logic that appear related to the route but which also seem related to user interface rendering. A classic example is authorization; for instance, you may want to render a login form for some subset of your pages if the user is not yet logged in. - -It's best to keep all logic around what to render in the component hierarchy. So this authorization should happen inside a component: - -```html - -``` - -You can create wrapper components using Blaze's "template as block helper" ability: - -```html - -``` - -Once that template exists, we can wrap our `Lists_show_page`: - -```html - -``` - -## Changing Routes - -Rendering an updated UI when a user reaches a new route is not that useful without giving the user some way to reach a new route! The simplest way is with the trusty `` tag and a URL. You can generate the URLs yourself using helpers such as `FlowRouter.pathFor` to display a link to a certain route: - -```html - -``` - -### Routing programmatically - -In some cases you want to change routes based on user action outside of them clicking on a link. For instance, in the example app, when a user creates a new list, we want to route them to the list they just created. We do this by calling `FlowRouter.go()` once we know the id of the new list: - -```js -import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; - -Template.App_body.events({ - async 'click .js-new-list'() { - const listId = await insert.callAsync(); - FlowRouter.go('Lists.show', { _id: listId }); - } -}); -``` - -You can also change only part of the URL if you want to, using the `FlowRouter.setParams()` and `FlowRouter.setQueryParams()`. For instance, if we were viewing one list and wanted to go to another: - -```js -FlowRouter.setParams({ _id: newList._id }); -``` - -Of course, calling `FlowRouter.go()` will always work, so unless you are trying to optimize for a specific situation it's better to use that. - -### Storing data in the URL - -As we discussed in the introduction, the URL is really a serialization of some part of the client-side state the user is looking at. Although parameters can only be strings, it's possible to convert any type of data to a string by serializing it. - -In general if you want to store arbitrary serializable data in a URL param, you can use `EJSON.stringify()` to turn it into a string. You'll need to URL-encode the string using `encodeURIComponent` to remove any characters that have meaning in a URL: - -```js -import { EJSON } from 'meteor/ejson'; -import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; - -FlowRouter.setQueryParams({ data: encodeURIComponent(EJSON.stringify(data)) }); -``` - -You can then get the data back out of Flow Router using `EJSON.parse()`. Note that Flow Router does the URL decoding for you automatically: - -```js -const data = EJSON.parse(FlowRouter.getQueryParam('data')); -``` - -## Redirecting - -Sometimes, your users will end up on a page that isn't a good place for them to be. Maybe the data they were looking for has moved, maybe they were on an admin panel page and logged out, or maybe they just created a new object and you want them to end up on the page for the thing they just created. - -Usually, we can redirect in response to a user's action by calling `FlowRouter.go()` and friends, like in our list creation example above, but if a user browses directly to a URL that doesn't exist, it's useful to know how to redirect immediately. - -If a URL is out-of-date (sometimes you might change the URL scheme of an application), you can redirect inside the `action` function of the route: - -```js -FlowRouter.route('/old-list-route/:_id', { - action(params) { - FlowRouter.go('Lists.show', params); - } -}); -``` - -### Redirecting dynamically - -The above approach will only work for static redirects. However, sometimes you need to load some data to figure out where to redirect to. In this case you'll need to render part of the component hierarchy to subscribe to the data you need. For example, in the Todos example app, we want to make the root (`/`) route redirect to the first known list: - -```js -FlowRouter.route('/', { - name: 'App.home', - action() { - BlazeLayout.render('App_body', { main: 'App_rootRedirector' }); - } -}); -``` - -The `App_rootRedirector` component is rendered inside the `App_body` layout: - -```js -Template.App_rootRedirector.onCreated(function rootRedirectorOnCreated() { - this.autorun(async () => { - if (this.subscriptionsReady()) { - const list = await Lists.findOneAsync(); - if (list) { - FlowRouter.go('Lists.show', { _id: list._id }); - } - } - }); -}); -``` - -### Redirecting after a user's action - -Often, you just want to go to a new route programmatically when a user has completed a certain action. If you want to wait for the method to return from the server, you can use async/await: - -```js -Template.App_body.events({ - async 'click .js-new-list'() { - try { - const listId = await lists.insert.callAsync(); - FlowRouter.go('Lists.show', { _id: listId }); - } catch (err) { - // Handle error - show message to user - console.error('Failed to create list:', err); - } - } -}); -``` - -You will also want to show some kind of indication that the method is working in between their click of the button and the redirect completing. Don't forget to provide feedback if the method is returning an error. - -## Advanced Routing - -### Dynamically load modules - -[Dynamic imports](https://docs.meteor.com/packages/dynamic-import) allow you to dramatically reduce the client's bundle size, and load modules and dependencies dynamically upon request, based on the current URI. - -Assume we have `index.html` and `index.js` with code for `index` template and this is the only place in the application where it depends on the large `moment` package. This means the `moment` package is not needed in the other parts of our app, and it will only waste bandwidth and slow load time. - -```html - - -``` - -```js -// /imports/client/index.js -import moment from 'moment'; -import { Template } from 'meteor/templating'; -import './index.html'; - -Template.index.helpers({ - time() { - return moment().format('LTS'); - } -}); -``` - -```js -// /imports/lib/routes.js -import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; -import { BlazeLayout } from 'meteor/kadira:blaze-layout'; - -FlowRouter.route('/', { - name: 'index', - waitOn() { - // Wait for index.js to load over the wire - return import('/imports/client/index.js'); - }, - action() { - BlazeLayout.render('App_body', { main: 'index' }); - } -}); -``` - -### Missing pages (404) - -If a user types an incorrect URL, chances are you want to show them some kind of amusing not-found page. There are actually two categories of not-found pages. The first is when the URL typed in doesn't match any of your route definitions. You can use `FlowRouter.notFound` to handle this: - -```js -FlowRouter.notFound = { - action() { - BlazeLayout.render('App_body', { main: 'App_notFound' }); - } -}; -``` - -The second is when the URL is valid, but doesn't actually match any data. In this case, the URL matches a route, but once the route has successfully subscribed, it discovers there is no data. It usually makes sense in this case for the page component to render a not-found template instead of the usual template for the page: - -```html - -``` - -### Analytics - -It's common to want to know which pages of your app are most commonly visited, and where users are coming from. You can read about how to set up Flow Router based analytics in the [Deployment Guide](/tutorials/deployment/deployment#analytics). - -### Server Side Routing - -As we've discussed, Meteor is a framework for client rendered applications, but this doesn't always remove the requirement for server rendered routes. There are three main use cases for server-side routing. - -#### Server Routing for API access - -Although Meteor allows you to write low-level connect handlers to create any kind of API you like on the server-side, if all you want to do is create a RESTful version of your Methods and Publications, you can often use the [`simple:rest`](http://atmospherejs.com/simple/rest) package. - -If you need more control, you can use the comprehensive [`nimble:restivus`](https://atmospherejs.com/nimble/restivus) package to create more or less whatever you need in whatever ontology you require. - -#### Server Rendering - -While Blaze does not have support for server-side rendering, React does. This means it is possible to render HTML on the server if you use React as your rendering framework. - -For server-side rendering with React, consider using packages like [`server-render`](/packages/server-render) which provides utilities for SSR in Meteor. - -#### Server Routing for additional resources - -There might be additional resources that you want to make available on your server or receive web hooks. If you need anything more complicated with dynamic parts of the URL you might want to implement [Picker](https://atmospherejs.com/communitypackages/picker) which is a simple server-side router that handles dynamic routes. - -If you need to authenticate the user when providing additional server-side resources such as PDF documents or XLSX spreadsheets, you can use [`mhagmajer:server-router`](https://atmospherejs.com/mhagmajer/server-router) package to do this easily. From e02d65a09a6505170fdaf79afac62117fdc4fb53 Mon Sep 17 00:00:00 2001 From: Gabriel Grubba Date: Mon, 30 Mar 2026 21:09:35 -0300 Subject: [PATCH 2/3] DOCS: revamp and update accounts tutorial MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In this PR: Removed - `accounts-ui`section - `alanning:roles` references — replaced with the Meteor core roles package Updated methods to be using the correct name(*Async for example) And added sections about Passwordless login, 2FA and Security configuration --- v3-docs/docs/tutorials/accounts/accounts.md | 565 +++++++++++++++----- 1 file changed, 434 insertions(+), 131 deletions(-) diff --git a/v3-docs/docs/tutorials/accounts/accounts.md b/v3-docs/docs/tutorials/accounts/accounts.md index 8d5d3154c3..05d5329b07 100644 --- a/v3-docs/docs/tutorials/accounts/accounts.md +++ b/v3-docs/docs/tutorials/accounts/accounts.md @@ -3,11 +3,12 @@ After reading this article, you'll know: 1. What features in core Meteor enable user accounts -2. How to use accounts-ui for a quick prototype -3. How to build a fully-featured password login experience -4. How to enable login through OAuth providers like Facebook -5. How to add custom data to Meteor's users collection -6. How to manage user roles and permissions +2. How to build a fully-featured password login experience +3. How to set up passwordless login +4. How to add two-factor authentication (2FA) +5. How to enable login through OAuth providers like Facebook +6. How to add custom data to Meteor's users collection +7. How to protect your data with per-document permissions ## Features in core Meteor @@ -23,41 +24,13 @@ This built-in feature means that you always get `this.userId` inside Methods and This package is the core of Meteor's developer-facing user accounts functionality. This includes: -1. A users collection with a standard schema, accessed through [`Meteor.users`](/api/accounts#Meteor-users), and the client-side singletons [`Meteor.userId()`](/api/accounts#Meteor-userId) and [`Meteor.user()`](/api/accounts#Meteor-user), which represent the login state on the client. -2. A variety of helpful other generic methods to keep track of login state, log out, validate users, etc. Visit the [Accounts section of the docs](/api/accounts) to find a complete list. -3. An API for registering new login handlers, which is used by all of the other accounts packages to integrate with the accounts system. +1. A users collection with a standard schema, accessed through [`Meteor.users`](/api/accounts#Meteor-users), and the client-side singletons [`Meteor.userId()`](/api/accounts#Meteor-userId), [`Meteor.user()`](/api/accounts#Meteor-user), and the async [`Meteor.userAsync()`](/api/accounts#Meteor-userAsync), which represent the login state on the client. +2. Reactive helpers [`Accounts.loggingIn()`](/api/accounts#Accounts-loggingIn) and [`Accounts.loggingOut()`](/api/accounts#Accounts-loggingOut) to track in-progress login/logout state. +3. A variety of helpful other generic methods to keep track of login state, log out, validate users, etc. Visit the [Accounts section of the docs](/api/accounts) to find a complete list. +4. An API for registering new login handlers, which is used by all of the other accounts packages to integrate with the accounts system. Usually, you don't need to include `accounts-base` yourself since it's added for you if you use `accounts-password` or similar, but it's good to be aware of what is what. -## Fast prototyping with accounts-ui - -Often, a complicated accounts system is not the first thing you want to build when you're starting out with a new app, so it's useful to have something you can drop in quickly. This is where `accounts-ui` comes in - it's one line that you drop into your app to get an accounts system. To add it: - -```bash -meteor add accounts-ui -``` - -Then include it anywhere in a Blaze template: - -```html -{{> loginButtons}} -``` - -Then, make sure to pick a login provider; they will automatically integrate with `accounts-ui`: - -```bash -# pick one or more of the below -meteor add accounts-password -meteor add accounts-facebook -meteor add accounts-google -meteor add accounts-github -meteor add accounts-twitter -meteor add accounts-meetup -meteor add accounts-meteor-developer -``` - -Now open your app, follow the configuration steps, and you're good to go - if you've done one of our [Meteor tutorials](/tutorials/react/1.creating-the-app), you've already seen this in action. Of course, in a production application, you probably want a more custom user interface and some logic to have a more tailored UX, but that's why we have the rest of these tutorials. - ## Password login Meteor comes with a secure and fully-featured password login system out of the box. To use it, add the package: @@ -66,11 +39,9 @@ Meteor comes with a secure and fully-featured password login system out of the b meteor add accounts-password ``` -To see what options are available to you, read the complete description of the [`accounts-password` API in the Meteor docs](/api/accounts). - ### Requiring username or email -By default, the `Accounts.createUser` function provided by `accounts-password` allows you to create an account with a username, email, or both. Most apps expect a specific combination of the two, so you will certainly want to validate the new user creation: +By default, the `Accounts.createUserAsync` function provided by `accounts-password` allows you to create an account with a username, email, or both. Most apps expect a specific combination of the two, so you will certainly want to validate the new user creation: ```js // Ensuring every user has an email address, should be in server-side code @@ -78,11 +49,11 @@ Accounts.validateNewUser((user) => { new SimpleSchema({ _id: { type: String }, emails: { type: Array }, - 'emails.$': { type: Object }, - 'emails.$.address': { type: String }, - 'emails.$.verified': { type: Boolean }, + "emails.$": { type: Object }, + "emails.$.address": { type: String }, + "emails.$.verified": { type: Boolean }, createdAt: { type: Date }, - services: { type: Object, blackbox: true } + services: { type: Object, blackbox: true }, }).validate(user); // Return true to allow user creation to proceed @@ -90,11 +61,49 @@ Accounts.validateNewUser((user) => { }); ``` -### Multiple emails +> When creating users programmatically, prefer the async variant: -Often, users might want to associate multiple email addresses with the same account. `accounts-password` addresses this case by storing the email addresses as an array in the user collection. There are some handy API methods to deal with [adding](/api/accounts#Accounts-addEmail), [removing](/api/accounts#Accounts-removeEmail), and [verifying](/api/accounts#Accounts-verifyEmail) emails. +```js +// Client or server +const userId = await Accounts.createUserAsync({ + username: "ada", + email: "ada@lovelace.com", + password: "secret", + profile: { name: "Ada Lovelace" }, +}); +``` -One useful thing to add for your app can be the concept of a "primary" email address. This way, if the user has added multiple emails, you know where to send confirmation emails and similar. +If you want to automatically send an email verification after account creation, use `Accounts.createUserVerifyingEmail` instead: + +```js +await Accounts.createUserVerifyingEmail({ + email: "ada@lovelace.com", + password: "secret", +}); +``` + +### Managing multiple email addresses + +Users can associate more than one email address with their account. Meteor stores them as an array in the user document, so you can add, remove, and verify each one independently. + +```js +// Add a new address for the user (server) +await Accounts.addEmailAsync(userId, "work@example.com"); + +// Remove an address (server) +Accounts.removeEmail(userId, "old@example.com"); + +// Send a verification email to a specific address (server) +Accounts.sendVerificationEmail(userId, "work@example.com"); +``` + +A common pattern is to record a "primary" email address — the one used for notifications and password resets — as a top-level field on the user document: + +```js +await Meteor.users.updateAsync(userId, { + $set: { primaryEmail: "work@example.com" }, +}); +``` ### Case sensitivity @@ -104,6 +113,80 @@ Meteor handles case sensitivity for email addresses and usernames. Since MongoDB Follow one rule: don't query the database by `username` or `email` directly. Instead, use the [`Accounts.findUserByUsername`](/api/accounts#Accounts-findUserByUsername) and [`Accounts.findUserByEmail`](/api/accounts#Accounts-findUserByEmail) methods provided by Meteor. This will run a query for you that is case-insensitive, so you will always find the user you are looking for. +### Security configuration + +`Accounts.config()` exposes several options that harden your login system. Call it once from server-side startup code. + +**Prevent user enumeration.** When enabled (the default in Meteor 3), "user not found" and "incorrect password" return the same error message to the caller, making it impossible for an attacker to discover which email addresses are registered: + +```js +Accounts.config({ ambiguousErrorMessages: true }); // default: true +``` + +**Block client-side account creation.** Ensure new accounts can only be created server-side (e.g. through a trusted Meteor Method), preventing unvetted signups from the browser console: + +```js +Accounts.config({ forbidClientAccountCreation: true }); +``` + +**Restrict signups by email domain.** Accept a string, an array of strings, or a function: + +```js +// single domain +Accounts.config({ restrictCreationByEmailDomain: "mycompany.com" }); + +// multiple domains +Accounts.config({ + restrictCreationByEmailDomain: ["mycompany.com", "contractor.io"], +}); + +// custom logic +Accounts.config({ + restrictCreationByEmailDomain: (email) => email.endsWith(".edu"), +}); +``` + +**Credential storage.** By default, login tokens are stored in `localStorage` and survive across browser sessions. Set `clientStorage` to `'session'` to clear credentials when the browser tab is closed: + +```js +Accounts.config({ clientStorage: "session" }); // 'local' (default) or 'session' +``` + +### Password hashing + +Meteor uses **bcrypt** to hash passwords by default. You can tune the work factor: + +```js +Accounts.config({ bcryptRounds: 12 }); // default: 10 +``` + +Meteor 3.x also supports **Argon2**, which is recommended by [OWASP](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) for new applications: + +```js +// server-side startup code +Accounts.config({ + argon2Enabled: true, + argon2Type: "argon2id", // 'argon2i' | 'argon2d' | 'argon2id' (default) + argon2TimeCost: 2, // iterations (default: 2) + argon2MemoryCost: 19456, // memory in KiB — 19 MB (default) + argon2Parallelism: 1, // threads (default: 1) +}); +``` + +Enabling Argon2 does not break existing users. Existing bcrypt hashes continue to work and are transparently re-hashed to Argon2 the next time each user logs in. + +### Token lifetime configuration + +You can control how long session and email tokens remain valid: + +```js +Accounts.config({ + loginExpirationInDays: 90, // session token lifetime (default: 90; set to null to never expire) + passwordResetTokenExpirationInDays: 3, // password reset link lifetime (default: 3 days) + passwordEnrollTokenExpirationInDays: 30, // account enrollment link lifetime (default: 30 days) +}); +``` + ### Email flows When you have a login system for your app based on user emails, that opens up the possibility for email-based account flows. The common thing between all of these workflows is that they involve sending a unique link to the user's email address, which does something special when it is clicked. Let's look at some common examples that Meteor's `accounts-password` package supports out of the box: @@ -116,38 +199,44 @@ When you have a login system for your app based on user emails, that opens up th `accounts-password` comes with handy functions that you can call from the server to send an email: -1. [`Accounts.sendResetPasswordEmail`](/api/accounts#Accounts-sendResetPasswordEmail) -2. [`Accounts.sendEnrollmentEmail`](/api/accounts#Accounts-sendEnrollmentEmail) -3. [`Accounts.sendVerificationEmail`](/api/accounts#Accounts-sendVerificationEmail) +1. [`Accounts.sendResetPasswordEmail(userId, email?, extraTokenData?, extraParams?)`](/api/accounts#Accounts-sendResetPasswordEmail) +2. [`Accounts.sendEnrollmentEmail(userId, email?, extraTokenData?, extraParams?)`](/api/accounts#Accounts-sendEnrollmentEmail) +3. [`Accounts.sendVerificationEmail(userId, email?, extraTokenData?, extraParams?)`](/api/accounts#Accounts-sendVerificationEmail) -The email is generated using the email templates from [`Accounts.emailTemplates`](/api/accounts#Accounts-emailTemplates), and include links generated with `Accounts.urls`. +The optional `extraTokenData` object is merged into the token stored in the database and is available inside email templates. The optional `extraParams` object is appended to the generated URL as query parameters. -#### Identifying when the link is clicked +If you need to generate a token without sending an email (for example, to build a custom mailer), use the lower-level helpers: -When the user receives the email and clicks the link inside, their web browser will take them to your app. Now, you need to be able to identify these special links and act appropriately. If you haven't customized the link URL, then you can use some built-in callbacks to identify when the app is in the middle of an email flow: +```js +// Generate a password reset token (server) +const { token } = Accounts.generateResetToken(userId, email, "resetPassword"); -1. [`Accounts.onResetPasswordLink`](/api/accounts#Accounts-onResetPasswordLink) -2. [`Accounts.onEnrollmentLink`](/api/accounts#Accounts-onEnrollmentLink) -3. [`Accounts.onEmailVerificationLink`](/api/accounts#Accounts-onEmailVerificationLink) +// Generate an email verification token (server) +const { token } = Accounts.generateVerificationToken(userId, email); +``` -Here's how you would use one of these functions: +The email is generated using the email templates from [`Accounts.emailTemplates`](/api/accounts#Accounts-emailTemplates), and includes links generated with `Accounts.urls`. + +#### Handling the link in your app + +When the user clicks the link in their email, their browser navigates to your app with the token embedded in the URL. Register a client-side callback to detect each flow and render the appropriate UI — there is one for each link type: `Accounts.onResetPasswordLink`, `Accounts.onEnrollmentLink`, and `Accounts.onEmailVerificationLink`. Here's how you would implement the password reset flow: ```js Accounts.onResetPasswordLink(async (token, done) => { // Display the password reset UI, get the new password... try { - await Accounts.resetPasswordAsync(token, newPassword); + await Accounts.resetPassword(token, newPassword); // Resume normal operation done(); } catch (err) { // Display error - console.error('Password reset failed:', err); + console.error("Password reset failed:", err); } }); ``` -If you want a different URL for your reset password page, you need to customize it using the `Accounts.urls` option: +If you want a different URL for your reset password page, you need to customize it using the `Accounts.urls` option. URL generators can also be `async` or return a `Promise`: ```js Accounts.urls.resetPassword = (token) => { @@ -159,10 +248,10 @@ If you have customized the URL, you will need to add a new route to your router #### Completing the process -When the user submits the form, you need to call the appropriate function to commit their change to the database: +When the user submits the form, you need to call the appropriate function to commit their change to the database. Both functions return a `Promise`: -1. [`Accounts.resetPasswordAsync`](/api/accounts#Accounts-resetPassword) - this one should be used both for resetting the password, and enrolling a new user; it accepts both kinds of tokens. -2. [`Accounts.verifyEmailAsync`](/api/accounts#Accounts-verifyEmail) +1. [`Accounts.resetPassword(token, newPassword)`](/api/accounts#Accounts-resetPassword) — use this both for resetting the password and enrolling a new user; it accepts both kinds of tokens. Logs in the user after a successful reset (unless 2FA is enabled — see [Two-Factor Authentication](#two-factor-authentication-accounts-2fa)). +2. [`Accounts.verifyEmail(token)`](/api/accounts#Accounts-verifyEmail) — logs in the user after a successful verification (unless 2FA is enabled). After you have called one of the two functions above or the user has cancelled the process, call the `done` function you got in the link callback. @@ -175,7 +264,7 @@ Accounts.emailTemplates.siteName = "Meteor Guide Todos Example"; Accounts.emailTemplates.from = "Meteor Todos Accounts "; Accounts.emailTemplates.resetPassword = { - subject(user) { + subject(user, url) { return "Reset your password on Meteor Todos"; }, text(user, url) { @@ -190,7 +279,7 @@ The Meteor Todos team html(user, url) { // This is where HTML email content would go. // See the section about html emails below. - } + }, }; ``` @@ -198,34 +287,192 @@ The Meteor Todos team If you've ever needed to deal with sending pretty HTML emails from an app, you know that it can quickly become a nightmare. Compatibility of popular email clients with basic HTML features like CSS is notoriously spotty. Start with a [responsive email template](https://github.com/leemunroe/responsive-html-email-template) or [framework](https://get.foundation/emails), and then use a tool to convert your email content into something that is compatible with all email clients. +## Passwordless login + +The `accounts-passwordless` package provides a one-time token (magic link) login experience — no password required. + +```bash +meteor add accounts-passwordless +``` + +### Requesting a login token + +On the client, call `Accounts.requestLoginTokenForUser` to send a one-time token to the user's email address: + +```js +// Client +await Accounts.requestLoginTokenForUser({ + selector: { email: "ada@lovelace.com" }, + // options.userCreationDisabled: true prevents creating a new account + // if no existing user matches the selector + options: {}, +}); +``` + +If no account exists for the given selector and `userCreationDisabled` is not set, you can pass `userData` to create the account on the fly: + +```js +await Accounts.requestLoginTokenForUser({ + selector: { email: "ada@lovelace.com" }, + userData: { email: "ada@lovelace.com", profile: { name: "Ada Lovelace" } }, +}); +``` + +### Logging in with the token + +When the user clicks the link in their email (or copies the token), call: + +```js +// Client +await Meteor.passwordlessLoginWithToken({ email: "ada@lovelace.com" }, token); +``` + +If the user has [Two-Factor Authentication](#two-factor-authentication-accounts-2fa) enabled, use the 2FA variant instead: + +```js +await Meteor.passwordlessLoginWithTokenAnd2faCode( + { email: "ada@lovelace.com" }, + token, + totpCode +); +``` + +### Automatic URL-based login + +Add `Accounts.autoLoginWithToken()` to your client startup code to detect when the URL contains a login token (e.g. from an email link) and log the user in automatically: + +```js +// client-side startup +Accounts.autoLoginWithToken(); +``` + +### Customizing the email + +Customize the token email through `Accounts.emailTemplates.sendLoginToken`: + +```js +Accounts.emailTemplates.sendLoginToken = { + subject(user) { + return "Your login link"; + }, + text(user, url) { + return `Click the link below to log in:\n\n${url}\n\nThis link expires in 15 minutes.`; + }, +}; +``` + +## Two-Factor Authentication + +The `accounts-2fa` package adds Time-based One-Time Password (TOTP) two-factor authentication, compatible with any standard authenticator app (Google Authenticator, Authy, etc.). + +```bash +meteor add accounts-2fa +``` + +### Enabling 2FA for a user + +The setup flow happens on the client: + +```js +// Step 1: generate a QR code and display it to the user +const { svg, secret, uri } = await new Promise((resolve, reject) => + Accounts.generate2faActivationQrCode("My App", (err, result) => { + if (err) reject(err); + else resolve(result); + }) +); +// Render `svg` in your UI so the user can scan it with their authenticator app + +// Step 2: once the user has scanned the QR code and sees the first code, confirm it +await new Promise((resolve, reject) => + Accounts.enableUser2fa(totpCode, (err) => { + if (err) reject(err); + else resolve(); + }) +); +``` + +### Disabling 2FA and checking status + +```js +// Check if the current user has 2FA enabled +const enabled = await new Promise((resolve, reject) => + Accounts.has2faEnabled((err, result) => { + if (err) reject(err); + else resolve(result); + }) +); + +// Disable 2FA for the current user +await new Promise((resolve, reject) => + Accounts.disableUser2fa((err) => { + if (err) reject(err); + else resolve(); + }) +); +``` + +### Logging in with 2FA + +When a user has 2FA enabled, the standard `Meteor.loginWithPassword` call will fail with an error prompting for a code. Use the dedicated method instead: + +```js +try { + await Meteor.loginWithPasswordAnd2faCode( + "ada@lovelace.com", + "mypassword", + totpCode + ); +} catch (err) { + console.error("Login failed:", err); +} +``` + +### Effect on password reset and email verification + +When 2FA is enabled, completing a password reset (`Accounts.resetPassword`) or email verification (`Accounts.verifyEmail`) will **not** automatically log the user in. The user must perform a full login (including the 2FA step) manually afterward. + +### Configuration + +```js +Accounts.config({ + loginTokenExpirationHours: 1, // how long a TOTP window stays valid (default: 1 hour) + tokenSequenceLength: 6, // TOTP code length (default: 6) +}); +``` + ## OAuth login Meteor supports popular login providers through OAuth out of the box. -### Facebook, Google, and more +### Adding an OAuth provider -Here's a complete list of login providers for which Meteor actively maintains core packages: +Meteor maintains packages for popular login providers. Add one or more to your app: -1. Facebook with `accounts-facebook` -2. Google with `accounts-google` -3. GitHub with `accounts-github` -4. Twitter with `accounts-twitter` -5. Meetup with `accounts-meetup` -6. Meteor Developer Accounts with `accounts-meteor-developer` +```bash +meteor add accounts-facebook # Facebook +meteor add accounts-google # Google +meteor add accounts-github # GitHub +meteor add accounts-twitter # Twitter +meteor add accounts-meetup # Meetup +meteor add accounts-meteor-developer # Meteor Developer Accounts +``` -### Logging in +Each package adds a `Meteor.loginWith` function and registers the service in the OAuth configuration UI. -If you are using an off-the-shelf login UI like `accounts-ui`, you don't need to write any code after adding the relevant package. If you are building a login experience from scratch, you can log in programmatically using the [`Meteor.loginWith`](/api/accounts#Meteor-loginWithExternalService) function: +### Logging in programmatically + +You can log in with any configured OAuth provider using the `Meteor.loginWith` function: ```js try { - await Meteor.loginWithFacebookAsync({ - requestPermissions: ['user_friends', 'public_profile', 'email'] + await Meteor.loginWithFacebook({ + requestPermissions: ["user_friends", "public_profile", "email"], }); // successful login! } catch (err) { // handle error - console.error('Login failed:', err); + console.error("Login failed:", err); } ``` @@ -234,9 +481,43 @@ try { There are a few points to know about configuring OAuth login: 1. **Client ID and secret.** It's best to keep your OAuth secret keys outside of your source code, and pass them in through Meteor.settings. Read how in the [Security article](/tutorials/security/security#api-keys). -2. **Redirect URL.** On the OAuth provider's side, you'll need to specify a *redirect URL*. The URL will look like: `https://www.example.com/_oauth/facebook`. Replace `facebook` with the name of the service you are using. Note that you will need to configure two URLs - one for your production app, and one for your development environment, where the URL might be something like `http://localhost:3000/_oauth/facebook`. +2. **Redirect URL.** On the OAuth provider's side, you'll need to specify a _redirect URL_. The URL will look like: `https://www.example.com/_oauth/facebook`. Replace `facebook` with the name of the service you are using. Note that you will need to configure two URLs - one for your production app, and one for your development environment, where the URL might be something like `http://localhost:3000/_oauth/facebook`. 3. **Permissions.** Each login service provider should have documentation about which permissions are available. If you want additional permissions to the user's data when they log in, pass some of these strings in the `requestPermissions` option. +### Server-side hooks for OAuth + +You can customize how OAuth accounts are created and updated on the server using these hooks. Each can only be registered once: + +```js +// Called before processing an external login. Return false to block the login. +Accounts.beforeExternalLogin((serviceName, serviceData, user) => { + // e.g. only allow logins from a specific GitHub org + if (serviceName === "github" && !serviceData.orgs?.includes("my-org")) { + return false; + } + return true; +}); + +// Provide additional lookup logic to find an existing user for an external login. +// Useful for linking accounts when the external service email matches an existing user. +Accounts.setAdditionalFindUserOnExternalLogin( + ({ serviceName, serviceData }) => { + if (serviceData.email) { + return Accounts.findUserByEmail(serviceData.email); + } + } +); + +// Called on every external login to update the user document. +// Return a modified user object to apply changes. +Accounts.onExternalLogin((options, user) => { + // Merge the latest profile data from the OAuth provider + user.profile = user.profile || {}; + user.profile.name = options.serviceData.name; + return user; +}); +``` + ### Calling service API for more data If your app supports or even requires login with an external service such as Facebook, it's natural to also want to use that service's API to request additional data about that user. @@ -273,39 +554,44 @@ On the server, each connection has a different logged in user, so there is no gl ```js // Accessing this.userId inside a publication -Meteor.publish('lists.private', function() { +Meteor.publish("lists.private", function () { if (!this.userId) { return this.ready(); } - return Lists.find({ - userId: this.userId - }, { - fields: Lists.publicFields - }); + return Lists.find( + { + userId: this.userId, + }, + { + fields: Lists.publicFields, + } + ); }); ``` ```js // Accessing this.userId inside a Method Meteor.methods({ - async 'todos.updateText'({ todoId, newText }) { + async "todos.updateText"({ todoId, newText }) { new SimpleSchema({ todoId: { type: String }, - newText: { type: String } + newText: { type: String }, }).validate({ todoId, newText }); const todo = await Todos.findOneAsync(todoId); if (!todo.editableBy(this.userId)) { - throw new Meteor.Error('todos.updateText.unauthorized', - 'Cannot edit todos in a private list that is not yours'); + throw new Meteor.Error( + "todos.updateText.unauthorized", + "Cannot edit todos in a private list that is not yours" + ); } await Todos.updateAsync(todoId, { - $set: { text: newText } + $set: { text: newText }, }); - } + }, }); ``` @@ -381,17 +667,17 @@ The best way to store your custom data onto the `Meteor.users` collection is to ```js // Using address schema from schema.org const newMailingAddress = { - addressCountry: 'US', - addressLocality: 'Seattle', - addressRegion: 'WA', - postalCode: '98052', - streetAddress: "20341 Whitworth Institute 405 N. Whitworth" + addressCountry: "US", + addressLocality: "Seattle", + addressRegion: "WA", + postalCode: "98052", + streetAddress: "20341 Whitworth Institute 405 N. Whitworth", }; await Meteor.users.updateAsync(userId, { $set: { - mailingAddress: newMailingAddress - } + mailingAddress: newMailingAddress, + }, }); ``` @@ -405,7 +691,7 @@ Sometimes, you want to set a field when the user first creates their account. Yo // Generate user initials after Facebook login Accounts.onCreateUser((options, user) => { if (!user.services.facebook) { - throw new Error('Expected login with Facebook only.'); + throw new Error("Expected login with Facebook only."); } const { first_name, last_name } = user.services.facebook; @@ -424,7 +710,7 @@ Accounts.onCreateUser((options, user) => { Note that the `user` object provided doesn't have an `_id` field yet. If you need to do something with the new user's ID inside this function, you can generate the ID yourself: ```js -import { Random } from 'meteor/random'; +import { Random } from "meteor/random"; // Generate a todo list for each new user Accounts.onCreateUser(async (options, user) => { @@ -450,7 +736,9 @@ Rather than dealing with the specifics of this field, it can be helpful to ignor ```js // Deny all client-side updates to user documents Meteor.users.deny({ - update() { return true; } + update() { + return true; + }, }); ``` @@ -459,21 +747,21 @@ Meteor.users.deny({ If you want to access the custom data you've added to the `Meteor.users` collection in your UI, you'll need to publish it to the client. The most important thing to keep in mind is that user documents contain private data about your users—hashed passwords and access keys for external APIs. This means it's critically important to filter the fields of the user document that you send to any client. ```js -Meteor.publish('Meteor.users.initials', function ({ userIds }) { +Meteor.publish("Meteor.users.initials", function ({ userIds }) { // Validate the arguments to be what we expect new SimpleSchema({ userIds: { type: Array }, - 'userIds.$': { type: String } + "userIds.$": { type: String }, }).validate({ userIds }); // Select only the users that match the array of IDs passed in const selector = { - _id: { $in: userIds } + _id: { $in: userIds }, }; // Only return one field, `initials` const options = { - fields: { initials: 1 } + fields: { initials: 1 }, }; return Meteor.users.find(selector, options); @@ -492,10 +780,14 @@ const user = await Meteor.userAsync({ fields: { "profile.name": 1 } }); const name = user?.profile?.name; // check if an email exists without fetching their entire document: -const userExists = !!await Accounts.findUserByEmail(email, { fields: { _id: 1 } }); +const userExists = !!(await Accounts.findUserByEmail(email, { + fields: { _id: 1 }, +})); // get the user id from a userName: -const user = await Accounts.findUserByUsername(userName, { fields: { _id: 1 } }); +const user = await Accounts.findUserByUsername(userName, { + fields: { _id: 1 }, +}); const userId = user?._id; ``` @@ -509,7 +801,7 @@ Accounts.config({ createdAt: 1, profile: 1, services: 1, - } + }, }); ``` @@ -521,21 +813,27 @@ Accounts.config({ defaultFieldSelector: { myBigArray: 0 } }); ## Roles and permissions -One of the main reasons you might want to add a login system to your app is to have permissions for your data. For example, if you were running a forum, you would want administrators or moderators to be able to delete any post, but normal users can only delete their own. This uncovers two different types of permissions: +Once users are logged in, you'll often want to control what each user can do. This uncovers two different types of permissions: 1. Role-based permissions 2. Per-document permissions -### alanning:roles +### roles -The most popular package for role-based permissions in Meteor is [`alanning:roles`](https://atmospherejs.com/alanning/roles). For example, here is how you would make a user into an administrator, or a moderator: +Meteor ships a core [`roles`](/packages/roles) package for role-based permissions. Add it to your app: + +```bash +meteor add roles +``` + +Here is how you would make a user into an administrator, or a moderator: ```js // Give Alice the 'admin' role -await Roles.addUsersToRolesAsync(aliceUserId, 'admin', Roles.GLOBAL_GROUP); +await Roles.addUsersToRolesAsync(aliceUserId, "admin", Roles.GLOBAL_GROUP); // Give Bob the 'moderator' role for a particular category -await Roles.addUsersToRolesAsync(bobsUserId, 'moderator', categoryId); +await Roles.addUsersToRolesAsync(bobsUserId, "moderator", categoryId); ``` Now, let's say you wanted to check if someone was allowed to delete a particular forum post: @@ -545,21 +843,21 @@ const forumPost = await Posts.findOneAsync(postId); const canDelete = await Roles.userIsInRoleAsync( userId, - ['admin', 'moderator'], + ["admin", "moderator"], forumPost.categoryId ); if (!canDelete) { - throw new Meteor.Error('unauthorized', - 'Only admins and moderators can delete posts.'); + throw new Meteor.Error( + "unauthorized", + "Only admins and moderators can delete posts." + ); } await Posts.removeAsync(postId); ``` -Note that we can check for multiple roles at once, and if someone has a role in the `GLOBAL_GROUP`, they are considered as having that role in every group. - -Read more in the [`alanning:roles` package documentation](https://atmospherejs.com/alanning/roles). +Note that you can check for multiple roles at once, and if someone has a role in `GLOBAL_GROUP`, they are considered as having that role in every group. ### Per-document permissions @@ -572,7 +870,7 @@ Lists.helpers({ return false; } return this.userId === userId; - } + }, }); ``` @@ -582,8 +880,10 @@ Now, we can call this simple function to determine if a particular user is allow const list = await Lists.findOneAsync(listId); if (!list.editableBy(userId)) { - throw new Meteor.Error('unauthorized', - 'Only list owners can edit private lists.'); + throw new Meteor.Error( + "unauthorized", + "Only list owners can edit private lists." + ); } ``` @@ -592,12 +892,15 @@ Learn more about how to use collection helpers in the [Collections article](/tut ## Best practices summary 1. **Use accounts-password** for email/password login and add OAuth packages as needed. -2. **Validate new users** with `Accounts.validateNewUser` to ensure required fields. -3. **Use case-insensitive queries** with `Accounts.findUserByEmail` and `Accounts.findUserByUsername`. -4. **Customize email templates** using `Accounts.emailTemplates` for professional communications. -5. **Never use the profile field** for sensitive data—deny client-side writes to user documents. -6. **Add custom data to top-level fields** on user documents, not nested in profile. -7. **Always filter fields** when publishing user data to clients. -8. **Use alanning:roles** for role-based access control. -9. **Use collection helpers** for per-document permissions. -10. **Configure defaultFieldSelector** to optimize user document fetching. +2. **Validate new users** with `Accounts.validateNewUser` to ensure required fields are present. +3. **Use `Accounts.createUserAsync`** (or `Accounts.createUserVerifyingEmail`) instead of the callback-based `createUser`. +4. **Use case-insensitive queries** with `Accounts.findUserByEmail` and `Accounts.findUserByUsername` — never query `Meteor.users` directly by email or username. +5. **Enable `ambiguousErrorMessages: true`** (the default) to prevent user enumeration attacks. +6. **Customize email templates** using `Accounts.emailTemplates` for professional-looking communications. +7. **Never use the profile field** for sensitive data — deny client-side writes with `Meteor.users.deny({ update() { return true; } })`. +8. **Add custom data to top-level fields** on user documents, not nested inside `profile`. +9. **Always filter fields** when publishing user data to clients — never expose password hashes or access tokens. +10. **Consider Argon2** for new applications by enabling `argon2Enabled: true` in `Accounts.config()`. +11. **Add 2FA** with `accounts-2fa` for applications with elevated security requirements. +12. **Use `accounts-passwordless`** to offer a frictionless, password-free login experience. +13. **Configure `defaultFieldSelector`** to avoid loading large user documents on every login. From 7981d7f26486eb8c233578a6c861cfea2f9b119c Mon Sep 17 00:00:00 2001 From: Gabriel Grubba Date: Mon, 30 Mar 2026 21:10:10 -0300 Subject: [PATCH 3/3] Revert "DOCS: revamp and update accounts tutorial" This reverts commit e02d65a09a6505170fdaf79afac62117fdc4fb53. --- v3-docs/docs/tutorials/accounts/accounts.md | 565 +++++--------------- 1 file changed, 131 insertions(+), 434 deletions(-) diff --git a/v3-docs/docs/tutorials/accounts/accounts.md b/v3-docs/docs/tutorials/accounts/accounts.md index 05d5329b07..8d5d3154c3 100644 --- a/v3-docs/docs/tutorials/accounts/accounts.md +++ b/v3-docs/docs/tutorials/accounts/accounts.md @@ -3,12 +3,11 @@ After reading this article, you'll know: 1. What features in core Meteor enable user accounts -2. How to build a fully-featured password login experience -3. How to set up passwordless login -4. How to add two-factor authentication (2FA) -5. How to enable login through OAuth providers like Facebook -6. How to add custom data to Meteor's users collection -7. How to protect your data with per-document permissions +2. How to use accounts-ui for a quick prototype +3. How to build a fully-featured password login experience +4. How to enable login through OAuth providers like Facebook +5. How to add custom data to Meteor's users collection +6. How to manage user roles and permissions ## Features in core Meteor @@ -24,13 +23,41 @@ This built-in feature means that you always get `this.userId` inside Methods and This package is the core of Meteor's developer-facing user accounts functionality. This includes: -1. A users collection with a standard schema, accessed through [`Meteor.users`](/api/accounts#Meteor-users), and the client-side singletons [`Meteor.userId()`](/api/accounts#Meteor-userId), [`Meteor.user()`](/api/accounts#Meteor-user), and the async [`Meteor.userAsync()`](/api/accounts#Meteor-userAsync), which represent the login state on the client. -2. Reactive helpers [`Accounts.loggingIn()`](/api/accounts#Accounts-loggingIn) and [`Accounts.loggingOut()`](/api/accounts#Accounts-loggingOut) to track in-progress login/logout state. -3. A variety of helpful other generic methods to keep track of login state, log out, validate users, etc. Visit the [Accounts section of the docs](/api/accounts) to find a complete list. -4. An API for registering new login handlers, which is used by all of the other accounts packages to integrate with the accounts system. +1. A users collection with a standard schema, accessed through [`Meteor.users`](/api/accounts#Meteor-users), and the client-side singletons [`Meteor.userId()`](/api/accounts#Meteor-userId) and [`Meteor.user()`](/api/accounts#Meteor-user), which represent the login state on the client. +2. A variety of helpful other generic methods to keep track of login state, log out, validate users, etc. Visit the [Accounts section of the docs](/api/accounts) to find a complete list. +3. An API for registering new login handlers, which is used by all of the other accounts packages to integrate with the accounts system. Usually, you don't need to include `accounts-base` yourself since it's added for you if you use `accounts-password` or similar, but it's good to be aware of what is what. +## Fast prototyping with accounts-ui + +Often, a complicated accounts system is not the first thing you want to build when you're starting out with a new app, so it's useful to have something you can drop in quickly. This is where `accounts-ui` comes in - it's one line that you drop into your app to get an accounts system. To add it: + +```bash +meteor add accounts-ui +``` + +Then include it anywhere in a Blaze template: + +```html +{{> loginButtons}} +``` + +Then, make sure to pick a login provider; they will automatically integrate with `accounts-ui`: + +```bash +# pick one or more of the below +meteor add accounts-password +meteor add accounts-facebook +meteor add accounts-google +meteor add accounts-github +meteor add accounts-twitter +meteor add accounts-meetup +meteor add accounts-meteor-developer +``` + +Now open your app, follow the configuration steps, and you're good to go - if you've done one of our [Meteor tutorials](/tutorials/react/1.creating-the-app), you've already seen this in action. Of course, in a production application, you probably want a more custom user interface and some logic to have a more tailored UX, but that's why we have the rest of these tutorials. + ## Password login Meteor comes with a secure and fully-featured password login system out of the box. To use it, add the package: @@ -39,9 +66,11 @@ Meteor comes with a secure and fully-featured password login system out of the b meteor add accounts-password ``` +To see what options are available to you, read the complete description of the [`accounts-password` API in the Meteor docs](/api/accounts). + ### Requiring username or email -By default, the `Accounts.createUserAsync` function provided by `accounts-password` allows you to create an account with a username, email, or both. Most apps expect a specific combination of the two, so you will certainly want to validate the new user creation: +By default, the `Accounts.createUser` function provided by `accounts-password` allows you to create an account with a username, email, or both. Most apps expect a specific combination of the two, so you will certainly want to validate the new user creation: ```js // Ensuring every user has an email address, should be in server-side code @@ -49,11 +78,11 @@ Accounts.validateNewUser((user) => { new SimpleSchema({ _id: { type: String }, emails: { type: Array }, - "emails.$": { type: Object }, - "emails.$.address": { type: String }, - "emails.$.verified": { type: Boolean }, + 'emails.$': { type: Object }, + 'emails.$.address': { type: String }, + 'emails.$.verified': { type: Boolean }, createdAt: { type: Date }, - services: { type: Object, blackbox: true }, + services: { type: Object, blackbox: true } }).validate(user); // Return true to allow user creation to proceed @@ -61,49 +90,11 @@ Accounts.validateNewUser((user) => { }); ``` -> When creating users programmatically, prefer the async variant: +### Multiple emails -```js -// Client or server -const userId = await Accounts.createUserAsync({ - username: "ada", - email: "ada@lovelace.com", - password: "secret", - profile: { name: "Ada Lovelace" }, -}); -``` +Often, users might want to associate multiple email addresses with the same account. `accounts-password` addresses this case by storing the email addresses as an array in the user collection. There are some handy API methods to deal with [adding](/api/accounts#Accounts-addEmail), [removing](/api/accounts#Accounts-removeEmail), and [verifying](/api/accounts#Accounts-verifyEmail) emails. -If you want to automatically send an email verification after account creation, use `Accounts.createUserVerifyingEmail` instead: - -```js -await Accounts.createUserVerifyingEmail({ - email: "ada@lovelace.com", - password: "secret", -}); -``` - -### Managing multiple email addresses - -Users can associate more than one email address with their account. Meteor stores them as an array in the user document, so you can add, remove, and verify each one independently. - -```js -// Add a new address for the user (server) -await Accounts.addEmailAsync(userId, "work@example.com"); - -// Remove an address (server) -Accounts.removeEmail(userId, "old@example.com"); - -// Send a verification email to a specific address (server) -Accounts.sendVerificationEmail(userId, "work@example.com"); -``` - -A common pattern is to record a "primary" email address — the one used for notifications and password resets — as a top-level field on the user document: - -```js -await Meteor.users.updateAsync(userId, { - $set: { primaryEmail: "work@example.com" }, -}); -``` +One useful thing to add for your app can be the concept of a "primary" email address. This way, if the user has added multiple emails, you know where to send confirmation emails and similar. ### Case sensitivity @@ -113,80 +104,6 @@ Meteor handles case sensitivity for email addresses and usernames. Since MongoDB Follow one rule: don't query the database by `username` or `email` directly. Instead, use the [`Accounts.findUserByUsername`](/api/accounts#Accounts-findUserByUsername) and [`Accounts.findUserByEmail`](/api/accounts#Accounts-findUserByEmail) methods provided by Meteor. This will run a query for you that is case-insensitive, so you will always find the user you are looking for. -### Security configuration - -`Accounts.config()` exposes several options that harden your login system. Call it once from server-side startup code. - -**Prevent user enumeration.** When enabled (the default in Meteor 3), "user not found" and "incorrect password" return the same error message to the caller, making it impossible for an attacker to discover which email addresses are registered: - -```js -Accounts.config({ ambiguousErrorMessages: true }); // default: true -``` - -**Block client-side account creation.** Ensure new accounts can only be created server-side (e.g. through a trusted Meteor Method), preventing unvetted signups from the browser console: - -```js -Accounts.config({ forbidClientAccountCreation: true }); -``` - -**Restrict signups by email domain.** Accept a string, an array of strings, or a function: - -```js -// single domain -Accounts.config({ restrictCreationByEmailDomain: "mycompany.com" }); - -// multiple domains -Accounts.config({ - restrictCreationByEmailDomain: ["mycompany.com", "contractor.io"], -}); - -// custom logic -Accounts.config({ - restrictCreationByEmailDomain: (email) => email.endsWith(".edu"), -}); -``` - -**Credential storage.** By default, login tokens are stored in `localStorage` and survive across browser sessions. Set `clientStorage` to `'session'` to clear credentials when the browser tab is closed: - -```js -Accounts.config({ clientStorage: "session" }); // 'local' (default) or 'session' -``` - -### Password hashing - -Meteor uses **bcrypt** to hash passwords by default. You can tune the work factor: - -```js -Accounts.config({ bcryptRounds: 12 }); // default: 10 -``` - -Meteor 3.x also supports **Argon2**, which is recommended by [OWASP](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) for new applications: - -```js -// server-side startup code -Accounts.config({ - argon2Enabled: true, - argon2Type: "argon2id", // 'argon2i' | 'argon2d' | 'argon2id' (default) - argon2TimeCost: 2, // iterations (default: 2) - argon2MemoryCost: 19456, // memory in KiB — 19 MB (default) - argon2Parallelism: 1, // threads (default: 1) -}); -``` - -Enabling Argon2 does not break existing users. Existing bcrypt hashes continue to work and are transparently re-hashed to Argon2 the next time each user logs in. - -### Token lifetime configuration - -You can control how long session and email tokens remain valid: - -```js -Accounts.config({ - loginExpirationInDays: 90, // session token lifetime (default: 90; set to null to never expire) - passwordResetTokenExpirationInDays: 3, // password reset link lifetime (default: 3 days) - passwordEnrollTokenExpirationInDays: 30, // account enrollment link lifetime (default: 30 days) -}); -``` - ### Email flows When you have a login system for your app based on user emails, that opens up the possibility for email-based account flows. The common thing between all of these workflows is that they involve sending a unique link to the user's email address, which does something special when it is clicked. Let's look at some common examples that Meteor's `accounts-password` package supports out of the box: @@ -199,44 +116,38 @@ When you have a login system for your app based on user emails, that opens up th `accounts-password` comes with handy functions that you can call from the server to send an email: -1. [`Accounts.sendResetPasswordEmail(userId, email?, extraTokenData?, extraParams?)`](/api/accounts#Accounts-sendResetPasswordEmail) -2. [`Accounts.sendEnrollmentEmail(userId, email?, extraTokenData?, extraParams?)`](/api/accounts#Accounts-sendEnrollmentEmail) -3. [`Accounts.sendVerificationEmail(userId, email?, extraTokenData?, extraParams?)`](/api/accounts#Accounts-sendVerificationEmail) +1. [`Accounts.sendResetPasswordEmail`](/api/accounts#Accounts-sendResetPasswordEmail) +2. [`Accounts.sendEnrollmentEmail`](/api/accounts#Accounts-sendEnrollmentEmail) +3. [`Accounts.sendVerificationEmail`](/api/accounts#Accounts-sendVerificationEmail) -The optional `extraTokenData` object is merged into the token stored in the database and is available inside email templates. The optional `extraParams` object is appended to the generated URL as query parameters. +The email is generated using the email templates from [`Accounts.emailTemplates`](/api/accounts#Accounts-emailTemplates), and include links generated with `Accounts.urls`. -If you need to generate a token without sending an email (for example, to build a custom mailer), use the lower-level helpers: +#### Identifying when the link is clicked -```js -// Generate a password reset token (server) -const { token } = Accounts.generateResetToken(userId, email, "resetPassword"); +When the user receives the email and clicks the link inside, their web browser will take them to your app. Now, you need to be able to identify these special links and act appropriately. If you haven't customized the link URL, then you can use some built-in callbacks to identify when the app is in the middle of an email flow: -// Generate an email verification token (server) -const { token } = Accounts.generateVerificationToken(userId, email); -``` +1. [`Accounts.onResetPasswordLink`](/api/accounts#Accounts-onResetPasswordLink) +2. [`Accounts.onEnrollmentLink`](/api/accounts#Accounts-onEnrollmentLink) +3. [`Accounts.onEmailVerificationLink`](/api/accounts#Accounts-onEmailVerificationLink) -The email is generated using the email templates from [`Accounts.emailTemplates`](/api/accounts#Accounts-emailTemplates), and includes links generated with `Accounts.urls`. - -#### Handling the link in your app - -When the user clicks the link in their email, their browser navigates to your app with the token embedded in the URL. Register a client-side callback to detect each flow and render the appropriate UI — there is one for each link type: `Accounts.onResetPasswordLink`, `Accounts.onEnrollmentLink`, and `Accounts.onEmailVerificationLink`. Here's how you would implement the password reset flow: +Here's how you would use one of these functions: ```js Accounts.onResetPasswordLink(async (token, done) => { // Display the password reset UI, get the new password... try { - await Accounts.resetPassword(token, newPassword); + await Accounts.resetPasswordAsync(token, newPassword); // Resume normal operation done(); } catch (err) { // Display error - console.error("Password reset failed:", err); + console.error('Password reset failed:', err); } }); ``` -If you want a different URL for your reset password page, you need to customize it using the `Accounts.urls` option. URL generators can also be `async` or return a `Promise`: +If you want a different URL for your reset password page, you need to customize it using the `Accounts.urls` option: ```js Accounts.urls.resetPassword = (token) => { @@ -248,10 +159,10 @@ If you have customized the URL, you will need to add a new route to your router #### Completing the process -When the user submits the form, you need to call the appropriate function to commit their change to the database. Both functions return a `Promise`: +When the user submits the form, you need to call the appropriate function to commit their change to the database: -1. [`Accounts.resetPassword(token, newPassword)`](/api/accounts#Accounts-resetPassword) — use this both for resetting the password and enrolling a new user; it accepts both kinds of tokens. Logs in the user after a successful reset (unless 2FA is enabled — see [Two-Factor Authentication](#two-factor-authentication-accounts-2fa)). -2. [`Accounts.verifyEmail(token)`](/api/accounts#Accounts-verifyEmail) — logs in the user after a successful verification (unless 2FA is enabled). +1. [`Accounts.resetPasswordAsync`](/api/accounts#Accounts-resetPassword) - this one should be used both for resetting the password, and enrolling a new user; it accepts both kinds of tokens. +2. [`Accounts.verifyEmailAsync`](/api/accounts#Accounts-verifyEmail) After you have called one of the two functions above or the user has cancelled the process, call the `done` function you got in the link callback. @@ -264,7 +175,7 @@ Accounts.emailTemplates.siteName = "Meteor Guide Todos Example"; Accounts.emailTemplates.from = "Meteor Todos Accounts "; Accounts.emailTemplates.resetPassword = { - subject(user, url) { + subject(user) { return "Reset your password on Meteor Todos"; }, text(user, url) { @@ -279,7 +190,7 @@ The Meteor Todos team html(user, url) { // This is where HTML email content would go. // See the section about html emails below. - }, + } }; ``` @@ -287,192 +198,34 @@ The Meteor Todos team If you've ever needed to deal with sending pretty HTML emails from an app, you know that it can quickly become a nightmare. Compatibility of popular email clients with basic HTML features like CSS is notoriously spotty. Start with a [responsive email template](https://github.com/leemunroe/responsive-html-email-template) or [framework](https://get.foundation/emails), and then use a tool to convert your email content into something that is compatible with all email clients. -## Passwordless login - -The `accounts-passwordless` package provides a one-time token (magic link) login experience — no password required. - -```bash -meteor add accounts-passwordless -``` - -### Requesting a login token - -On the client, call `Accounts.requestLoginTokenForUser` to send a one-time token to the user's email address: - -```js -// Client -await Accounts.requestLoginTokenForUser({ - selector: { email: "ada@lovelace.com" }, - // options.userCreationDisabled: true prevents creating a new account - // if no existing user matches the selector - options: {}, -}); -``` - -If no account exists for the given selector and `userCreationDisabled` is not set, you can pass `userData` to create the account on the fly: - -```js -await Accounts.requestLoginTokenForUser({ - selector: { email: "ada@lovelace.com" }, - userData: { email: "ada@lovelace.com", profile: { name: "Ada Lovelace" } }, -}); -``` - -### Logging in with the token - -When the user clicks the link in their email (or copies the token), call: - -```js -// Client -await Meteor.passwordlessLoginWithToken({ email: "ada@lovelace.com" }, token); -``` - -If the user has [Two-Factor Authentication](#two-factor-authentication-accounts-2fa) enabled, use the 2FA variant instead: - -```js -await Meteor.passwordlessLoginWithTokenAnd2faCode( - { email: "ada@lovelace.com" }, - token, - totpCode -); -``` - -### Automatic URL-based login - -Add `Accounts.autoLoginWithToken()` to your client startup code to detect when the URL contains a login token (e.g. from an email link) and log the user in automatically: - -```js -// client-side startup -Accounts.autoLoginWithToken(); -``` - -### Customizing the email - -Customize the token email through `Accounts.emailTemplates.sendLoginToken`: - -```js -Accounts.emailTemplates.sendLoginToken = { - subject(user) { - return "Your login link"; - }, - text(user, url) { - return `Click the link below to log in:\n\n${url}\n\nThis link expires in 15 minutes.`; - }, -}; -``` - -## Two-Factor Authentication - -The `accounts-2fa` package adds Time-based One-Time Password (TOTP) two-factor authentication, compatible with any standard authenticator app (Google Authenticator, Authy, etc.). - -```bash -meteor add accounts-2fa -``` - -### Enabling 2FA for a user - -The setup flow happens on the client: - -```js -// Step 1: generate a QR code and display it to the user -const { svg, secret, uri } = await new Promise((resolve, reject) => - Accounts.generate2faActivationQrCode("My App", (err, result) => { - if (err) reject(err); - else resolve(result); - }) -); -// Render `svg` in your UI so the user can scan it with their authenticator app - -// Step 2: once the user has scanned the QR code and sees the first code, confirm it -await new Promise((resolve, reject) => - Accounts.enableUser2fa(totpCode, (err) => { - if (err) reject(err); - else resolve(); - }) -); -``` - -### Disabling 2FA and checking status - -```js -// Check if the current user has 2FA enabled -const enabled = await new Promise((resolve, reject) => - Accounts.has2faEnabled((err, result) => { - if (err) reject(err); - else resolve(result); - }) -); - -// Disable 2FA for the current user -await new Promise((resolve, reject) => - Accounts.disableUser2fa((err) => { - if (err) reject(err); - else resolve(); - }) -); -``` - -### Logging in with 2FA - -When a user has 2FA enabled, the standard `Meteor.loginWithPassword` call will fail with an error prompting for a code. Use the dedicated method instead: - -```js -try { - await Meteor.loginWithPasswordAnd2faCode( - "ada@lovelace.com", - "mypassword", - totpCode - ); -} catch (err) { - console.error("Login failed:", err); -} -``` - -### Effect on password reset and email verification - -When 2FA is enabled, completing a password reset (`Accounts.resetPassword`) or email verification (`Accounts.verifyEmail`) will **not** automatically log the user in. The user must perform a full login (including the 2FA step) manually afterward. - -### Configuration - -```js -Accounts.config({ - loginTokenExpirationHours: 1, // how long a TOTP window stays valid (default: 1 hour) - tokenSequenceLength: 6, // TOTP code length (default: 6) -}); -``` - ## OAuth login Meteor supports popular login providers through OAuth out of the box. -### Adding an OAuth provider +### Facebook, Google, and more -Meteor maintains packages for popular login providers. Add one or more to your app: +Here's a complete list of login providers for which Meteor actively maintains core packages: -```bash -meteor add accounts-facebook # Facebook -meteor add accounts-google # Google -meteor add accounts-github # GitHub -meteor add accounts-twitter # Twitter -meteor add accounts-meetup # Meetup -meteor add accounts-meteor-developer # Meteor Developer Accounts -``` +1. Facebook with `accounts-facebook` +2. Google with `accounts-google` +3. GitHub with `accounts-github` +4. Twitter with `accounts-twitter` +5. Meetup with `accounts-meetup` +6. Meteor Developer Accounts with `accounts-meteor-developer` -Each package adds a `Meteor.loginWith` function and registers the service in the OAuth configuration UI. +### Logging in -### Logging in programmatically - -You can log in with any configured OAuth provider using the `Meteor.loginWith` function: +If you are using an off-the-shelf login UI like `accounts-ui`, you don't need to write any code after adding the relevant package. If you are building a login experience from scratch, you can log in programmatically using the [`Meteor.loginWith`](/api/accounts#Meteor-loginWithExternalService) function: ```js try { - await Meteor.loginWithFacebook({ - requestPermissions: ["user_friends", "public_profile", "email"], + await Meteor.loginWithFacebookAsync({ + requestPermissions: ['user_friends', 'public_profile', 'email'] }); // successful login! } catch (err) { // handle error - console.error("Login failed:", err); + console.error('Login failed:', err); } ``` @@ -481,43 +234,9 @@ try { There are a few points to know about configuring OAuth login: 1. **Client ID and secret.** It's best to keep your OAuth secret keys outside of your source code, and pass them in through Meteor.settings. Read how in the [Security article](/tutorials/security/security#api-keys). -2. **Redirect URL.** On the OAuth provider's side, you'll need to specify a _redirect URL_. The URL will look like: `https://www.example.com/_oauth/facebook`. Replace `facebook` with the name of the service you are using. Note that you will need to configure two URLs - one for your production app, and one for your development environment, where the URL might be something like `http://localhost:3000/_oauth/facebook`. +2. **Redirect URL.** On the OAuth provider's side, you'll need to specify a *redirect URL*. The URL will look like: `https://www.example.com/_oauth/facebook`. Replace `facebook` with the name of the service you are using. Note that you will need to configure two URLs - one for your production app, and one for your development environment, where the URL might be something like `http://localhost:3000/_oauth/facebook`. 3. **Permissions.** Each login service provider should have documentation about which permissions are available. If you want additional permissions to the user's data when they log in, pass some of these strings in the `requestPermissions` option. -### Server-side hooks for OAuth - -You can customize how OAuth accounts are created and updated on the server using these hooks. Each can only be registered once: - -```js -// Called before processing an external login. Return false to block the login. -Accounts.beforeExternalLogin((serviceName, serviceData, user) => { - // e.g. only allow logins from a specific GitHub org - if (serviceName === "github" && !serviceData.orgs?.includes("my-org")) { - return false; - } - return true; -}); - -// Provide additional lookup logic to find an existing user for an external login. -// Useful for linking accounts when the external service email matches an existing user. -Accounts.setAdditionalFindUserOnExternalLogin( - ({ serviceName, serviceData }) => { - if (serviceData.email) { - return Accounts.findUserByEmail(serviceData.email); - } - } -); - -// Called on every external login to update the user document. -// Return a modified user object to apply changes. -Accounts.onExternalLogin((options, user) => { - // Merge the latest profile data from the OAuth provider - user.profile = user.profile || {}; - user.profile.name = options.serviceData.name; - return user; -}); -``` - ### Calling service API for more data If your app supports or even requires login with an external service such as Facebook, it's natural to also want to use that service's API to request additional data about that user. @@ -554,44 +273,39 @@ On the server, each connection has a different logged in user, so there is no gl ```js // Accessing this.userId inside a publication -Meteor.publish("lists.private", function () { +Meteor.publish('lists.private', function() { if (!this.userId) { return this.ready(); } - return Lists.find( - { - userId: this.userId, - }, - { - fields: Lists.publicFields, - } - ); + return Lists.find({ + userId: this.userId + }, { + fields: Lists.publicFields + }); }); ``` ```js // Accessing this.userId inside a Method Meteor.methods({ - async "todos.updateText"({ todoId, newText }) { + async 'todos.updateText'({ todoId, newText }) { new SimpleSchema({ todoId: { type: String }, - newText: { type: String }, + newText: { type: String } }).validate({ todoId, newText }); const todo = await Todos.findOneAsync(todoId); if (!todo.editableBy(this.userId)) { - throw new Meteor.Error( - "todos.updateText.unauthorized", - "Cannot edit todos in a private list that is not yours" - ); + throw new Meteor.Error('todos.updateText.unauthorized', + 'Cannot edit todos in a private list that is not yours'); } await Todos.updateAsync(todoId, { - $set: { text: newText }, + $set: { text: newText } }); - }, + } }); ``` @@ -667,17 +381,17 @@ The best way to store your custom data onto the `Meteor.users` collection is to ```js // Using address schema from schema.org const newMailingAddress = { - addressCountry: "US", - addressLocality: "Seattle", - addressRegion: "WA", - postalCode: "98052", - streetAddress: "20341 Whitworth Institute 405 N. Whitworth", + addressCountry: 'US', + addressLocality: 'Seattle', + addressRegion: 'WA', + postalCode: '98052', + streetAddress: "20341 Whitworth Institute 405 N. Whitworth" }; await Meteor.users.updateAsync(userId, { $set: { - mailingAddress: newMailingAddress, - }, + mailingAddress: newMailingAddress + } }); ``` @@ -691,7 +405,7 @@ Sometimes, you want to set a field when the user first creates their account. Yo // Generate user initials after Facebook login Accounts.onCreateUser((options, user) => { if (!user.services.facebook) { - throw new Error("Expected login with Facebook only."); + throw new Error('Expected login with Facebook only.'); } const { first_name, last_name } = user.services.facebook; @@ -710,7 +424,7 @@ Accounts.onCreateUser((options, user) => { Note that the `user` object provided doesn't have an `_id` field yet. If you need to do something with the new user's ID inside this function, you can generate the ID yourself: ```js -import { Random } from "meteor/random"; +import { Random } from 'meteor/random'; // Generate a todo list for each new user Accounts.onCreateUser(async (options, user) => { @@ -736,9 +450,7 @@ Rather than dealing with the specifics of this field, it can be helpful to ignor ```js // Deny all client-side updates to user documents Meteor.users.deny({ - update() { - return true; - }, + update() { return true; } }); ``` @@ -747,21 +459,21 @@ Meteor.users.deny({ If you want to access the custom data you've added to the `Meteor.users` collection in your UI, you'll need to publish it to the client. The most important thing to keep in mind is that user documents contain private data about your users—hashed passwords and access keys for external APIs. This means it's critically important to filter the fields of the user document that you send to any client. ```js -Meteor.publish("Meteor.users.initials", function ({ userIds }) { +Meteor.publish('Meteor.users.initials', function ({ userIds }) { // Validate the arguments to be what we expect new SimpleSchema({ userIds: { type: Array }, - "userIds.$": { type: String }, + 'userIds.$': { type: String } }).validate({ userIds }); // Select only the users that match the array of IDs passed in const selector = { - _id: { $in: userIds }, + _id: { $in: userIds } }; // Only return one field, `initials` const options = { - fields: { initials: 1 }, + fields: { initials: 1 } }; return Meteor.users.find(selector, options); @@ -780,14 +492,10 @@ const user = await Meteor.userAsync({ fields: { "profile.name": 1 } }); const name = user?.profile?.name; // check if an email exists without fetching their entire document: -const userExists = !!(await Accounts.findUserByEmail(email, { - fields: { _id: 1 }, -})); +const userExists = !!await Accounts.findUserByEmail(email, { fields: { _id: 1 } }); // get the user id from a userName: -const user = await Accounts.findUserByUsername(userName, { - fields: { _id: 1 }, -}); +const user = await Accounts.findUserByUsername(userName, { fields: { _id: 1 } }); const userId = user?._id; ``` @@ -801,7 +509,7 @@ Accounts.config({ createdAt: 1, profile: 1, services: 1, - }, + } }); ``` @@ -813,27 +521,21 @@ Accounts.config({ defaultFieldSelector: { myBigArray: 0 } }); ## Roles and permissions -Once users are logged in, you'll often want to control what each user can do. This uncovers two different types of permissions: +One of the main reasons you might want to add a login system to your app is to have permissions for your data. For example, if you were running a forum, you would want administrators or moderators to be able to delete any post, but normal users can only delete their own. This uncovers two different types of permissions: 1. Role-based permissions 2. Per-document permissions -### roles +### alanning:roles -Meteor ships a core [`roles`](/packages/roles) package for role-based permissions. Add it to your app: - -```bash -meteor add roles -``` - -Here is how you would make a user into an administrator, or a moderator: +The most popular package for role-based permissions in Meteor is [`alanning:roles`](https://atmospherejs.com/alanning/roles). For example, here is how you would make a user into an administrator, or a moderator: ```js // Give Alice the 'admin' role -await Roles.addUsersToRolesAsync(aliceUserId, "admin", Roles.GLOBAL_GROUP); +await Roles.addUsersToRolesAsync(aliceUserId, 'admin', Roles.GLOBAL_GROUP); // Give Bob the 'moderator' role for a particular category -await Roles.addUsersToRolesAsync(bobsUserId, "moderator", categoryId); +await Roles.addUsersToRolesAsync(bobsUserId, 'moderator', categoryId); ``` Now, let's say you wanted to check if someone was allowed to delete a particular forum post: @@ -843,21 +545,21 @@ const forumPost = await Posts.findOneAsync(postId); const canDelete = await Roles.userIsInRoleAsync( userId, - ["admin", "moderator"], + ['admin', 'moderator'], forumPost.categoryId ); if (!canDelete) { - throw new Meteor.Error( - "unauthorized", - "Only admins and moderators can delete posts." - ); + throw new Meteor.Error('unauthorized', + 'Only admins and moderators can delete posts.'); } await Posts.removeAsync(postId); ``` -Note that you can check for multiple roles at once, and if someone has a role in `GLOBAL_GROUP`, they are considered as having that role in every group. +Note that we can check for multiple roles at once, and if someone has a role in the `GLOBAL_GROUP`, they are considered as having that role in every group. + +Read more in the [`alanning:roles` package documentation](https://atmospherejs.com/alanning/roles). ### Per-document permissions @@ -870,7 +572,7 @@ Lists.helpers({ return false; } return this.userId === userId; - }, + } }); ``` @@ -880,10 +582,8 @@ Now, we can call this simple function to determine if a particular user is allow const list = await Lists.findOneAsync(listId); if (!list.editableBy(userId)) { - throw new Meteor.Error( - "unauthorized", - "Only list owners can edit private lists." - ); + throw new Meteor.Error('unauthorized', + 'Only list owners can edit private lists.'); } ``` @@ -892,15 +592,12 @@ Learn more about how to use collection helpers in the [Collections article](/tut ## Best practices summary 1. **Use accounts-password** for email/password login and add OAuth packages as needed. -2. **Validate new users** with `Accounts.validateNewUser` to ensure required fields are present. -3. **Use `Accounts.createUserAsync`** (or `Accounts.createUserVerifyingEmail`) instead of the callback-based `createUser`. -4. **Use case-insensitive queries** with `Accounts.findUserByEmail` and `Accounts.findUserByUsername` — never query `Meteor.users` directly by email or username. -5. **Enable `ambiguousErrorMessages: true`** (the default) to prevent user enumeration attacks. -6. **Customize email templates** using `Accounts.emailTemplates` for professional-looking communications. -7. **Never use the profile field** for sensitive data — deny client-side writes with `Meteor.users.deny({ update() { return true; } })`. -8. **Add custom data to top-level fields** on user documents, not nested inside `profile`. -9. **Always filter fields** when publishing user data to clients — never expose password hashes or access tokens. -10. **Consider Argon2** for new applications by enabling `argon2Enabled: true` in `Accounts.config()`. -11. **Add 2FA** with `accounts-2fa` for applications with elevated security requirements. -12. **Use `accounts-passwordless`** to offer a frictionless, password-free login experience. -13. **Configure `defaultFieldSelector`** to avoid loading large user documents on every login. +2. **Validate new users** with `Accounts.validateNewUser` to ensure required fields. +3. **Use case-insensitive queries** with `Accounts.findUserByEmail` and `Accounts.findUserByUsername`. +4. **Customize email templates** using `Accounts.emailTemplates` for professional communications. +5. **Never use the profile field** for sensitive data—deny client-side writes to user documents. +6. **Add custom data to top-level fields** on user documents, not nested in profile. +7. **Always filter fields** when publishing user data to clients. +8. **Use alanning:roles** for role-based access control. +9. **Use collection helpers** for per-document permissions. +10. **Configure defaultFieldSelector** to optimize user document fetching.