英文:
Dynamically change socket.io origins
问题
我正在运行使用SocketIo的Node应用程序,并在启动应用程序时创建套接字服务器。此时还指定了允许的域名列表。
app.js
async function listenCallback(server) {
try {
const domains = await db.raw('select distinct domain from users');
global.io = new SocketIo(server, domains);
} catch (err) {
server.close();
}
}
socket.js
class SocketIo {
constructor(server, domains) {
domains[0].map(row => {
whitelist.push(`https://${row.domain}:*`)
});
this.io = socketIo(server, {
origins: whitelist.join(' '),
secure: process.env.SSL_SERVER === 'true',
});
}
updateOrigins(domains) {
???
}
如何在服务器已经运行时动态更新来源(在updateOrigins中)?
英文:
I am running node app with SocketIo and creating sockets server when starting app. In this moment also list of allowed domains is specified.
app.js
async function listenCallback(server) {
try {
const domains = await db.raw('select distinct domain from users');
global.io = new SocketIo(server, domains);
} catch (err) {
server.close();
}
}
socket.js
class SocketIo {
constructor(server, domains) {
domains[0].map(row => {
whitelist.push(`https://${row.domain}:*`)
});
this.io = socketIo(server, {
origins: whitelist.join(' '),
secure: process.env.SSL_SERVER === 'true',
});
}
updateOrigins(domains) {
???
}
How can I update origins dynamically (in updateOrigins) when server is already running?
答案1
得分: 1
你可能想要查找每个连接的来源。类似这样的代码将在每次连接尝试时调用一个来源验证函数(未经调试)。也许对你有用?
io.origins( function (origin, callback) {
try {
const sql = db.format('select distinct domain from users where domain = ?', [origin])
db.query(sql, function (error, results, fields) {
if (error) {
console.error('error looking up origin in database', origin, error)
return callback('origin lookup failed', false)
}
/* if we got any rows back, we have an origin match */
if (results.length > 0) return callback(null, true)
return callback('origin not allowed', false)
})
}
catch (err) {
console.error('error looking up origin in database', origin, err)
return callback('origin lookup failed', false)
}
});
你可能想要实现某种来源缓存以避免过于频繁地重复数据库查找。
英文:
You may want to look up the origin on each connection. Something like this will call an origin validation function on each connection attempt (not debugged). Maybe it will work for you?
io.origins( function (origin, callback) {
try {
const sql = db.format ('select distinct domain from users where domain = ?', [origin])
db.query(sql, function (error, results, fields) {
if (error) {
console.error ('error looking up origin in database', origin, error)
return callback ('origin lookup failed', false)
}
/* if we got any rows back, we have an origin match */
if (results.length > 0) return callback (null, true)
return callback ('origin not allowed', false)
})
}
catch (err) {
console.error ('error looking up origin in database', origin, err)
return callback('origin lookup failed', false)
}
});
You may want to implement some sort of origin cache to avoid repeating the database lookups too often.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论