Skip to content
Snippets Groups Projects

Added hashing of passwords

Merged Tobias Ingebrigt Ørstad requested to merge 95-backend-cleanup into dev
3 files
+ 418
44
Compare changes
  • Side-by-side
  • Inline
Files
3
+ 43
19
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();
}
);
});
}
);
});
Loading