0% found this document useful (0 votes)
9 views5 pages

Experiment 3

This document provides step-by-step instructions for implementing session management and user authentication using Express.js. It includes code examples for setting up sessions with cookies, handling user registration, and login functionality with password hashing using bcrypt. The instructions guide users through initializing a project, installing dependencies, and running the application locally.
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)
9 views5 pages

Experiment 3

This document provides step-by-step instructions for implementing session management and user authentication using Express.js. It includes code examples for setting up sessions with cookies, handling user registration, and login functionality with password hashing using bcrypt. The instructions guide users through initializing a project, installing dependencies, and running the application locally.
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/ 5

3.

Express JS-Cookies, Sessions, Authentication

a. Write a program for session management using cookies and sessions

Step-1:

Open VS Code and open (or create) your project folder

Step-2:

Open integrated terminal

• The terminal opens at your project folder path.

Step-3:

Initialize npm and install dependencies

Run these commands in the terminal:

• npm init -y
• npm install express express-session

Step-4:

• In VS Code explorer, click New File.


• Name it app.js.
• Paste the following code inside app.js:

const express = require('express');


const session = require('express-session');

const app = express();


const port = 3000;

app.use(session({
secret: 'mySecretKey123',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));

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

app.get('/', (req, res) => {


if (req.session.views) {
req.session.views++;
res.send(`<h1>Session Demo</h1>
<p>You visited this page ${req.session.views} times.</p>
<p><a href="/logout">Logout</a></p>`);
} else {
req.session.views = 1;
res.send(`<h1>Welcome! This is your first visit.</h1>
<p><a href="/">Refresh</a> | <a href="/logout">Logout</a></p>`);
}
});

app.get('/logout', (req, res) => {


req.session.destroy(err => {
if (err) {
return res.send('Error logging out');
}
res.clearCookie('connect.sid');
res.send('<h1>Logged out</h1><p><a href="/">Login again</a></p>');
});
});

app.listen(port, () => {
console.log(`Server started on http://localhost:${port}`);
});

Step-5:

In the terminal inside VS Code, run:

• node app.js

You should see:

• Server started on http://localhost:3000

Step-6:

Open your browser and visit:

http://localhost:3000

Output:
b. write a program for user authentication

Step-1:

Open VS Code and open (or create) your project folder

Step-2:

Open integrated terminal

• The terminal opens at your project folder path.

Step-3:

Initialize npm and install dependencies

Run these commands in the terminal:

• npm init -y
• npm install express express-session
• npm install bcryptjs

Step-4:

• In VS Code explorer, click New File.


• Name it app.js.
• Paste the following code inside app.js:

const express = require('express');


const session = require('express-session');
const bcrypt = require('bcrypt');

const app = express();


const port = 3000;

const users = [];

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

app.use(session({
secret: 'secretKey123',
resave: false,
saveUninitialized: false,
}));

function isAuthenticated(req, res, next) {


if (req.session.userId) {
next();
} else {
res.redirect('/login');
}
}
app.get('/', (req, res) => {
if (req.session.userId) {
res.send(`
<h1>Welcome user!</h1>
<p><a href="/protected">Go to protected page</a></p>
<p><a href="/logout">Logout</a></p>
`);
} else {
res.send(`
<h1>Home</h1>
<p><a href="/login">Login</a> | <a href="/register">Register</a></p>
`);
}
});

app.get('/register', (req, res) => {


res.send(`
<h1>Register</h1>
<form method="POST" action="/register">
<input name="username" placeholder="Username" required /><br/>
<input name="password" type="password" placeholder="Password" required
/><br/>
<button type="submit">Register</button>
</form>
<p><a href="/">Home</a></p>
`);
});

app.post('/register', async (req, res) => {


const { username, password } = req.body;
if (users.find(u => u.username === username)) {
return res.send('User already exists. <a href="/register">Try again</a>');
}
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.send('Registration successful! <a href="/login">Login now</a>');
});

app.get('/login', (req, res) => {


res.send(`
<h1>Login</h1>
<form method="POST" action="/login">
<input name="username" placeholder="Username" required /><br/>
<input name="password" type="password" placeholder="Password" required
/><br/>
<button type="submit">Login</button>
</form>
<p><a href="/">Home</a></p>
`);
});

app.post('/login', async (req, res) => {


const { username, password } = req.body;
Output:

You might also like