gpt4 book ai didi

java - Node.JS + Passport + MySQL + EasyRTC 身份验证

转载 作者:行者123 更新时间:2023-12-01 12:45:15 28 4
gpt4 key购买 nike

正如标题中提到的,我正在使用 Node.js + Passport.JS 和 MySQL.js。所有这些都已安装并且大部分工作正常,但我遇到了一些我无法解决的问题。

  1. 我的 profile.ejs 页面可以访问 user.x 变量,但我无法在大多数脚本中访问这些变量。我想将我的 easyrtcid 设置为登录用户的电子邮件地址。

  2. 目前 Passport session 似乎不起作用。可以使用相同的用户 ID 和密码从两个不同的浏览器登录。

配置文件.ejs

    <!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/easyrtc/easyrtc.css" />
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript" src="http://localhost:8080/easyrtc/easyrtc.js"></script>
<script type="text/javascript" src="E:/PortableApps/nodejs/app/config/demo_audio_video_simple.js"></script>
<script type="text/javascript" src="E:/PortableApps/nodejs/app/config/jquery-2.1.1.min.js"></script>

<style>
/* Header styles */

.row {
float:left;
position:relative;
width:250px;
text-align:center;
}
.well,
.hidden {
float:left;
position:relative;
padding:0 0 1em 0;
overflow:hidden;
}

#otherClients {
height:200px;
overflow-y:scroll;
}

#selfVideo {
height:225px;
width:300px;
float:left;
border:1px solid gray;
margin-left:10px;
}
#callerVideo {
height:225px;
width:300px;
border:1px solid gray;
margin-left:10px;
}

