Authentication using Passport

RMAG news

Introduction to Passport.org

Passport is a library of authentication functions that is adaptable to the needs of most applications.

Node.js authentication using Passport is a popular choice for developers because it provides a simple and flexible way to authenticate users. Passport is a middleware that can be easily integrated into any Node.js application to handle authentication strategies, such as local authentication with username and password, OAuth, OpenID, and more.

Setup and installation Passport.org

First, you need to set up a Node.js project. Initialize a new Node.js project using npm or yarn.

Then, install Passport and any relevant strategies you plan to use.

npm install passport passport-local

Configure Passport.js

Create a File Like eg-app.js

Create a server and connect it with database to Store user data

const express = require(express);N
const app = express();
const { connectMongoose, User } = require(./database.js);
const expressSession = require(express-session);
const ejs = require(ejs);
const passport = require(passport);
const { initializingPassport, isAuthenticated } = require(./passportConfig.js);
// Call the connectMongoose function to establish the database connection
connectMongoose();

initializingPassport(passport);

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// To Use Passport..
app.use(
expressSession({ secret: secret, resave: false, saveUninitialized: false })
);
app.use(passport.initialize());
app.use(passport.session());

app.set(view engine, ejs);

app.get(/, (req, res) => {
res.render(index);
});

app.get(/register, (req, res) => {
res.render(register);
});

app.get(/login, (req, res) => {
res.render(login);
});

app.post(/register, async (req, res) => {
// Handle registration logic here
const user = await User.findOne({ username: req.body.username });
if (user) return res.status(400).send(User already exists);

const newuser = await User.create(req.body);

res.status(201).send(newuser);
});

app.post(
/login,
passport.authenticate(local, {
failureRedirect: /register,
successRedirect: /,
})
);

app.get(/profile, isAuthenticated, (req, res) => {
res.send(req.user);
});

// For Logout…
app.get(/logout, (req, res) => {
req.logout();
res.send(logged out);
})

app.listen(3000, () => {
console.log(Listening on 3000);
});

This code creates a web server using Express and enables user authentication using Passport. It sets up routes for registering, logging in, accessing user profiles, and logging out. Data is stored in a MongoDB database, allowing users to register, log in, view their profile, and log out securely.

Database Connection

First You need to install mongoDB inside Your Terminal

npm i mongoose

To Connect with Databse We write

const mongoose = require(mongoose);

exports.connectMongoose = () => {
mongoose.connect(mongodb://localhost:27017/Your Collection Name) //Write Your collection address here
.then((e) => console.log(`connected to mongodb: ${e.connection.host}`))
.catch((e) => console.log(e));
};

const userSchema = new mongoose.Schema({
name: String,

username: {
type: String,
required: true,
unique: true
},
password:String,
});

exports.User = mongoose.model(User, userSchema);

This code defines a module for connecting to a MongoDB database using Mongoose. It exports a function connectMongoose that connects to the MongoDB server at localhost:27017/passport. It also defines a User model with a schema containing fields for name, username (required and unique), and password.

Passport Config

In Passport Config It Checks where If user is Real or not.

const User = require(./database).User; // Import the User model directly
const LocalStrategy = require(passport-local).Strategy;

exports.initializingPassport = (passport) => {
passport.use(
new LocalStrategy(async (username, password, done) => {
try {
const user = await User.findOne({ username }); // Correct variable name

if (!user) return done(null, false);

if (user.password !== password) return done(null, false);

return done(null, user); // Authentication successful
} catch (error) {
return done(error, false);
}
})
);

passport.serializeUser((user, done) => {
done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (error) {
done(error, false);
}
});
};

// For accessing Own Account….
exports.isAuthenticated = (req, res, done) => {
if(req.user) return done();

res.redirect(/login);
}

This module sets up Passport for local authentication, allowing users to log in with a username and password.

It verifies user credentials by checking if the provided username exists in the database and if the password matches the stored password for that user.

If authentication is successful, it stores the user’s ID in the session to keep them logged in across requests.

It also includes middleware to ensure that users accessing certain routes are authenticated, redirecting them to the login page if they are not.

Create Basic Frontend Using Basic .ejs File

An EJS file is a template file used in web development to generate dynamic HTML content. “EJS” stands for Embedded JavaScript. It allows developers to embed JavaScript code directly into the HTML markup, making it easier to generate dynamic content based on data from the server or user interactions.

In simpler terms, an EJS file is like an HTML file with the added capability of including JavaScript code within it. This JavaScript code can be used to insert dynamic data, loop through arrays, conditionally show/hide content, and more. When the EJS file is rendered by the server, the JavaScript code is executed, and the resulting HTML is sent to the client’s browser for display.

register.ejs
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<meta name=viewport content=width=device-width, initial-scale=1.0>
<title>Document</title>
</head>
<body>
<form method=post>
<input type=text placeholder=Name name=name />
<input type=email placeholder=Email name=username />
<input type=password placeholder=Password name=password />
<button>Register</button>
</form>
</body>
</html>
login.ejs
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Document</title>
</head>
<body>
<form method=”post”>
<input type=”email” placeholder=”Email” name=”username” />
<input type=”password” placeholder=”Password” name=”password” />
<button>Login</button>
</form>
</body>
</html>
index.ejs
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Document</title>
</head>
<body>
<h2>Page 1</h2>

<a href=”/”>Home</a>
<a href=”/register”>Register</a>
<a href=”/login”>Login</a>

</body>
</html>

By this Following Code We Cand Easily Perforem Local Authentication.

THANK YOU

Leave a Reply

Your email address will not be published. Required fields are marked *