0% found this document useful (0 votes)
3 views4 pages

Passport Local Mern Notes

This document outlines the steps to set up local authentication using Passport.js in a MERN stack project. It covers installing necessary packages, creating a user model with password hashing, configuring Passport.js, initializing it in an Express server, and creating authentication routes for user registration, login, and logout. The document also provides example API requests for testing the authentication functionality.

Uploaded by

shivamp7003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Passport Local Mern Notes

This document outlines the steps to set up local authentication using Passport.js in a MERN stack project. It covers installing necessary packages, creating a user model with password hashing, configuring Passport.js, initializing it in an Express server, and creating authentication routes for user registration, login, and logout. The document also provides example API requests for testing the authentication functionality.

Uploaded by

shivamp7003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Setting Up Passport.

js Local Authentication in a MERN Stack Project

## Step 1: Install Required Packages


First, install the necessary dependencies in your Node.js backend:
```sh
npm install express passport passport-local bcryptjs express-session mon
```
## Step 2: Set Up User Model
Create a `User` model using Mongoose (`models/User.js`).
```javascript
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
// Hash password before saving
UserSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next(); // If password is not modified
this.password = await bcrypt.hash(this.password, 10); // Hash the passwo
next();
});
module.exports = mongoose.model('User', UserSchema);
```
## Step 3: Configure Passport.js
Create a `config/passport.js` file.
```javascript
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const User = require('../models/User');
module.exports = function (passport) {
passport.use(
new LocalStrategy(async (username, password, done) => {
try {
const user = await User.findOne({ username });
if (!user) return done(null, false, { message: 'User not found' }); // If no
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return done(null, false, { message: 'Incorrect password' })
return done(null, user); // If user is found and password matches, retu
} catch (err) {
return done(err);
}
})
);
// Serialize user to store in session
passport.serializeUser((user, done) => {
done(null, user.id);
});
// Deserialize user from session
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err);
}
});
};
```
## Step 4: Initialize Passport in Express
In your main server file (`server.js` or `index.js`), configure passport and se
```javascript
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const authRoutes = require('./routes/auth');
require('./config/passport')(passport);
const app = express();
app.use(express.json()); // Middleware to parse JSON request bodies
app.use(session({
secret: 'your_secret_key', // Secret key for session encryption
resave: false, // Prevents resaving session if nothing changed
saveUninitialized: false // Avoids storing uninitialized sessions
}));
app.use(passport.initialize()); // Initialize Passport middleware
app.use(passport.session()); // Middleware to use persistent login sessions
// Routes
app.use('/auth', authRoutes);
mongoose.connect('mongodb://localhost:27017/passportAuth', { useNewU
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.listen(5000, () => console.log('Server running on port 5000'));
```
## Step 5: Create Authentication Routes
Create `routes/auth.js`.
```javascript
const express = require('express');
const passport = require('passport');
const User = require('../models/User');
const router = express.Router();
// Register Route
router.post('/register', async (req, res) => {
try {
const { username, password } = req.body;
let user = await User.findOne({ username });
if (user) return res.status(400).json({ msg: 'User already exists' });
user = new User({ username, password });
await user.save();
res.status(201).json({ msg: 'User registered' });
} catch (err) {
res.status(500).json({ msg: 'Server error' });
}
});
// Login Route
router.post('/login', passport.authenticate('local'), (req, res) => {
res.json({ msg: 'Logged in successfully', user: req.user });
});
// Logout Route
router.get('/logout', (req, res) => {
req.logout(() => {
res.json({ msg: 'Logged out successfully' });
});
});
module.exports = router;
```
## Step 6: Test the Authentication
Use **Postman** or **cURL** to test:
1. **Register a User:**
```sh
POST http://localhost:5000/auth/register
Body: { "username": "testuser", "password": "password123" }
```
2. **Login:**
```sh
POST http://localhost:5000/auth/login
Body: { "username": "testuser", "password": "password123" }
```
3. **Logout:**
```sh
GET http://localhost:5000/auth/logout
```
---
This setup ensures secure local authentication using **Passport.js** in a M

You might also like