Skip to content

Commit

Permalink
Solution to lesson 5 FrontendMasters#1
Browse files Browse the repository at this point in the history
  • Loading branch information
RodrigoBervig committed Jan 30, 2020
1 parent ed637fd commit 273cb0f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/resources/user/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ userSchema.pre('save', function(next) {
})
})

userSchema.methods.checkPassword = function(password) {
userSchema.methods.checkPassword = password => {
const passwordHash = this.password
return new Promise((resolve, reject) => {
bcrypt.compare(password, passwordHash, (err, same) => {
Expand Down
41 changes: 38 additions & 3 deletions src/utils/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,48 @@ export const verifyToken = token =>
new Promise((resolve, reject) => {
jwt.verify(token, config.secrets.jwt, (err, payload) => {
if (err) return reject(err)
resolve(payload)
resolve(payload) // payload will be a user
})
})

export const signup = async (req, res) => {}
/* Routes for authentication: (don't really work with REST) */
export const signup = async (req, res) => {
if (!req.body.password || !req.body.email) {
return res.status(400).send({ message: 'Email or Password invalid' })
}

export const signin = async (req, res) => {}
try {
const user = await User.create(req.body)
const token = newToken(user)
return res.status(201).send({ token })
} catch (e) {
console.error(e)
res.status(400).end()
}
}

export const signin = async (req, res) => {
if (!req.body.password || !req.body.email) {
return res.status(400).send({ message: 'E-mail or password invalid' })
}

const user = await User.findOne({ email: req.body.email })
.select('email password')
.exec()

if (!user) {
return res.status(401).send({ message: 'User not valid' })
}

const password = await user.checkPassword(req.body.password)

if (!password) {
return res.status(401).send({ message: 'password not valid' })
}

const token = newToken(user)
return res.status(201).send({ token })
}

export const protect = async (req, res, next) => {
next()
Expand Down

0 comments on commit 273cb0f

Please sign in to comment.