From e8ee7f381f8232142c351f73a7f806aef076c3ee Mon Sep 17 00:00:00 2001 From: Alexander Emelin Date: Sun, 20 Sep 2020 13:37:45 +0300 Subject: [PATCH] gin auth example improvements (#154) --- _examples/gin_auth/README.md | 2 +- _examples/gin_auth/chat.html | 68 +++++++----------------------------- _examples/gin_auth/main.go | 19 ++++++++++ 3 files changed, 33 insertions(+), 56 deletions(-) diff --git a/_examples/gin_auth/README.md b/_examples/gin_auth/README.md index eb40441c..5ec5cf54 100644 --- a/_examples/gin_auth/README.md +++ b/_examples/gin_auth/README.md @@ -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. diff --git a/_examples/gin_auth/chat.html b/_examples/gin_auth/chat.html index 2858d5ad..d76b2150 100644 --- a/_examples/gin_auth/chat.html +++ b/_examples/gin_auth/chat.html @@ -1,5 +1,5 @@ - + @@ -7,7 +7,6 @@ input[type="text"] { width: 300px; } - .muted { color: #CCCCCC; font-size: 10px; @@ -19,7 +18,7 @@ src="https://rawgit.com/centrifugal/centrifuge-js/master/dist/centrifuge.min.js"> diff --git a/_examples/gin_auth/main.go b/_examples/gin_auth/main.go index 7af11133..0c903210 100644 --- a/_examples/gin_auth/main.go +++ b/_examples/gin_auth/main.go @@ -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 @@ -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())