Skip to content

Instantly share code, notes, and snippets.

@blogcacanid
Created November 12, 2020 07:44
Show Gist options
  • Save blogcacanid/34f2ad284b547f655c8ac6a156807ddf to your computer and use it in GitHub Desktop.
Save blogcacanid/34f2ad284b547f655c8ac6a156807ddf to your computer and use it in GitHub Desktop.
auth.controller.js Authentication JWT Node.js
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