Skip to content

Commit

Permalink
gin auth example improvements (#154)
Browse files Browse the repository at this point in the history
  • Loading branch information
FZambia authored Sep 20, 2020
1 parent 6bc3e45 commit e8ee7f3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 56 deletions.
2 changes: 1 addition & 1 deletion _examples/gin_auth/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Example demonstrates simple chat with JSON protocol sharing session auth with [gin-gonic](https://github.com/gin-gonic/gin).
Example demonstrates a simple chat with JSON protocol sharing session auth with [gin-gonic](https://github.com/gin-gonic/gin).

Client uses Websocket by default, but you can simply uncomment one line in `chat.html` to use SockJS instead.

Expand Down
68 changes: 13 additions & 55 deletions _examples/gin_auth/chat.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
input[type="text"] {
width: 300px;
}

.muted {
color: #CCCCCC;
font-size: 10px;
Expand All @@ -19,7 +18,7 @@
src="https://rawgit.com/centrifugal/centrifuge-js/master/dist/centrifuge.min.js"></script>
<script type="text/javascript">
// helper functions to work with escaping html.
var tagsToReplace = {'&': '&amp;', '<': '&lt;', '>': '&gt;'};
const tagsToReplace = {'&': '&amp;', '<': '&lt;', '>': '&gt;'};

function replaceTag(tag) {
return tagsToReplace[tag] || tag;
Expand All @@ -29,27 +28,27 @@
return str.replace(/[&<>]/g, replaceTag);
}

var channel = "chat:index";
const channel = "chat:index";

function getParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

$(function () {
var input = $("#input");
var container = $('#messages');
var centrifuge = new Centrifuge('ws://localhost:8080/connection/websocket');
const input = $("#input");
const container = $('#messages');
const centrifuge = new Centrifuge('ws://localhost:8080/connection/websocket');
// var centrifuge = new Centrifuge('http://localhost:8080/connection/sockjs');
centrifuge.setConnectData({"user-agent": navigator.userAgent});
// bind listeners on centrifuge object instance events.
centrifuge.on('connect', function (ctx) {
drawText('Connected with client ID ' + ctx.client + ' over ' + ctx.transport + ' with data: ' + JSON.stringify(ctx.data));
drawText('Connected with client ID ' + ctx.client + ' over ' + ctx.transport + ' as user: ' + ctx.data.email);
input.attr("disabled", false);
});
centrifuge.on('message', function (data) {
Expand All @@ -62,43 +61,25 @@
input.attr("disabled", true);
});

// show how many users currently in channel.
function showPresence(sub) {
sub.presence().then(function (result) {
var count = 0;
for (var key in result.presence) {
count++;
}
drawText('Now in this room: ' + count + ' clients');
}, function (err) {
drawText("Presence error: " + JSON.stringify(err));
});
}

// subscribe on channel and bind various event listeners. Actual
// subscription request will be sent after client connects to
// a server.
var sub = centrifuge.subscribe(channel, handleMessage)
const sub = centrifuge.subscribe(channel, handleMessage)
.on("join", handleJoin)
.on("leave", handleLeave)
.on("unsubscribe", handleUnsubscribe)
.on("subscribe", handleSubscribe)
.on("error", handleSubscribeError);

showPresence(sub);

// Trigger actual connection establishing with a server.
// At this moment actual client work starts - i.e. subscriptions
// defined start subscribing etc.
centrifuge.connect();

function handleSubscribe(ctx) {
drawText('Subscribed on channel ' + ctx.channel + ' (resubscribed: ' + ctx.isResubscribe + ', recovered: ' + ctx.recovered + ')');
if (ctx.isResubscribe) {
showPresence(sub);
}
// This can be whatever JSON you want.
var rpcRequest = {"method": "getCurrentYear"}
const rpcRequest = {"method": "getCurrentYear"};
centrifuge.rpc(rpcRequest).then(function (data) {
drawText(JSON.stringify(data));
}, function (err) {
Expand All @@ -111,14 +92,14 @@
}

function handleMessage(message) {
var clientID;
let clientID;
if (message.info) {
clientID = message.info.client;
} else {
clientID = null;
}
var inputText = message.data["input"].toString();
var text = safeTagsReplace(inputText) + ' <span class="muted">from ' + clientID + '</span>';
const inputText = message.data["input"].toString();
const text = safeTagsReplace(inputText) + ' <span class="muted">from ' + clientID + '</span>';
drawText(text);
}

Expand Down Expand Up @@ -147,29 +128,6 @@
});
input.val('');
});
if (getParam("disconnect") == "1") {
function reconnect() {
setTimeout(function () {
centrifuge.disconnect();
setTimeout(function () {
reconnect();
}, 11000);
}, 4000);
}

reconnect();
}
if (getParam("publish") == "1") {
var publishInterval = parseInt(getParam("publishInterval")) || 1000;
var counter = 0
setInterval(function () {
sub.publish({"input": counter.toString()}).then(function () {
}, function (err) {
drawText("Publish error: " + JSON.stringify(err));
});
counter++;
}, publishInterval);
}
});
</script>
</head>
Expand Down
19 changes: 19 additions & 0 deletions _examples/gin_auth/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ func handleLog(e centrifuge.LogEntry) {
log.Printf("%s: %v", e.Message, e.Fields)
}

type connectData struct {
Email string `json:"email"`
}

type contextKey int

var ginContextKey contextKey
Expand Down Expand Up @@ -92,6 +96,21 @@ func main() {

node, _ := centrifuge.New(cfg)

node.OnConnecting(func(ctx context.Context, event centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) {
// Let's include user email into connect reply, so we can display user name in chat.
// This is an optional step actually.
cred, ok := centrifuge.GetCredentials(ctx)
if !ok {
return centrifuge.ConnectReply{}, centrifuge.DisconnectServerError
}
data, _ := json.Marshal(connectData{
Email: cred.UserID,
})
return centrifuge.ConnectReply{
Data: data,
}, nil
})

node.OnConnect(func(c *centrifuge.Client) {
transport := c.Transport()
log.Printf("user %s connected via %s.", c.UserID(), transport.Name())
Expand Down

0 comments on commit e8ee7f3

Please sign in to comment.