Created
November 12, 2020 07:44
-
-
Save blogcacanid/34f2ad284b547f655c8ac6a156807ddf to your computer and use it in GitHub Desktop.
auth.controller.js Authentication JWT Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const db = require("../models"); | |
const config = require("../config/auth.config"); | |
const User = db.user; | |
var jwt = require("jsonwebtoken"); | |
var bcrypt = require("bcryptjs"); | |
exports.register = (req, res) => { | |
// Save User to Database | |
User.create({ | |
username: req.body.username, | |
email: req.body.email, | |
password: bcrypt.hashSync(req.body.password, 8) | |
}) | |
.then(user => { | |
res.send({ message: "User was registered successfully!" }); | |
}) | |
.catch(err => { | |
res.status(500).send({ message: err.message }); | |
}); | |
}; | |
exports.login = (req, res) => { | |
User.findOne({ | |
where: { | |
username: req.body.username | |
} | |
}) | |
.then(user => { | |
if (!user) { | |
return res.status(404).send({ message: "User Not found." }); | |
} | |
var passwordIsValid = bcrypt.compareSync( | |
req.body.password, | |
user.password | |
); | |
if (!passwordIsValid) { | |
return res.status(401).send({ | |
accessToken: null, | |
message: "Invalid Password!" | |
}); | |
} | |
var token = jwt.sign({ id: user.id }, config.secret, { | |
expiresIn: 86400 // 24 hours | |
}); | |
res.status(200).send({ | |
id: user.id, | |
username: user.username, | |
email: user.email, | |
accessToken: token | |
}); | |
}) | |
.catch(err => { | |
res.status(500).send({ message: err.message }); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment