use websockets to logout remote users
This commit is contained in:
		@ -119,6 +119,8 @@ func main() {
 | 
			
		||||
		Session:       session,
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	go app.ListenToWsChannel()
 | 
			
		||||
 | 
			
		||||
	app.infoLog.Println("Connected to MariaDB")
 | 
			
		||||
 | 
			
		||||
	err = app.serve()
 | 
			
		||||
 | 
			
		||||
@ -12,6 +12,8 @@ func (app *application) routes() http.Handler {
 | 
			
		||||
 | 
			
		||||
	mux.Get("/", app.Home)
 | 
			
		||||
 | 
			
		||||
	mux.Get("/ws", app.WsEndPoint)
 | 
			
		||||
 | 
			
		||||
	mux.Route("/admin", func(mux chi.Router) {
 | 
			
		||||
		mux.Use(app.Auth)
 | 
			
		||||
		mux.Get("/virtual-terminal", app.VirtualTerminal)
 | 
			
		||||
 | 
			
		||||
@ -105,7 +105,12 @@
 | 
			
		||||
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
 | 
			
		||||
                integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
 | 
			
		||||
                crossorigin="anonymous"></script>
 | 
			
		||||
        <script src="/static/js/base.js"></script>
 | 
			
		||||
        <script type="module">
 | 
			
		||||
            import {wsConn, socket} from "/static/js/base.js"
 | 
			
		||||
            document.addEventListener("DOMContentLoaded", function() {
 | 
			
		||||
                wsConn({{.IsAuthenticated}}, {{.UserID}});
 | 
			
		||||
            });
 | 
			
		||||
        </script>
 | 
			
		||||
        {{ block "js" . }}
 | 
			
		||||
        {{ end }}
 | 
			
		||||
    </body>
 | 
			
		||||
 | 
			
		||||
							
								
								
									
										109
									
								
								cmd/web/ws-handlers.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										109
									
								
								cmd/web/ws-handlers.go
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,109 @@
 | 
			
		||||
package main
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"net/http"
 | 
			
		||||
 | 
			
		||||
	"github.com/gorilla/websocket"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type WebSocketConnection struct {
 | 
			
		||||
	*websocket.Conn
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type WsPayload struct {
 | 
			
		||||
	Action      string              `json:"action"`
 | 
			
		||||
	Message     string              `json:"message"`
 | 
			
		||||
	UserName    string              `json:"user_name"`
 | 
			
		||||
	MessageType string              `json:"message_type"`
 | 
			
		||||
	UserID      int                 `json:"user_id"`
 | 
			
		||||
	Conn        WebSocketConnection `json:"-"`
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type WsJSONResponse struct {
 | 
			
		||||
	Action  string `json:"action"`
 | 
			
		||||
	Message string `json:"message"`
 | 
			
		||||
	UserID  int    `json:"user_id"`
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
var upgradeConnection = websocket.Upgrader{
 | 
			
		||||
	ReadBufferSize:  1024,
 | 
			
		||||
	WriteBufferSize: 1024,
 | 
			
		||||
	// since we don't expect any communication from the client side
 | 
			
		||||
	CheckOrigin: func(r *http.Request) bool { return true },
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
var clients = make(map[WebSocketConnection]string)
 | 
			
		||||
 | 
			
		||||
var wsChan = make(chan WsPayload)
 | 
			
		||||
 | 
			
		||||
func (app *application) WsEndPoint(w http.ResponseWriter, r *http.Request) {
 | 
			
		||||
	ws, err := upgradeConnection.Upgrade(w, r, nil)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		app.errorLog.Println(err)
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	app.infoLog.Printf("Client connected from %s\n", r.RemoteAddr)
 | 
			
		||||
	var response WsJSONResponse
 | 
			
		||||
	response.Message = "Connected to server"
 | 
			
		||||
 | 
			
		||||
	err = ws.WriteJSON(response)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		app.errorLog.Println(err)
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	conn := WebSocketConnection{Conn: ws}
 | 
			
		||||
	clients[conn] = ""
 | 
			
		||||
 | 
			
		||||
	go app.ListenForWS(&conn)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (app *application) ListenForWS(conn *WebSocketConnection) {
 | 
			
		||||
	defer func() {
 | 
			
		||||
		if r := recover(); r != nil {
 | 
			
		||||
			app.errorLog.Println("ERROR:", fmt.Sprintf("%v", r))
 | 
			
		||||
		}
 | 
			
		||||
	}()
 | 
			
		||||
 | 
			
		||||
	var payload WsPayload
 | 
			
		||||
 | 
			
		||||
	for {
 | 
			
		||||
		err := conn.ReadJSON(&payload)
 | 
			
		||||
		if err != nil {
 | 
			
		||||
			// do nothing
 | 
			
		||||
			app.errorLog.Println(err)
 | 
			
		||||
			break
 | 
			
		||||
		}
 | 
			
		||||
		payload.Conn = *conn
 | 
			
		||||
		wsChan <- payload
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (app *application) ListenToWsChannel() {
 | 
			
		||||
	var response WsJSONResponse
 | 
			
		||||
	for {
 | 
			
		||||
		e := <-wsChan
 | 
			
		||||
		switch e.Action {
 | 
			
		||||
		case "deleteUser":
 | 
			
		||||
			response.Action = "logout"
 | 
			
		||||
			response.Message = "Your account has ben deleted"
 | 
			
		||||
			response.UserID = e.UserID
 | 
			
		||||
			app.broadcastToAll(response)
 | 
			
		||||
		default:
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (app *application) broadcastToAll(response WsJSONResponse) {
 | 
			
		||||
	for client := range clients {
 | 
			
		||||
		// broadcast to every connected client
 | 
			
		||||
		err := client.WriteJSON(response)
 | 
			
		||||
		if err != nil {
 | 
			
		||||
			app.errorLog.Printf("Websocket err on %s: %s", response.Action, err)
 | 
			
		||||
			_ = client.Close()
 | 
			
		||||
			delete(clients, client)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user