Meteor Authentication System
Explore how to set up and manage user authentication in Meteor.js applications. Learn to create accounts, handle login and logout, and use React's context API for maintaining authentication state across the app. This lesson guides you through adding Meteor's accounts-password package and integrating secure user management in your full-stack project.
We'll cover the following...
Meteor authentication
Authentication is a means of identifying an application’s users before granting access to web resources. Meteor provides a built-in way to add user functionality without having to write an authentication system ourselves. The basic workflow of a web application provides a mechanism for users to log in and register accounts.
Not every application needs authentication, so the user authentication functionality isn’t available by default in created projects. We need to install the account functionality through the terminal. We’ll create a little app, install the Meteor account package, and get familiar with the package before installing it to the online bookshop application that we’re building throughout this chapter.
We’ll install a login provider on the terminal by typing meteor add accounts-password. Meteor creates a users collection in MongoDB after the installation of the accounts-password package. This collection is used for the management of users’ accounts.
The coding playground at the end of this lesson implements authentication in a MeteorJS application. We have a Meteor Method called createAccount inside the imports/api/methods.js file. On line 2, we import Accounts from meteor/accounts-base. This package was added to the project when we installed the accounts-password package.
The createAccount method is called from the client. On line 6, we destructure the user object that’s passed to the function to get the username and password passed from the client. On line 7, a check is performed to determine if a user with the username exists by calling Accounts.findUserByUsername. If no user already exists with the passed username, a new user account is created by calling Accounts.createUser() with the user details. The Accounts.createUser method logs the user in automatically upon successful account creation if called on the client. If it’s called on the server, it returns the _id of the newly-created user back to the client.
Creating a user account
Open the imports/ui/Login.jsx file. Inside the file, there are input textboxes used to allow the user to enter the username and password. The state of the text input is captured by the useState React hook defined and attached to the input textbox on lines 6–7. On lines 32–49, we define a function called registerAccount. This function is passed to the “Register Account” button on line 98. On line 39, the createAccount method is called and executed, and a message is displayed that says the account has been successfully created.
Meteor user login
Open the imports/ui/Login.jsx file. A user logs in to the system by entering a username and password into the input textboxes on lines 112–126. The value entered in the input textbox is saved in state using the useState declared on lines 8–9. The function to log the user into the system is defined in lines 51–65.
The login function checks if the username and password were entered into the textbox by checking the state of the input textbox. If that check clears, a call is made to Meteor.loginWithPassword with the entered value for the username and password. The Meteor.loginWithPassword function is used to log an account into the system.
The Meteor.loginWithPassword function checks for the correctness of the entered username and password. If it’s correct, a callback function is returned with null as the first parameter. If there’s an error, the first parameter of the callback function contains the error object along with its details.
Using Auth context
Upon successful login, we need to store the login state of the application in a variable. This is a perfect case for the use of the context API by React.
Open the imports/context/AuthContext.jsx file. Inside the file, we create a React context on line 3. We then create an AuthProvider that will be used to wrap the component that consumes the context. We’ll want to place this component very high up the component tree because the authenticated state of the application should be accessed by all components in the application.
Open the client/main.jsx file. On line 5, we import the AuthProvider from the AuthContext.jsx file. This component is used to wrap the App component so that all components inside can use the AuthContext
Inside the AuthProvider component in imports/context/AuthContext.jsx on line 6, we define a state named auth, and the function that changes the value of auth known as setAuth. The initial value of the auth state is false. Upon successful login, the state changes using the setAuth function. The AuthProvider function returns a Provider component with the auth state value and the function used to change the auth state.
The useAuth function retrieves the value of the context from the AuthProvider. The function throws an error if we can’t find a context object. At the end of the imports/context/AuthContext.jsx file, the AuthProvider and useAuth function are exported.
When we successfully log in, we set the auth state to true by calling the setAuth function on line 61 inside the imports/ui/Login.jsx file. We also clear the respective state of the input textboxes.
Meteor user logout
Logging out of the system is as simple as calling Meteor.logout(). This is defined on lines 67–71 of the logout function. We set the auth state to false inside the callback function of Meteor.logout
Task
Click the “Run” button to experiment with the application. Create an account and try logging in with an incorrect password. Then, try logging in with the correct password.
# This file contains information which helps Meteor properly upgrade your # app when you run 'meteor update'. You should check it into version control # with your project. notices-for-0.9.0 notices-for-0.9.1 0.9.4-platform-file notices-for-facebook-graph-api-2 1.2.0-standard-minifiers-package 1.2.0-meteor-platform-split 1.2.0-cordova-changes 1.2.0-breaking-changes 1.3.0-split-minifiers-package 1.4.0-remove-old-dev-bundle-link 1.4.1-add-shell-server-package 1.4.3-split-account-service-packages 1.5-add-dynamic-import-package 1.7-split-underscore-from-meteor-base 1.8.3-split-jquery-from-blaze