Skip to content

Commit

Permalink
signup with password hashing implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
dinilgamage committed Feb 23, 2024
1 parent d5aacf0 commit f9e1709
Show file tree
Hide file tree
Showing 4 changed files with 595 additions and 5 deletions.
10 changes: 9 additions & 1 deletion backend/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,13 @@ exports.loginUser = async (req, res) => {

//signup user
exports.signupUser = async (req, res) => {
res.json({message: 'Signup'})
const { email, password } = req.body;

try {
const user = await User.signup(email, password);
res.status(200).json({ email, user });
}
catch (err) {
res.status(400).json({ error: err.message });
}
};
24 changes: 20 additions & 4 deletions backend/models/userModel.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const userSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Email is required'],
required: true,
unique: true,
trim: true,
trim: true

},
password: {
type: String,
required: [true, 'Password is required'],
minlength: [6, 'Password must be at least 6 characters']
required: true
}
}, { timestamps: true });

//static signup method
userSchema.statics.signup = async function(email, password) {
const exists = await this.findOne({ email });

if (exists) {
throw new Error('Email already in use');
}

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

const user = await this.create({ email, password: hashedPassword });

return user;
};

module.exports = mongoose.model('User', userSchema);
Loading

0 comments on commit f9e1709

Please sign in to comment.