Full Post Page
 

ExpressJS Authentication

Category: NODE JS & Written by Admin On May-26-2025 17:11:41

ExpressJS :Authentication Login Logout from login-> server-->database | Session database mongoose package bcrypt=>step https://www.npmjs.com/package/bcrypt npm i bcrypt step 1 npm install bcryptjs step 2 const bcrypt=require('bcryptjs') step 3 const hashedPassword =bcrypt.hash(password,10) or bcrypt.hashSync(password,10) step 4 const isMath=bcrypt.compare('admin',hashedPassword) or bcrypt.compareSync('admin123',hashedPassword) npm install mongoose npm install express-session npm i bcryptnpm i bcrypt app.js const session=require('express-session') const bcrypt=require('bcrypts') const mongoose=require('mongoose') //database connection mongoose.connect('mongodb://127.0.1/user-crud').then(()=>{ console.log("database connection successfully") }) //middleware app.use(express.urlencoded({ extended:false})) app.use(express.json()) app.set('view engine',"ejs") DATA CURD OPERATION WORK Schema -deine the structure Schema-Model using model we do CRUD operation create model file user.model.js const mongoose =require('mongoose') const userSchema=new mongoose.Schema({ username :{ type: String, require: true, unique: true }, userpass:{ type :String, require: true } }) //export module.exports=mongoose.model('User',userSchema)// define table(collection self users) // OPEN CMD CHECK YOUR DB AND collection show dbs,use yourdbname,show collections,db.collectiosname.find() INSERT DATA HERE SELF first db.users.insertOne({ username:"admin123@gmail.com" , userpass:"kumar" }) db.users.insertOne({ username:"Rupesh123@gmail.com" , userpass:"23456" }) //CHECK db.users.find() Go Route app.get('/login',(req,res)=>{ res.render("login"); }); app.get('/register',(req,res)=>{ res.render("register"); }); insert app.post('/register',async(req,res) => { const {username,userpass} = req.body// oject destruture const hasedPassword =await bcrypt.hash(userpass, 10) // method 1 create await User.create({username,userpass: hasedPassword}) //res.send({username,userpass: hasedPassword}) // for seeing browser but krna redirect login page par res.redirect ('/login') // after fill redirect in login page }) //Session step 1 const session=require('express-session') app.use(session({ secret:'secret123', resave:false, saveUninitialized:false })) step 3 app.get('/',(req,res)=>{ res.send(`<h2>Home Page</h2> <p>Hello, ${req.session.user}</p>`) }); step 2 // after login create session name user req.session.user = username res.redirect('/') // logout route app.get('/logout',(req,res)=>{ req.session.destroy(()=>{ res.redirect('/login') }) }) notes after logut from route open logout Hello, undefined showing this error showing but we want to don't open any page without login step 1 create login check middleware and pass in any route para let checklogin=(req,res,next)=>{ if(req.session.user){ next() }else{ res.redirect('login') } } app.get('/login',(req,res)=>{ // check for i m login or not if(req.session.user){ res.redirect('/') }else{ res.render('login',{error:null}) } }); Example: app.get('/',checklogin,(req,res)=>{ res.send(`<h2>Home Page</h2> <p>Hello, ${req.session.user}</p>`) });

Comments

Share your thoughts about this post

Why Choose Us:

Experienced Instructors: Our team of experienced instructors are passionate about coding and dedicated to helping you succeed. With years of industry experience and a knack for teaching, they'll guide you every step of the way. Beginner-Friendly Content: Don't worry if you're new to coding. Our tutorials are designed with beginners in mind, starting from the fundamentals and gradually building up to more advanced topics. Updated Content: Coding is a rapidly evolving field, and we're committed to keeping our content up-to-date with the latest trends, technologies, and best practices. Community Support: Learning to code is more fun and effective when you're part of a supportive community. Join our online community forums to connect with fellow learners, share insights, and collaborate on projects. Get Started Today:



Recent Posts

Advance Js Fetch API Part-5

June-06-2025 21:23:08


Advance Js Promise Part-4

June-06-2025 11:35:05


Advance js oop part-3

June-06-2025 08:25:42


ExpressJs API With Image Crud-3

June-02-2025 21:09:41


NodeJs API-MVC-2

June-02-2025 10:56:22


ExpressJs API Crud-1

June-02-2025 10:27:58


ExpressJs Files upload

June-02-2025 10:15:40


NodeJS Cookie and CsrfToken

May-30-2025 19:20:40


ExpressJS Session

May-30-2025 19:14:29


ExpressJS NodeJs Crud Part-2

May-27-2025 21:52:18


ExpressJS NodeJS Crud Part-1

May-27-2025 21:33:30


ExpressJS Authentication

May-26-2025 17:11:41


NodeJS ExpressJS Files Upload

May-26-2025 16:53:29



Angular Introduction

May-13-2025 21:02:32



Advance Js part-1

May-12-2025 15:41:29