-
-
Save sahilkashyap64/609d4c25bc531ce878142426ee75c5e1 to your computer and use it in GitHub Desktop.
Login with MERN Stack, JWT
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
//.env | |
JWT_SECRET={{mysecret}} |
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
class ErrorHandler extends Error { | |
constructor(statusCode, message) { | |
super(); | |
this.statusCode = statusCode; | |
this.message = message; | |
} | |
} | |
const handleError = (err, res) => { | |
const { statusCode, message } = err; | |
res.status(statusCode).json({ | |
status: "error", | |
statusCode, | |
message | |
}); | |
}; | |
module.exports = { | |
ErrorHandler, | |
handleError | |
}; |
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
{ | |
"name": "backend", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1", | |
"start":"node server.js" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"bcryptjs": "^2.4.3", | |
"cors": "^2.8.5", | |
"dotenv": "^8.2.0", | |
"express": "^4.17.1", | |
"jsonwebtoken": "^8.5.1", | |
"mongoose": "^5.9.5", | |
"morgan": "^1.10.0" | |
} | |
} |
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 express = require("express"); | |
const router = express.Router(); | |
const userController = require("../controllers/userController");//import userController | |
router.post("/signup", userController.signup);//get signup function from userController | |
router.post("/login", userController.login);//get login function from userController | |
module.exports = router; |
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
//express | |
const express = require("express"); | |
const app = express(); | |
const path = require("path"); | |
require("dotenv").config({ | |
path: path.join(__dirname, "./.env") | |
}); | |
const PORT = process.env.PORT || 3000; | |
const routes = require("./routes/route");//imports routes | |
//imports | |
const morgan = require("morgan"); | |
var cors = require('cors'); | |
const { handleError, ErrorHandler } = require('./helpers/error') | |
//mongodb | |
const mongoose = require("mongoose"); | |
mongoose | |
.connect("mongodb://localhost:27017/mernbackend", { useNewUrlParser: true, useUnifiedTopology: true,autoIndex: true , useCreateIndex: true,}) | |
.then(() => { | |
console.log("Connected to the Database successfully"); | |
}); | |
//middlewares | |
app.use(express.json()); | |
app.use(morgan("dev"));//this will log all the http request in console | |
app.use(cors()); //for dealing with cross orgin policy | |
app.use("/", routes); //importing routes from route file | |
app.use((err, req, res, next) => { | |
handleError(err, res); | |
});//handle error | |
//server | |
app.listen(PORT, function() { | |
console.log("Server is listening on Port:", PORT); | |
}); |
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 User = require("../models/userModel"); | |
const jwt = require("jsonwebtoken"); | |
const bcrypt = require("bcryptjs"); | |
const { ErrorHandler } = require('../helpers/error'); | |
async function hashPassword(password) { | |
return await bcrypt.hash(password, 10); | |
} | |
async function validatePassword(plainPassword, hashedPassword) { | |
return await bcrypt.compare(plainPassword, hashedPassword); | |
} | |
//sign up | |
exports.signup = async (req, res, next) => { | |
try { | |
const { email, password } = req.body; | |
if (!email || !password) { | |
throw new ErrorHandler(404, 'Missing required email and password fields'); | |
} | |
// checking if the email provided already exist in the DB | |
const email_exist=await User.findOne({email}); | |
//if it exist we are returning an error message | |
if (email_exist) { | |
throw new ErrorHandler(409, 'Email already exist!'); | |
} | |
const hashedPassword = await hashPassword(password); | |
const newUser = new User({ | |
email, | |
password: hashedPassword, | |
}); | |
const accessToken = jwt.sign( | |
{ userId: newUser._id }, | |
process.env.JWT_SECRET, | |
{ | |
expiresIn: "1d" | |
} | |
); | |
newUser.accessToken = accessToken; | |
await newUser.save(); | |
res.json({ data: newUser,accessToken }); | |
} catch (error) { | |
next(error); | |
} | |
}; | |
//login | |
exports.login = async (req, res, next) => { | |
try { | |
const { email, password } = req.body; | |
const user = await User.findOne({ email }); | |
if (!user) { | |
throw new ErrorHandler(401, 'Email does not exist!') | |
} | |
const validPassword = await validatePassword(password, user.password); | |
if (!validPassword) { | |
throw new ErrorHandler(404, 'Password is not correct!') | |
} | |
const accessToken = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { | |
expiresIn: "1d" | |
}); | |
await User.findByIdAndUpdate(user._id, { accessToken }); | |
res | |
.status(200) | |
.json({ data: { email: user.email }, accessToken }); | |
} catch (error) { | |
next(error); | |
} | |
}; |
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 mongoose = require("mongoose"); | |
const Schema = mongoose.Schema; | |
const UserSchema = new Schema({ | |
email: { | |
type: String, | |
required: true, | |
trim: true, | |
unique: true | |
}, | |
password: { type: String, required: true }, | |
}); | |
const User = mongoose.model("user", UserSchema); | |
module.exports = User; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment