我的问题是如何通过快递把手获取用户名val来查看。 在这个聊天应用程序中,用户名可以在HTML代码中访问,它可以更改。如果有人更改了h4标签内容的用户名(从John Doe到Doe John),它会影响所有客户端。我也使用express-session和mongostore来存储会话,我知道我无法访问会话而无需req。那么你提出的解决这个问题的方法是什么?(访问会议)先谢谢。
那是客户端
<h4 id="username">{{username}}</h4>
<div class="chat">
<ul class="chat-box"></ul>
</div>
<div class="chat-user">
<form io="form-chat" class="form-inline">
<div class="form-group">
<input type="text" class="form-controll" id="text-chat" name="text-chat" value="">
</div>
<button>send`enter code here`</button>
</form>
服务器端
function socket(io) {
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
console.log(splitUsername[0]);*/
io.emit('chat message', msg);
});
});
}
module.exports = socket;
答案 0 :(得分:2)
永远不要相信客户(在服务器端存储重要变量,而不是依赖客户端)
在能够使用聊天功能之前,我会进行简单验证(选择用户名)协议。
in1 <- mx.symbol.Variable("data1") # 7 values
in2 <- mx.symbol.Variable("data2") # 7 values
客户在验证用户名之前无法使用聊天(套接字&#34;输入&#34;事件)
如果您担心安全性,还应该清理/转义客户端的消息。 示例:发送以下消息(const _onlineUsernames = {};
const MAX_USERNAME_LENGTH = 16;
io.on('connection', function(socket) {
//.: Login (Pick Username)
socket.on('enter',function(username){
if(username){ //did we really receive a username?
if(username.length!=0 && username.length<=MAX_USERNAME_LENGTH){
if(!_onlineUsernames[username]){
//username not in use, add to online list & verify :
_onlineUsernames[username] = {sid:socket.id};
socket.chat_verified = true; //used to verify username has been picked
socket.chat_username = username; //store in the socket
}else{socket.emit('error', 'username currently in use');}
}else{socket.emit('error', 'length of username supplied');}
}else{socket.emit('error', 'no username supplied');}
});
//.: Chat Logic
socket.on('chat message', function(msg) {
if(socket.chat_verified){ // Check if the user is verified (previously picked username)
console.log(socket.chat_username);
// Here, I would do some escaping/sanitation before emiting the message,
// mainly to prevent client-to-client injection (sanitation/escaping can be done in the client-side instead)
io.emit('chat message', msg);
}else{ socket.emit('error', 'chat_verification_required'); }
});
//.: Login (Pick Username)
socket.on('disconnect',function(){
// Check if disconnected user was verified (picked username)
if(socket.chat_verified){ delete _onlineUsernames[socket.chat_username]; }//username is free to be used again
});
});
)
编辑:(问题专门询问从套接字访问会话)
使用 express-session-socket.io 中间件在socket.io中公开快速会话对象(类似于我在套接字中存储用户名所做的操作)
代码示例:简单(因为您可能已经定义了sessionStore)
<script>alert('injected js!);</script>