Exchanging Public Keys with PubNub
Use PubNub Presence + State to exchange public keys.
by lw7360
HTML
<script src="http://cdn.pubnub.com/pubnub.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div class="jumbotron">
<h1>PubNub Key Exchange</h1>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="input-group"> <span class="input-group-addon">Username</span>
<input id="username" type="text" class="form-control" placeholder="'doge'">
</div>
</div>
<div class="col-md-6">
<div class="input-group"> <span class="input-group-addon">Public Key</span>
<input id="publicKey" type="text" class="form-control" placeholder="'much_security'">
</div>
</div>
<button id="login" type="button" class="btn btn-primary">Create User</button>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<table id="user_key" class="table table-hover">
<thead>
<tr>
<th><strong>#</strong>
</th>
<th><strong>Username</strong>
</th>
<th><strong>Public Key</strong>
</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="col-md-6">
<div id="here_now"> <pre>// pubnub.here_now() returns...</pre>
</div>
</div>
</div>
</div>
CSS
#login {
margin-top: 10px;
margin-left: 15px;
}
JavaScript
$("#login").click(function () {
$(this).focus(); // Focus on the "Create User" button.
var username = $("#username").val(); // Grab the Username
var publicKey = $("#publicKey").val(); // Grab the Public Key
// Make sure that something was entered for the Username and Public Key
if (username.length > 0 && publicKey.length > 0) {
// Initialize PubNub
var pubnub = PUBNUB.init({
publish_key: 'demo',
subscribe_key: 'demo',
uuid: username
});
// This function updates the table by calling here_now.
var updateTable = function () {
pubnub.here_now({
channel: 'doge_key_exchange',
state: true,
callback: function (m) {
$("#here_now").html("<pre>// pubnub.here_now() returns...<br><br>" + JSON.stringify(m, undefined, 2) + "</pre>"); // Prints the results of the `here_now` call.
var table = $("tbody");
table.empty();
var foundSelf = false;
var str = "";
for (var i = 0; i < m.uuids.length; i++) {
var state = m.uuids[i].state;
str += "<tr><td>" + (i + 1) + "</td><td>" + state.username + "</td><td>" + state.publicKey + "</td></tr>";
if (state.username === username && state.publicKey === publicKey) {
foundSelf = true;
$("#username").val("");
$("#publicKey").val("");
}
}
table.append(str);
if (!foundSelf) {
// If the results of our here_now call
// doesn't include ourself, try again.
updateTable();
}
}
});
};
pubnub.subscribe({
...