Skip to content

Commit

Permalink
docs: update the Passport.js example
Browse files Browse the repository at this point in the history
  • Loading branch information
darrachequesne committed Jan 12, 2024
1 parent 6ab2509 commit d943c3e
Show file tree
Hide file tree
Showing 17 changed files with 641 additions and 156 deletions.
2 changes: 2 additions & 0 deletions examples/passport-example/README.md
Expand Up @@ -5,6 +5,8 @@ This example shows how to retrieve the authentication context from a basic [Expr

![Passport example](assets/passport_example.gif)

Please read the related guide: https://socket.io/how-to/use-with-passport

## How to use

```
Expand Down
55 changes: 55 additions & 0 deletions examples/passport-example/cjs/index.html
@@ -0,0 +1,55 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Passport example</title>
</head>
<body>
<p>Authenticated!</p>

<table>
<tbody>
<tr>
<td>Status</td>
<td><span id="status">Disconnected</span></td>
</tr>
<tr>
<td>Socket ID</td>
<td><span id="socket-id"></span></td>
</tr>
<tr>
<td>Username</td>
<td><span id="username"></span></td>
</tr>
</tbody>
</table>

<form action="/logout" method="post">
<div>
<input type="submit" value="Log out" />
</div>
</form>

<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const socketIdSpan = document.getElementById('socket-id');
const usernameSpan = document.getElementById('username');
const statusSpan = document.getElementById('status');

socket.on('connect', () => {
statusSpan.innerText = 'connected';
socketIdSpan.innerText = socket.id;

socket.emit('whoami', (username) => {
usernameSpan.innerText = username;
});
});

socket.on('disconnect', () => {
statusSpan.innerText = 'disconnected';
socketIdSpan.innerText = '-';
});
</script>
</body>
</html>
109 changes: 109 additions & 0 deletions examples/passport-example/cjs/index.js
@@ -0,0 +1,109 @@
const express = require("express");
const { createServer } = require("node:http");
const { Server } = require("socket.io");
const session = require("express-session");
const bodyParser = require("body-parser");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const { join } = require("node:path");

const port = process.env.PORT || 3000;

const app = express();
const httpServer = createServer(app);

const sessionMiddleware = session({
secret: "changeit",
resave: true,
saveUninitialized: true,
});

app.use(sessionMiddleware);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());

app.get("/", (req, res) => {
if (!req.user) {
return res.redirect("/login");
}
res.sendFile(join(__dirname, "index.html"));
});

app.get("/login", (req, res) => {
if (req.user) {
return res.redirect("/");
}
res.sendFile(join(__dirname, "login.html"));
});

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

app.post("/logout", (req, res) => {
const sessionId = req.session.id;
req.session.destroy(() => {
// disconnect all Socket.IO connections linked to this session ID
io.to(`session:${sessionId}`).disconnectSockets();
res.status(204).end();
});
});

passport.use(
new LocalStrategy((username, password, done) => {
if (username === "john" && password === "changeit") {
console.log("authentication OK");
return done(null, { id: 1, username });
} else {
console.log("wrong credentials");
return done(null, false);
}
}),
);

passport.serializeUser((user, cb) => {
console.log(`serializeUser ${user.id}`);
cb(null, user);
});

passport.deserializeUser((user, cb) => {
console.log(`deserializeUser ${user.id}`);
cb(null, user);
});

const io = new Server(httpServer);

io.engine.use(sessionMiddleware);
io.engine.use(passport.initialize());
io.engine.use(passport.session());

io.engine.use(
(req, res, next) => {
if (req.user) {
next();
} else {
res.writeHead(401);
res.end();
}
},
);

io.on("connection", (socket) => {
const req = socket.request;

socket.join(`session:${req.session.id}`);
socket.join(`user:${req.user.id}`);

socket.on("whoami", (cb) => {
cb(req.user.username);
});
});

httpServer.listen(port, () => {
console.log(`application is running at: http://localhost:${port}`);
});
Expand Up @@ -8,17 +8,17 @@
<p>Not authenticated</p>
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username" />
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
<br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password" />
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
</html>
20 changes: 20 additions & 0 deletions examples/passport-example/cjs/package.json
@@ -0,0 +1,20 @@
{
"name": "passport-example",
"version": "0.0.1",
"private": true,
"type": "commonjs",
"description": "Example with passport (https://www.passportjs.org)",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "~4.17.3",
"express-session": "~1.17.2",
"passport": "^0.7.0",
"passport-local": "^1.0.0",
"socket.io": "^4.7.2"
},
"devDependencies": {
"prettier": "^3.1.1"
}
}
55 changes: 55 additions & 0 deletions examples/passport-example/esm/index.html
@@ -0,0 +1,55 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Passport example</title>
</head>
<body>
<p>Authenticated!</p>