#well {
position:relative;
}
#connectControls {
float:left;
width:250px;
text-align:center;
}
/*#acceptCallBox {
display:none;
z-index:2;
position:absolute;
top:100px;
left:400px;
border:red solid 2px;
background-color:pink;
padding:15px;
}
</style>
<script>
//var socket = io.connect('http://localhost');
var selfEasyrtcid = "";
var haveSelfVideo = false;
//console.log(user);

// easyrtc.enableDebug(true);

// display globals in console
//for(var b in window) {
//if(window.hasOwnProperty(b)) console.log(b);
// }


function disable(domId) {
console.log("about to try disabling " + domId);
document.getElementById(domId).disabled = "disabled";
}


function enable(domId) {
console.log("about to try enabling " + domId);
document.getElementById(domId).disabled = "";
}


function connect() {
console.log("Initializing connection");
easyrtc.enableAudio(document.getElementById('shareAudio').checked);
easyrtc.enableVideo(document.getElementById('shareVideo').checked);
easyrtc.setRoomOccupantListener(convertListToButtons);
easyrtc.connect("easyrtc.audioVideo", loginSuccess, loginFailure);
console.log("connection complete");

}

function hangup() {
easyrtc.hangupAll();
disable('hangupButton');
console.log("hangup");
}


function clearConnectList() {
var otherClientDiv = document.getElementById('otherClients');
while (otherClientDiv.hasChildNodes()) {
otherClientDiv.removeChild(otherClientDiv.lastChild);
}
}

function convertListToButtons (roomName, data, isPrimary) {
console.log("convert list to buttons");
console.log(JSON.stringify(data));
console.dir(data);
clearConnectList();
var otherClientDiv = document.getElementById('otherClients');
for(var easyrtcid in data) {
var button = document.createElement('button');
button.onclick = function(easyrtcid) {
return function() {
performCall(easyrtcid);
};
}(easyrtcid);

var label = document.createTextNode(easyrtc.idToName(easyrtcid));
button.appendChild(label);
otherClientDiv.appendChild(button);
}
}

function setUpMirror() {
if( !haveSelfVideo) {
var selfVideo = document.getElementById("selfVideo");
easyrtc.setVideoObjectSrc(selfVideo, easyrtc.getLocalStream());
selfVideo.muted = true;
haveSelfVideo = true;
}
}

function performCall(otherEasyrtcid) {
easyrtc.hangupAll();
console.log("calling" + otherEasyrtcid);
var acceptedCB = function(accepted, easyrtcid) {
if( !accepted ) {
easyrtc.showError("CALL-REJECTED", "Sorry, your call to " + easyrtc.idToName(easyrtcid) + " was rejected");
enable('otherClients');
}
};

var successCB = function(easyrtcid) {
setUpMirror();
console.log("call accepted by " + easyrtc.idToName(easyrtcid));
enable('hangupButton');
};
var failureCB = function(otherEasyrtcid) {
console.log("call to " + easyrtc.idToName(otherEasyrtcid) + " failed:" + errMessage);
enable('otherClients');
};
easyrtc.call(otherEasyrtcid, successCB, failureCB, acceptedCB);
enable('hangupButton');
}

function loginSuccess(easyrtcid) {
console.log(easyrtcid);
selfEasyrtcid = easyrtcid;
disable("connectButton");
// enable("disconnectButton");
enable('otherClients');
// console.log(data);
document.getElementById("iam").innerHTML = "I am " + easyrtc.cleanId(easyrtcid);
}


function loginFailure(errorCode, message) {
easyrtc.showError(errorCode, message);
}

function disconnect() {
console.log("disconnect");
document.getElementById("iam").innerHTML = "logged out";
easyrtc.disconnect();
enable("connectButton");
// disable("disconnectButton");
clearConnectList();
easyrtc.setVideoObjectSrc(document.getElementById('selfVideo'), "");
}

easyrtc.setStreamAcceptor( function(easyrtcid, stream) {
setUpMirror();
var video = document.getElementById('callerVideo');
easyrtc.setVideoObjectSrc(video,stream);
console.log("saw video from " + easyrtcid);
enable("hangupButton");
});



easyrtc.setOnStreamClosed( function (easyrtcid) {
easyrtc.setVideoObjectSrc(document.getElementById('callerVideo'), "");
disable("hangupButton");
});


var callerPending = null;

easyrtc.setCallCancelled( function(easyrtcid){
if( easyrtcid === callerPending) {
document.getElementById('acceptCallBox').style.display = "none";
callerPending = false;
}
});


easyrtc.setAcceptChecker(function(easyrtcid, callback) {
document.getElementById('acceptCallBox').style.display = "block";
callerPending = easyrtcid;
if( easyrtc.getConnectionCount() > 0 ) {
console.log(easyrtcid + "has" + easyrtc.getConnectionCount() + " peer connections");
document.getElementById('acceptCallLabel').innerHTML = "Drop current call and accept new from " + easyrtc.idToName(easyrtcid) + " ?";
}
else {
document.getElementById('acceptCallLabel').innerHTML = "Accept incoming call from " + easyrtc.idToName(easyrtcid) + " ?";
}
var acceptTheCall = function(wasAccepted) {
document.getElementById('acceptCallBox').style.display = "none";
if( wasAccepted && easyrtc.getConnectionCount() > 0 ) {
easyrtc.hangupAll();
}
callback(wasAccepted);
callerPending = null;
};
document.getElementById("callAcceptButton").onclick = function() {
acceptTheCall(true);
};
document.getElementById("callRejectButton").onclick =function() {
acceptTheCall(false);
};
} );

</script>

</head>
<body>

<div class="container">

<div class="page-header text-center">
<h1><span class="fa fa-anchor"> </span> Profile Page</h1>
<a href="/logout" class="btn btn-default btn-sm">Logout</a>
</div>
<div class="row">

<!-- LOCAL INFORMATION -->
<div class="well">
<h3><span class="fa fa-user"> </span> Local</h3>

<div id="connectControls">
<input type="checkbox" checked="checked" id="shareAudio" />Share audio
<input type="checkbox" checked="checked" id="shareVideo" />Share video <br />
<button id="connectButton" onclick="connect()">Connect</button>
<button id="hangupButton" disabled="disabled" onclick="hangup()">Hangup</button>
<div id="iam">Not yet connected...</div>
<strong>id</strong>: <%= user.id %><br>
<strong>email</strong>: <%= user.email%><br>
<strong>password</strong>: <%= user.password %>
<br />
<strong>Connected users:</strong>
<div id="otherClients"> </div>
</div>

<div id="videos">
<video autoplay="autoplay" id="selfVideo" class="easyrtcMirror" muted="muted" volume="0"> </video>
<video autoplay="autoplay" id="callerVideo"> </video>
<div id="acceptCallBox"> <!-- Should be initially hidden using CSS -->
<div id="acceptCallLabel"> </div>
<button id="callAcceptButton" >Accept</button> <button id="callRejectButton">Reject</button>
</div>
</div>
<div id="hidden"> </div>
<!--hide-->
<br style="clear:both;" />
<hr />
</div>
</div>

</div>
</body>
</html>

Passport .js

    // config/passport.js

// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../models/user');
var mysql = require('mysql');
//Database connection details
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : ''
});

connection.query('USE nodejsmysql');
// expose this function to our app using module.exports
module.exports = function(passport) {

// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log("serialize");
done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function(id, done) {
console.log("deserialize");
connection.query("select * from users where id = "+id,function(err,rows){
done(err, rows[0]);

});
});

// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'

passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {

// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
connection.query("select * from users where email = '"+email+"'",function(err,rows){
// console.log(rows);

if (err) // error connecting to database
return done(err);
if (rows.length) { // user exists
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {

// if there is no user with that email
// create the user
var newUserMysql = new Object();

newUserMysql.email = email;
newUserMysql.password = password; // use the generateHash function in our user model

var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";

connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;

return done(null, newUserMysql);
});
}
});
}));

// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'

passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form

connection.query("select * from users where email = '"+email+"'",function(err,rows){


if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}

// if the user is found but the password is wrong
if (!( rows[0].password == password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

// all is well, return successful user

return done(null, rows[0]);

});
}));
};

最佳答案

我能够解决问题的第一部分。在 profile.ejs 上,我刚刚获取了元素的值并将其设置为 easyrtcid.username

element = document.getElementById('email');
var searchThis = element.textContent || element.innerText;
easyrtc.setUsername(searchThis);

现在,当用户登录时,他们将看到自己的用户名,而不是看到随机的 easyrtcID,并且每个其他用户将发送他们的用户名,因此,convertlisttobuttons() 现在还将显示已登录用户的电子邮件地址。

我仍然遇到第二个问题,但不知道如何继续。一旦用户登录,他们的 session 应该被锁定,并且其他人不应该能够使用该电子邮件/密码组合登录。我仍然需要这方面的帮助。

关于java - Node.JS + Passport + MySQL + EasyRTC 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24768269/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com