Skip to content

Commit

Permalink
Merge pull request #11 from Loo-Ashworth/emmad
Browse files Browse the repository at this point in the history
added user validation stuff
  • Loading branch information
adrianHards committed Jun 14, 2023
2 parents aa21c24 + 6da1bed commit b4ab720
Show file tree
Hide file tree
Showing 10 changed files with 462 additions and 81 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,7 @@ Some people occasionally experience MongoDB connection errors when running the t
- Check that it's running using `brew services list`

If you have issues that are not resolved by these tips, please reach out to a coach and, once the issue is resolved, we can add a new tip!

Requirements
Bcrypt - for pw hashing
Validator
15 changes: 15 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,21 @@ app.use((req, res, next) => {
next();
});

app.post('/signup', async (req, res) => {
try {
if (req.body.password !== req.body.password2) {
throw new Error("Passwords don't match. Try again.");
}

const user = new User(req.body);
await user.save();
// Rest of your sign-up logic...
} catch (error) {
res.status(400).send(error);
}
});


// route setup
app.use("/", homeRouter);
app.use("/posts", sessionChecker, postsRouter);
Expand Down
27 changes: 19 additions & 8 deletions controllers/sessions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const User = require("../models/user");
const bcrypt = require('bcrypt');


const SessionsController = {
New: (req, res) => {
Expand All @@ -9,15 +11,23 @@ const SessionsController = {
console.log("trying to log in");
const email = req.body.email;
const password = req.body.password;

User.findOne({ email: email }).then((user) => {
console.log("password entered:", password)
// Ensure password field is included
User.findOne({ email: email }).select('+password').then(async (user) => {
if (!user) {
res.render("sessions/new", { error: "User not found" });
} else if (user.password != password) {
res.render("sessions/new", { error: "Incorrect password" });
} else {
req.session.user = user;
res.redirect("/posts");
}
else {

// Compare the user input password with the hashed password in the database
const match = await bcrypt.compare(password, user.password);

if (!match) {
res.render("sessions/new", { error: 'Incorrect password' });
} else {
req.session.user = user;
res.redirect("/posts");
}
}
});
},
Expand All @@ -30,4 +40,5 @@ const SessionsController = {
},
};

module.exports = SessionsController;

module.exports = SessionsController;
29 changes: 22 additions & 7 deletions controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,30 @@ const UsersController = {
res.render("users/new", {});
},


Create: (req, res) => {
const user = new User(req.body);
user.save((err) => {
if (err) {
throw err;
}
res.status(201).redirect("/posts");
});
user.save()
.then(() => {
res.status(201).redirect("/posts");
})
.catch((error) => {
console.error(error);
if (error.name === 'MongoError' && error.code === 11000) {
// Duplicate username or email error
let errorMsg = '';
if (error.keyPattern && error.keyPattern.username) {
errorMsg = 'Username already exists!';
} else if (error.keyPattern && error.keyPattern.email) {
errorMsg = 'Email already exists!';
}
res.status(422).render("users/new", { error: errorMsg });
} else {
// Some other error
res.status(400).render("users/new", { error: 'An error occurred while creating the user.' });
}
});
},
};
}

module.exports = UsersController;
46 changes: 42 additions & 4 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,48 @@
const mongoose = require("mongoose");
const bcrypt = require('bcrypt');
const validator = require('validator');

const UserSchema = new mongoose.Schema({
email: String,
password: String,
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
},
},
password: {
type: String,
required: true,
minlength: 8,
validate(value) {
if(value.length < 8) {
throw new Error("Passwords is too short. At least 8 characters.")
}
}},
username:
{ type: String,
required: true,
unique: true,
trim: true,
maxlength: 25 },
});

const User = mongoose.model("User", UserSchema);
UserSchema.pre('save', async function (next) {
console.log("password: ", this)
const user = this;
if (user.isModified('password')) {
console.log('Hashing password...');
user.password = await bcrypt.hash(user.password, 8);
console.log('Hashed password:', user.password);
}
next();
});

module.exports = mongoose.model("User", UserSchema);


module.exports = User;
Loading

0 comments on commit b4ab720

Please sign in to comment.