<table>
<tbody>
<tr>
<td>Status</td>
<td><span id="status">Disconnected</span></td>
</tr>
<tr>
<td>Socket ID</td>
<td><span id="socket-id"></span></td>
</tr>
<tr>
<td>Username</td>
<td><span id="username"></span></td>
</tr>
</tbody>
</table>

<form action="/logout" method="post">
<div>
<input type="submit" value="Log out" />
</div>
</form>

<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const socketIdSpan = document.getElementById('socket-id');
const usernameSpan = document.getElementById('username');
const statusSpan = document.getElementById('status');

socket.on('connect', () => {
statusSpan.innerText = 'connected';
socketIdSpan.innerText = socket.id;

socket.emit('whoami', (username) => {
usernameSpan.innerText = username;
});
});

socket.on('disconnect', () => {
statusSpan.innerText = 'disconnected';
socketIdSpan.innerText = '-';
});
</script>
</body>
</html>
112 changes: 112 additions & 0 deletions examples/passport-example/esm/index.js
@@ -0,0 +1,112 @@
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import session from "express-session";
import bodyParser from "body-parser";
import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const port = process.env.PORT || 3000;

const app = express();
const httpServer = createServer(app);

const sessionMiddleware = session({
secret: "changeit",
resave: true,
saveUninitialized: true,
});

app.use(sessionMiddleware);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());

const __dirname = dirname(fileURLToPath(import.meta.url));

app.get("/", (req, res) => {
if (!req.user) {
return res.redirect("/login");
}
res.sendFile(join(__dirname, "index.html"));
});

app.get("/login", (req, res) => {
if (req.user) {
return res.redirect("/");
}
res.sendFile(join(__dirname, "login.html"));
});

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

app.post("/logout", (req, res) => {
const sessionId = req.session.id;
req.session.destroy(() => {
// disconnect all Socket.IO connections linked to this session ID
io.to(`session:${sessionId}`).disconnectSockets();
res.status(204).end();
});
});

passport.use(
new LocalStrategy((username, password, done) => {
if (username === "john" && password === "changeit") {
console.log("authentication OK");
return done(null, { id: 1, username });
} else {
console.log("wrong credentials");
return done(null, false);
}
}),
);

passport.serializeUser((user, cb) => {
console.log(`serializeUser ${user.id}`);
cb(null, user);
});

passport.deserializeUser((user, cb) => {
console.log(`deserializeUser ${user.id}`);
cb(null, user);
});

const io = new Server(httpServer);

io.engine.use(sessionMiddleware);
io.engine.use(passport.initialize());
io.engine.use(passport.session());

io.engine.use(
(req, res, next) => {
if (req.user) {
next();
} else {
res.writeHead(401);
res.end();
}
},
);

io.on("connection", (socket) => {
const req = socket.request;

socket.join(`session:${req.session.id}`);
socket.join(`user:${req.user.id}`);

socket.on("whoami", (cb) => {
cb(req.user.username);
});
});

httpServer.listen(port, () => {
console.log(`application is running at: http://localhost:${port}`);
});

0 comments on commit d943c3e

Please sign in to comment.