I'm developing an AngularJS webapp that can be opened in different tabs, I would like to know which is the best way to detect when the user logs-out in one of these tabs; I'd like to popup a login modal window in the other tabs. I was thinking to use a server-sent event or track the existence of my server cookie. I never done something like this, so I'm asking what are the pros and cons about my options or if I missing some other smarter way to do it.
EDIT: on the server I've got ServiceStack (C#) that supports Server-Sent Events out of the box
As you're using ServiceStack's Server Events you can just send a notification when a user logs out.
First you need to detect the User has logged out by implementing the OnLogout Session or Auth Event, e.g:
public class MyAuthEvents : AuthEvents
{
public IServerEvents ServerEvents { get; set; }
public override void OnLogout(IRequest httpReq,
IAuthSession session, IServiceBase authService)
{
var channel = "home"; //replace with channel tabs are subscribed to
var msg = "...";
ServerEvents.NotifyUserId(session.UserAuthId, "cmd.logout", msg, channel);
}
}
Notifying by UserId will send the notification to different tabs as well as browsers where the user is logged in. If you only want to send notifications to all tabs in just the 1 browser you can use the NotifySession(session.Id)
API instead.
To register your AuthEvents Handler with ServiceStack you just need to register it in the IOC, e.g:
container.RegisterAs<MyAuthEvents, IAuthEvents>();
Then handle the cmd.logout notification in your JavaScript ServerEvents Client, e.g:
$(source).handleServerEvents({
handlers: {
logout: function (msg) {
//Show AngularJS dialog
$mdDialog.alert({
title: 'Attention',
textContent: msg,
ok: 'Close'
});
},
//... Other custom handlers
}
});
Server sent events is pretty good way to handle this. Event based handling is good because it saves resources unlike other methods like (checking the existence of cookies), or constant polling of data, or heartbeat type of thing. So any method where server can message the client app to work on something(in your case popup a modal informing the logged out session) will do the best. You can also use socket.io which is well designed and can do this easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With