-
Notifications
You must be signed in to change notification settings - Fork 10.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: update the Passport.js example
- Loading branch information
1 parent
6ab2509
commit d943c3e
Showing
17 changed files
with
641 additions
and
156 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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}`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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}`); | ||
}); |
Oops, something went wrong.