Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Milestone 06/Passwords in Plain Sight/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
.env
.DS_Store
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ export const login = async (req, res) => {
try {
const { email, password } = req.body

const user = await User.findOne({ email })
const user = await User.findOne({ email }).select('+password')
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' })
}

// Direct string comparison — unsafe
if (user.password !== password) {
const isMatch = await user.matchPassword(password)
if (!isMatch) {
return res.status(401).json({ message: 'Invalid credentials' })
}

Expand Down
17 changes: 16 additions & 1 deletion Milestone 06/Passwords in Plain Sight/backend/models/User.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose from 'mongoose'
import bcrypt from 'bcryptjs'

const userSchema = new mongoose.Schema(
{
Expand All @@ -11,10 +12,24 @@ const userSchema = new mongoose.Schema(
password: {
type: String,
required: true,
// No minlength, no select: false, no pre-save hook
minlength: 8,
select: false,
},
},
{ timestamps: true }
)

userSchema.pre('save', async function (next) {
if (!this.isModified('password')) {
return next()
}

this.password = await bcrypt.hash(this.password, 12)
next()
})

userSchema.methods.matchPassword = async function (enteredPassword) {
return bcrypt.compare(enteredPassword, this.password)
}

export default mongoose.model('User', userSchema)
Loading