Authentication User Flow

Learn how to implement authentication and authorization in MeteorJS.

Log in user

Meteor logs a user in to the system by checking the combination of the username or email of the user with the password. When a successful login occurs, Meteor stores the login token, token expiration date, and userId in the localStorage browser with the respective Meteor.loginToken, Meteor.loginTokenExpires, and Meteor.userId keys. The storage of these values ensures that a user is always logged in to the system as they navigate the application.

The imports/ui/Login.jsx file uses the AuthContext to set the auth state of the application. The loginUser function defined on lines 12–25 is called when the “login” button is clicked. The loginUser function reads the state of the username and password, which is then passed to Meteor.loginWithPassword. Upon successful login, the first parameter of the callback function is null. If it fails, it holds the error object from which the reason for the failure can be extracted.

Log out user

The logout function logs the user out of the system. The browser’s local storage is also cleared of the values that were initially set by Meteor when the user logs in to the system. The auth state from the AuthContext is also set to false upon successful logout.

Authenticated user

When a user logs in, the user becomes authenticated, and their privilege to use the system is elevated based on the business rules set by the developer. The imports/ui/Authenticated.js file displays the details of an authenticated user. It receives the user object and the roles attached to the user. These props are passed from the parent App.jsx component, and, as we know, props can only be passed from a parent component to a child component.

On line 4 in Authenticated.jsx, we destructure the user object. A check is performed by using the JavaScript || operator, which is a logical OR operator that returns the first truthy value between two values. In our case, on line 4, if a user is truthy, it destructures the value of username, profile, and email from the user. If not, it returns an empty object.

We loop over the roles prop using the map function on line 16 and return a paragraph for each role element, which is rendered by React. React uses the key prop, which must be unique to accurately identify rendered elements on the page.

Task

The Meteor.loginWithPassword accepts either a username or email for the login. The bookshop application currently uses username for the login. Can you modify Login.jsx to accept a login in with either email or username?

Get hands-on with 1400+ tech skills courses.