Bcrypt Authentication

 

1. Installing Third-party package bcrypt

Storing the passwords in plain text within a database is not a good idea since they can be misused, So Passwords should be encrypted

bcrypt
package provides functions to perform operations like encryption, comparison, etc

  • bcrypt.hash() uses various processes and encrypts the given password and makes it unpredictable
  • bcrypt.compare() function compares the password entered by the user and hash against each other

Installation Command

root@123:~/myapp# npm install bcrypt --save

2. Goodreads APIs for Specified Users

We need to maintain the list of users in a table and provide access only to that specified users

User needs to be registered and then log in to access the books

  • Register User API
  • Login User API

2.1 Register User API

Here we check whether the user is a new user or an existing user. Returns "User Already exists" for existing user else for a new user we store encrypted password in the DB

app.post("/users/", async (request, response) => {
const { username, name, password, gender, location } = request.body;
const hashedPassword = await bcrypt.hash(request.body.password, 10);
const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`;
const dbUser = await db.get(selectUserQuery);
if (dbUser === undefined) {
const createUserQuery = `
INSERT INTO
user (username, name, password, gender, location)
VALUES
(
'${username}',
'${name}',
'${hashedPassword}',
'${gender}',
'${location}'
)`;
const dbResponse = await db.run(createUserQuery);
const newUserId = dbResponse.lastID;
response.send(`Created new user with ${newUserId}`);
} else {
response.status = 400;
response.send("User already exists");
}
});
JAVASCRIPT
Collapse

2.2 Login User API

Here we check whether the user exists in DB or not. Returns "Invalid User" if the user doesn't exist else we compare the given password with the DB user password

app.post("/login", async (request, response) => {
const { username, password } = request.body;
const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`;
const dbUser = await db.get(selectUserQuery);
if (dbUser === undefined) {
response.status(400);
response.send("Invalid User");
} else {
const isPasswordMatched = await bcrypt.compare(password, dbUser.password);
if (isPasswordMatched === true) {
response.send("Login Success!");
} else {
response.status(400);
response.send("Invalid Password");
}
}
});
JAVASCRIPT
Collapse

Status Codes

Status CodesStatus Text ID
200OK
204No Response
301Moved Permanently
400Bad Request
403Forbidden
401Unauthorized

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form