我需要从编码的connect.sid cookie中获取会话ID。我需要在server.js的路由之外执行此操作,以在将用户连接到其请求的房间之前验证用户。现在,cookie如下所示:
cookie: 'io=YB0puaz8_Fr5RN4qAAAA; connect.sid=s%3Awew35upI6SzKaNbrmHlgJZPB3085Vcx9.OYZ014EDbjHVQK7u8qgkNvkDzzn5jhwi2HOjhfRVMqw'
如何从该connect.sid获取用户ID?它看起来不像会话集合存储此。这是 存储的加密用户ID吗?如果可以,该如何解密?
我不确定是否应该为此使用cookie解析器。我已经尝试了一些功能,但是看起来它主要用作中间件。您可能还会注意到我有两次app.use(session({}))。由于某种原因,如果我删除第一个,则无法登录。这是一些非常混乱的代码。我很抱歉。
我将会话存储在connect-mongo中。这是我的server.js
:
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const MongoStore = require('connect-mongo')(session);
const SessionStorage = require('./models/Session');
//Middleware authentication function
const { ensureAuthenticated } = require('./config/auth');
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = require('socket.io').listen(server);
//Passport Config
require('./config/passport')(passport);
//Load environment variables
require('dotenv').config();
//Database configuration
const db = process.env.DB;
//Connect to database
mongoose.connect(db, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
//Bodyparser for incoming requests
app.use(express.urlencoded({ extended: true }));
// Express session
app.use(
session({
// store: new MongoStore({ mongooseConnection: mongoose.connection}),
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: 10 * 60 * 1000
},
rolling: true
})
);
const sessionMiddleware = session({
store: new MongoStore({ mongooseConnection: mongoose.connection}),
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
rolling: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: 10 * 60 * 1000
}
});
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
app.use(sessionMiddleware);
io.use((socket, next) => {
sessionMiddleware(socket.request, {}, next);
});
//Socket Integration
io.on('connection', socket => {
socket.use((packet, next) => {
const handshake = socket.request;
if (handshake.headers.cookie){
//Sometimes session connect comes first but the pair will always be side by side
const credentialsArr = handshake.headers.cookie.replace(";", '').replace(/\=/g,' ').split(" ");
//Throwin that deuce into an object
const credentials = {};
let key = credentialsArr[0];
credentials[key] = credentialsArr[1];
//Sometimes theres only an io cookie and no session cookie
//This prevents an entry in the credentials obj being 'undefined: undefined'
if (credentialsArr.length > 2){
key = credentialsArr[2];
credentials[key] = credentialsArr[3];
}
//Make sure this session exists before hitting DB
if (!credentials['connect.sid']) next(new Error('Please log in again.'));
if (packet.sessioncookie) return next();
next(new Error('Please log in.'))
});
socket.on('subscribe', room => {
//TO DO
//Make sure user is in requested group
//Make sure group exists!
socket.join(room);
console.log(`User joined room: ${room}`);
});
socket.on('disconnect', room => {
socket.leave(room);
console.log(`User diconnected`);
});
console.log('User connected!');
});
const PORT = process.env.PORT || 7575;
server.listen(PORT, console.log(`Server started on port ${PORT}`));```