# Handling User Authentication With the MEAN Stack

This post provides a solution to the question, “How do I handle user authentication with the MEAN Stack - MongoDB, ExpressJS, AngularJS, and NodeJS?”.

Much of this post is ported from Handling User Authentication with Angular and Flask from Real Python.

Keep in mind that this solution posed in this tutorial is not the only solution to the question at hand, and it may not even be the right solution for your situation. Regardless of the solution you implement, it is important to note that since end users have full control of the browser as well as access to the front-end code, sensitive data living in your server-side API must be secure. In other words, make certain that you implement an authentication strategy on the server-side to protect sensitive API endpoints.

That said, we need to enable the following workflow:

1. When the client accesses the main route, an index page is served, at which point Angular takes over.
2. The Angular app immediately “asks” the server if a user is logged in.
3. Assuming the server indicates that a user is not logged in, the client is immediately asked to log in.
4. Once logged in, the Angular app then tracks the user’s login status.

This tutorial uses NodeJS v4.3.1, ExpressJS v4.13.4, MongoDB v3.2.3, and AngularJS v1.4.9. For a full list of dependencies, please view the package.json file.

## Getting Started

First, grab the boilerplate code from the project repo, install the requirements, and then test out the app:

Navigate to http://localhost:3000/ and you should see a simple welcome message - “Yo!”. Once you’re finished admiring the page, kill the server, and glance over the code within the project folder:

Nothing too spectacular. You can see that the back-end code resides in the “server” folder, while the front-end code lives in the “client” folder. Explore the files and folders within each.

Let’s start with the back-end API. This is already built out, for your convenience. Why? The focus of this tutorial is mainly on the client-side. If you’re looking for a back-end tutorial for setting up Passport with NodeJS, ExpressJS, and MongoDB take a look at this tutorial.

### User Registration

Open the “routes” folder and locate the following code:

Here, we grab the values from the payload sent with the POST request (from the client-side), create a new User instance, and then attempt to add the instance to the database. If this succeeds a user is added, of course, and then we return a JSON response with a status of “success”. If it fails, an “error” response is sent.

Let’s test this via curl. Fire up the server, and then run the following command:

You should see a success message:

Try it again, with the exact same username and password, and you should see an error:

This utilizes Passport’s local strategy to verify the username/email as well as the password. The appropriate response is then returned.

With the server running, test again with curl-

-and you should see:

Test again with curl, sending the wrong password, and you should see:

Perfect!

### User Logout

Finally, take a look at the logout:

This should be straightforward, and you can probably guess what the response will look like - but let’s test it again to be sure:

You should see:

On to the client-side!

## Angular App

Before diving in, remember that since end users have full access to the power of the browser as well as DevTools and the client-side code, it’s vital that you not only restrict access to sensitive endpoints on the server-side - but that you also do not store sensitive data on the client-side. Keep this in mind as you add auth functionality to your own MEAN application stack.

### Client-side Routing

Let’s add the remainder of the client-side routes to the main.js file:

Here, we created five new routes. Before we add the subsequent templates and controllers, let’s create a service to handle authentication.

### Authentication Service

Start by adding the basic structure of the service to a new file called services.js in the “client” directory:

## Route Restriction

Right now all client-side routes require a user to be logged in. What if you want certain routes restricted and other routes open?

You can add the following code to each route handler, replacing true with false for routes that you do not want to restrict:

For example:

Now just update the $routeChangeStart code in main.js: Test it out! ## Persistant Login Finally, what happens on a page refresh? Try it. The user is logged out, right? Why? Because the controller and services are called again, setting the user variable to null. This is a problem since the user is still logged in on the server side. Fortunately, the fix is simple: Within the $routeChangeStart we need to ALWAYS check if a user is logged in. Right now, it’s checking whether isLoggedIn() is false. Let’s update getUserStatus() so that it checks the user status on the back-end:

Finally, update the \$routeChangeStart:

Try it out!

## Conclusion

That’s it. One thing you should note is that the Angular app can be used with various frameworks as long as the endpoints are set up correctly in the AJAX requests. So, you can easily take the Angular portion and add it to your Django or Pyramid or NodeJS app. Try it!

Check out a Python/Flask app with Angular Auth here

Grab the final code from the repo. Cheers!