// app/models/user.jsconstsignup= (request, response) => {
// get user from request body// encrypt plain text password with bcrypt// set user's password_digest to encrypted pw// create token to be sent back to client to create "session"// set user's token to created token// save user with password_digest and session token to database// respond with 201 and json of created user info
}

Sign In

We'll need a route within server.js to handle this request:

// server.jsapp.post('/signin', User.signin)

Let's dream-drive /signin as well:

// app/models/user.jsconstsignin= (request, response) => {
// get user creds from request body// find user based on username in request// check user's password_digest against pw from request// if match, create and save a new token for user// send back json to client with token and user info
}

Pause and Digest

We've gotten a lot done, but we're not quite finished. Let's go back over what we have done so we can see clearer what's left to do.

We've gotten /signup and /signin working.

/signup can:

create new users

securely encrypt users' passwords

generate a user token to be stored client-side

respond with a status of 201 and important user info

/signin can:

verify that a username and password in a request match a record in the database

regenerate a user's token to restore client-side

respond with a status of 200 and important user info

So what else do we need?

Well, if we have routes that need to be protected by authentication, we'd need to build in that functionality.

Right now, we're passing a token back to our client that we're expecting the client to store for the duration of the user's session.

For any routes that should be protected to authenticated users, we'd have to get that token back from the client and ensure that it matches the user's token within the database.

Protecting Routes with Token Authentication

There are many, many ways we could go about this, but let's start with the most simple and straightforward.

We'll need to assume our client knows to send us the token we sent back on sign in with every authenticated request coming into our API.

That being said, we can create an authenticate function that takes the client's request body as an argument. We can use this as a helper function to conditionally return out of a different function should the request coming in not be from an authenticated user.