Commit d4346d12 authored by Tobias Ørstad's avatar Tobias Ørstad
Browse files

Added hashing of passwords

parent b76fd9a7
const express = require("express");
const router = express.Router();
const mongo = require("mongodb");
const bcrypt = require("bcrypt");
const MongoClient = mongo.MongoClient;
const connectionUrl = process.env.MONGO_CONNECTION_STRING;
const saltRounds = 10;
router.get("/username/:playerId", (req, res) => {
// Connect to database
......@@ -67,14 +69,30 @@ router.get("/login/:username/:password", (req, res) => {
db.collection(collection)
.find({
name: req.params.username,
password: req.params.password,
})
.toArray((err, result) => {
if (err) {
res.sendStatus(500);
return;
}
res.json(result);
// Compares the given password with the encrypted password stored in the database,
// response is true on match, false else
bcrypt.compare(
req.params.password,
result[0].password,
(err, response) => {
if (err) {
res.sendStatus(500);
client.close();
return;
}
if (response) {
res.json(result);
} else {
res.json([]);
}
}
);
client.close();
});
}
......@@ -103,24 +121,30 @@ router.put("/", (req, res) => {
res.status(400).send("Invalid parameters");
return;
}
// Inserts the user. Note that the name index is unique, inserting a user with an
// already existing username will give an error.
db.collection(collection).insertOne(
{
name: req.body.username,
password: req.body.password,
dateJoined: date,
},
(err, result) => {
if (err) {
res.status(400).send("Already existing username"); // Internal server error
return;
}
res.json(result.ops[0]);
client.close();
//Hashes the password
bcrypt.hash(req.body.password, saltRounds, (err, hash) => {
if (err) {
res.sendStatus(500); // Internal server error
return;
}
);
// Inserts the user. Note that the name index is unique, inserting a user with an
// already existing username will give an error.
db.collection(collection).insertOne(
{
name: req.body.username,
password: hash,
dateJoined: date,
},
(err, result) => {
if (err) {
res.status(400).send("Already existing username");
return;
}
res.json(result.ops[0]);
client.close();
}
);
});
}
);
});
......
This diff is collapsed.
......@@ -10,6 +10,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^4.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment