If you need a starting point fork this: Starting point.
- Create a model called
User
that has the following fields:username
which is aString
, not optional, and unique.password
which is aString
and not optional.email
which is aString
and must be an email.firstName
which is aString
.lastName
which is aString
.
- Create a
user
folder, and inside it ausers.controllers
and ausers.routes
files and connect it the routes toapp.js
.
- In
users.controllers
, create a method calledsignup
. - Install
bcrypt
and require it inusers.controllers
. - Hash the password with
10
salt rounds and overwritereq.body.password
with the new, hashed password. - Pass the body of the request to
User.create
. - Change the response status to
201
and end it with a message. - Don't forget to create your route in
users.routes.js
and give it the path/apis/signup
.
- Create a new folder called
config
. - In this folder create a file called
keys.js
. - Create an object that has two properties:
JWT_SECRET
: give it a secret key.JWT_EXPIRATION_MS
: give it the time for your token expiration in milliseconds.
- Export this object.
Generate a token in users.controllers
's signup
method.
- Require
JWT_EXPIRATION_MS
andJWT_SECRET
fromconfig/keys.js
. - Install
jsonwebtoken
. - Require
jwt
fromjsonwebtoken
. - In
users.controllers
, create a function calledgenerateToken
that takesuser
as an argument. - In this function, create an object called
payload
and pass it the user'susername
that's coming fromuser
. - Keep in mind that the token must have the user's ID and the expiration date of the token.
- Add an
exp
property topayload
and its value is the date right now plusJWT_EXPIRATION_MS
. - After creating your
payload
object, calljwt.sign()
and pass it two arguments:payload
, make sure to stringify it.JWT_SECRET
- Save the returned value in a variable called
token
and returntoken
. - In the
signup
method, after creating the user callgenerateToken
and pss it the new user. - Save the returned value in a variable called
token
and send it as a response.