CRUD Assignment
steps using in Crud assignment
first, create a folder name example "Crud_folder"
initialize package.json open the terminal and run the command npm init -y,
install the dependencies using npm install expresss mongoose cores bcrypt dotenv cookie-parser email-validator nodemon jsonwebtoken.
in Crud_folder create index.js and app.js files.
In Crud_folder create different types of folder
router-folder with authRoutes.js file
controller with authController.js file
middleware with jwtAuth.js file
for MongoDB connection creates a separate folder config with file databaseConfig.js
for creating a schema of the database create a model folder with userSchema.js file
for storing sensitive information such as database connection link, PORT number, CLINT_URL PORT create a file .env in file section type .env
node_module already install when creating JSON file
first, see the screenshot of how your file is shown in the folder
lets start in package.json make sure all dependencies successfully install
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"nodemon ./index.js" // write this starting servedr and terminal
}, // write npm run start server running
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.0",
"cookie-parser": "^1.4.6",
"cores": "^0.8.5",
"dotenv": "^16.3.1",
"email-validator": "^2.0.4",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.1",
"mongoose": "^7.3.4",
"nodemon": "^3.0.1"
}
}
require('dotenv').config();
const PORT = process.env.PORT||5006;
const app = require('./app');
app.listen(PORT, ()=>{
console.log(`Server is running at http//localhost:${PORT}`);
})
In app.js file write the code
const express = require('express');
const app = express();
const authRouter=require('./router/authRoute.js');
const databaseconnect = require('./config/databaseConfig.js');
databaseconnect();
const cookieParser= require('cookie-parser');
app.use(cookieParser());
const cores = require('cores');
app.use(cores({
origin:[process.env.CLINT_URL],
Credential:true
}))
app.use(express.json());
app.use('/api/auth/',authRouter);
app.use('/',(req , res)=>{
res.status(200).json({data:'JWTH server'})
})
module.exports=app;
authrouter.js
const express=require('express');
const { signup ,signin,getUser, logout } = require('../controller/authController');
const jwtAuth = require('../middleware/jwtAuth');
const authRouter=express.Router();
authRouter.post('/signup', signup);
authRouter.post('/signin', signin);
authRouter.get('/user',jwtAuth,getUser)
authRouter.get('/logout', jwtAuth, logout)
module.exports=authRouter;
authController.js
const userModel = require("../model/userschema");
const emailValidator = require('email-validator');
const bcrypt = require('bcrypt');
const signup= async(req,res,next)=>{
const {name, email,password, confirmPassword}=req.body;
console.log(name, email, password, confirmPassword);
if(!name||!email||!password||!confirmPassword){
res.status(400).json({
success:false,
message:"Every field is required"
})
}
const validEmail = emailValidator.validate(email);
if(!validEmail){
res.status(400).json({
success:false,
message:"please provide valid email"
})
}
if(password!==confirmPassword){
res.status(400).json({
success:false,
message:"Confirm password not match"
})
}
try {
const userInfo= userModel(req.body);
const result = await userInfo.save();
return res.status(200).json({
success:true,
data:result
});
} catch (error) {
if(error===11000){
return res.status(400).json({
success:false,
message:'Account already exist with provide id'
})
}
return res.status(400).json({
success:false,
message:error.message
})
}
}
const signin = async(req,res,next)=>{
const{ email, password}= req.body;
if(!email||!password){
res.status(400).json({
success:false,
message:"Every field is mandatory"
})
}
const user = await userModel
.findOne({
email
})
.select('+password');
if(!user|| !( await bcrypt.compare(password, user.password))){
res.status(400).json({
success:false,
message:"Invalid credentials"
})
}
try {
const token = user.jwtToken();
user.password=undefined;
const cookieOption={
maxAge:24*60*60*1000,
httpOnly:true
};
res.cookie("token",token,cookieOption);
res.status(200).json({
success:true,
data:user
})
} catch (error) {
res.status(400).json({
success:false,
message:error.message
})
}
}
const getUser= async(req,res,next)=>{
const userId= req.user.Id;
try {
const user= await userModel.findById(userId);
return res.status(200).json({
success: true,
data:user
});
} catch (e) {
return res.success(400).json({
success:false,
message:e.message
})
}
}
const logout=(req,res)=>{
try {
const cookieOption ={
expires:new Date(),
httpOnly:true
}
res.cookie("token",null,cookieOption);
return res.status(200).json({
success:true,
message:"Logged Out"
})
} catch (e) {
return res.status(400).json({
success:false,
message:e.message
})
}
}
module.exports={
signup,
signin,
getUser,
logout
}
databaseConfig.js
const mongoose = require('mongoose')
const MONGODB_URL= process.env.MONGODB_URL||'mongodb://127.0.0.1:27017/config';
const databaseconnect= async()=>{
try {
await mongoose.connect(MONGODB_URL);
console.log("Connected to DataBase:");
} catch (error) {
console.log("ERROR find",error.message);
}
}
module.exports=databaseconnect;
userSchema.js
const mongoose= require('mongoose');
const JWT = require('jsonwebtoken')
const bcrypt= require('bcrypt');
const {Schema} =mongoose;
const userSchema = new Schema({
name:{
type:String,
required:[true, 'user name is Required'],
minLength:[7, 'Name must be at least 7 char'],
maxLength:[50, 'Name should be less than 50'],
trim:true
},
email:{
type:String,
required:[true, 'user email is Required'],
unique:true,
lowercase:true,
unique:[true, 'already registed'],
trim:true
},
password:{
type:String,
select:false,
required:[true, 'user password is Required'],
},
confirmPassword:{
type:String,
required:[true,'confirmpassword required'],
select:false
},
forgetPasswordToken:{
type:String,
select:false,
},
forPasswordExpiryDate:{
type:Date
},
});
userSchema.pre('save', async function(next){
if(!this.isModified('password')){
return next();
}
this.password=await bcrypt.hash(this.password,10);
return next();
})
userSchema.methods={
jwtToken(){
return JWT.sign({
id: this._id,
email:this.email},
process.env.SECRET,
{expiresIn:'24h'}
)
}
}
const userModel = mongoose.model('user', userSchema);
module.exports=userModel;
middleware folder file name jwtAuth.js
const JWT = require('jsonwebtoken');
//must use next
const jwtAuth = (req,res,next)=>{
const token = (req.cookies && req.cookies.token)||null;
if(!token){
return res.status(400).json({
success:false,
message:'Not authorized'
})
}
try {
const payload = JWT.verify(token, process.env.SECRET);
req.user = { id:payload.id, email:payload.email};
} catch (e) {
return res.status(400).json({
success:false,
message:e.message
})
}
next();
}
module.exports=jwtAuth;
.env
PORT=5009
MONGODB_URL=
SECRET=SECRET
CLINT_URL=http://localhost:3000