Send alerts to connected socket instance when token is expired

This commit is contained in:
Dane Everitt 2019-09-24 22:05:34 -07:00
parent 6930ae816d
commit 71d5b0fe83
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53

View File

@ -17,6 +17,8 @@ import (
)
const (
TokenExpiringEvent = "token expiring"
TokenExpiredEvent = "token expired"
SetStateEvent = "set state"
SendServerLogsEvent = "send logs"
SendCommandEvent = "send command"
@ -143,7 +145,19 @@ func (rt *Router) routeWebsocket(w http.ResponseWriter, r *http.Request, ps http
zap.S().Error(err)
return
}
defer c.Close()
// Make a ticker and completion channel that is used to continuously poll the
// JWT stored in the session to send events to the socket when it is expiring.
ticker := time.NewTicker(time.Second * 30)
done := make(chan bool)
// Whenever this function is complete, end the ticker, close out the channel,
// and then close the websocket connection.
defer func() {
ticker.Stop()
done <- true
c.Close()
}()
s := rt.Servers.Get(ps.ByName("server"))
handler := WebsocketHandler{
@ -185,6 +199,29 @@ func (rt *Router) routeWebsocket(w http.ResponseWriter, r *http.Request, ps http
s.Emit(server.StatusEvent, s.State)
// Sit here and check the time to expiration on the JWT every 30 seconds until
// the token has expired. If we are within 3 minutes of the token expiring, send
// a notice over the socket that it is expiring soon. If it has expired, send that
// notice as well.
go func() {
for {
select {
case <-done:
return
case <-ticker.C:
{
if handler.JWT != nil {
if handler.JWT.ExpirationTime.Unix()-time.Now().Unix() <= 0 {
handler.SendJson(&WebsocketMessage{Event: TokenExpiredEvent})
} else if handler.JWT.ExpirationTime.Unix()-time.Now().Unix() <= 180 {
handler.SendJson(&WebsocketMessage{Event: TokenExpiringEvent})
}
}
}
}
}
}()
for {
j := WebsocketMessage{inbound: true}