-
Notifications
You must be signed in to change notification settings - Fork 2
/
RoomCodeAuth.js
105 lines (94 loc) · 2.59 KB
/
RoomCodeAuth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const Passport = require("passport").Passport;
const LocalStrategy = require("passport-local").Strategy;
const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
var cors = require("cors");
let userId = 0;
module.exports = class RoomCodeAuth {
constructor() {
this.roomCode = process.env.SHARE_SPACE_ROOM_CODE || "share-space";
this.passport = new Passport();
this._configure();
}
_configure() {
this.passport.use(
new LocalStrategy(
{
usernameField: "username",
passwordField: "password",
session: true
},
(username, roomCode, done) => {
if (roomCode == this.roomCode) {
return done(null, { name: username, id: userId++ });
}
return done(null, false, { message: "Incorrect room code." });
}
)
);
this.passport.serializeUser((user, done) => {
done(null, user);
});
this.passport.deserializeUser((user, done) => {
done(null, user);
});
}
_getSession() {
if (!this.session) {
this.session = session({ secret: "share-space" });
}
return this.session;
}
checkAuth(request, callback) {
this._getSession()(request, {}, err => {
if (err) {
callback(err);
} else if (request.session.passport && request.session.passport.user) {
callback(null, request.session.passport.user);
} else {
callback(Error("User not authenticated"));
}
});
}
requireAuth() {
const router = express.Router();
// Issue session cookies at correct /login, else 401
router.post(
"/login",
cors({ origin: true, credentials: true }),
this.passport.authenticate("local", { session: true }),
(req, res) => {
console.log(`Authorized user: ${JSON.stringify(req.user)}`);
res.send(req.user);
}
);
// All other requests must be issued with a session cookie, which is
// loaded into req.user by passport.session(), else 401.
router.use("/", (req, res, next) => {
if (!req.user) {
res.sendStatus(401);
} else {
next();
}
});
// Add an endpoint to test the session cookie
router.get(
"/test",
cors({ origin: true, credentials: true }),
(req, res) => {
res.send("test\n");
console.log("test");
}
);
return router;
}
middleware() {
return [
this._getSession(),
bodyParser.urlencoded({ extended: false }),
this.passport.initialize(),
this.passport.session()
];
}
};