Building the API - user interaction

We're building software for people, and we need to give them a way to communicate with it. This lesson will show you how to prepare an API for user interaction like loging in and adding products to list of favorites. Moreover you will be introduced to the security essentials like cookies encryption and password hashing.

Building the API - user interaction#

You are about to implement three more endpoints:

  • POST /login will accept body in the form of {email: user_email, password: user_password}, look for a user in the database, and respond with one of the following:

    • Status code 200 along with a cookie containing userID if the user is found.

    • Status code 401 if the user is not found.

  • GET /isLoggedIn will respond with one of the following:

    • Status code 200 if a cookie containing userID is present in the request, and the user with the given userID exists in the database.

    • Status code 401 if the cookie is not set or the user is not found.

  • POST /favorites/:id will add a product to the list of a user's favorites. The product will be defined by the :id query parameter, and the user will be retrieved by userID from the cookie. Action success will be confirmed by status code 202. If the cookie is not present, this endpoint will respond with status code 401.

You will keep userID in a cookie file, which could be easily compromised. An attacker could steal this data, use it to impersonate someone else, and act in the system as that person, which is as easy as changing the cookie file content. To protect your users against this kind of attacks, always encrypt cookies containing sensitive data.

Install dependencies necessary to accomplish this step:

Generate a private key that you will use to encrypt and decrypt cookies:

Add import statements that you'll need for /user/* endpoints to api.ts:

Declare the encrypt() and decrypt() functions that will help protect data kept in cookies from manipulation:

User authentication#

You can now introduce endpoints mentioned at the beginning of this section, and keep userID in the cookie file as it's now protected from manipulation.

Start by importing the cookie-parser:

Add it to your api sub-application:

Then add the endpoints code:

Notice the usage of the crypto library in the login endpoint. Passwords are stored in the database in hashed form (using SHA-512), and when the user sends their password, it needs to be hashed again before it's used to query the database. Never store user passwords in plain text. If your database is compromised and data you keep in it leaks, it will be a disaster for your customers if you store their passwords in plain text.

 

This page is a preview of The newline Guide to Angular Universal

No discussions yet