Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Created July 11, 2020 19:31
Show Gist options
  • Select an option

  • Save heytulsiprasad/4c7690e6e0aec69b28637c67048b9e29 to your computer and use it in GitHub Desktop.

Select an option

Save heytulsiprasad/4c7690e6e0aec69b28637c67048b9e29 to your computer and use it in GitHub Desktop.
Login authentication route using JWT
// @route POST api/auth
// @desc Auth user
// @access Public
router.post("/", async (req, res) => {
const { email, password } = req.body
// Simple validation
if (!email || !password) return res.status(400).json({ msg: "Please enter all fields" })
// Check for existing user
const user = await User.findOne({ email })
if (!user) return res.status(400).json({ msg: "User doesn't exists" });
// Validate password
bcrypt.compare(password, user.password)
.then(isMatch => {
if (!isMatch) return res.status(400).json({ msg: "Invalid credentials"})
// If it does match, we'll generate a JWT token
jwt.sign(
{ id: user.id },
process.env.JWT_SECRET,
{ expiresIn: 4800 },
(err, token) => {
if (err) throw err;
res.json({
token,
user: {
id: user.id,
name: user.name,
email: user.email,
})
}
)
})
})
const mongoose = require("mongoose")
const Schema = mongoose.Schema
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
register_date: {
type: Date,
default: Date.now,
},
});
// Creating a model out of schema
const user = mongoose.model("user", userSchema);
export default user;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment