-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmanager.go
191 lines (161 loc) · 4.35 KB
/
manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
var (
/**
websocketUpgrader is used to upgrade incomming HTTP requests into a persitent websocket connection
*/
websocketUpgrader = websocket.Upgrader{
// Apply the Origin Checker
CheckOrigin: checkOrigin,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
var (
ErrEventNotSupported = errors.New("this event type is not supported")
)
// checkOrigin will check origin and return true if its allowed
func checkOrigin(r *http.Request) bool {
// Grab the request origin
origin := r.Header.Get("Origin")
switch origin {
// Update this to HTTPS
case "https://localhost:8080":
return true
default:
return false
}
}
// Manager is used to hold references to all Clients Registered, and Broadcasting etc
type Manager struct {
clients ClientList
// Using a syncMutex here to be able to lcok state before editing clients
// Could also use Channels to block
sync.RWMutex
// handlers are functions that are used to handle Events
handlers map[string]EventHandler
// otps is a map of allowed OTP to accept connections from
otps RetentionMap
}
// NewManager is used to initalize all the values inside the manager
func NewManager(ctx context.Context) *Manager {
m := &Manager{
clients: make(ClientList),
handlers: make(map[string]EventHandler),
// Create a new retentionMap that removes Otps older than 5 seconds
otps: NewRetentionMap(ctx, 5*time.Second),
}
m.setupEventHandlers()
return m
}
// setupEventHandlers configures and adds all handlers
func (m *Manager) setupEventHandlers() {
m.handlers[EventSendMessage] = SendMessageHandler
m.handlers[EventChangeRoom] = ChatRoomHandler
}
// routeEvent is used to make sure the correct event goes into the correct handler
func (m *Manager) routeEvent(event Event, c *Client) error {
// Check if Handler is present in Map
if handler, ok := m.handlers[event.Type]; ok {
// Execute the handler and return any err
if err := handler(event, c); err != nil {
return err
}
return nil
} else {
return ErrEventNotSupported
}
}
// loginHandler is used to verify an user authentication and return a one time password
func (m *Manager) loginHandler(w http.ResponseWriter, r *http.Request) {
type userLoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
var req userLoginRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Authenticate user / Verify Access token, what ever auth method you use
if req.Username == "percy" && req.Password == "123" {
// format to return otp in to the frontend
type response struct {
OTP string `json:"otp"`
}
// add a new OTP
otp := m.otps.NewOTP()
resp := response{
OTP: otp.Key,
}
data, err := json.Marshal(resp)
if err != nil {
log.Println(err)
return
}
// Return a response to the Authenticated user with the OTP
w.WriteHeader(http.StatusOK)
w.Write(data)
return
}
// Failure to auth
w.WriteHeader(http.StatusUnauthorized)
}
// serveWS is a HTTP Handler that the has the Manager that allows connections
func (m *Manager) serveWS(w http.ResponseWriter, r *http.Request) {
// Grab the OTP in the Get param
otp := r.URL.Query().Get("otp")
if otp == "" {
// Tell the user its not authorized
w.WriteHeader(http.StatusUnauthorized)
return
}
// Verify OTP is existing
if !m.otps.VerifyOTP(otp) {
w.WriteHeader(http.StatusUnauthorized)
return
}
log.Println("New connection")
// Begin by upgrading the HTTP request
conn, err := websocketUpgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
// Create New Client
client := NewClient(conn, m)
// Add the newly created client to the manager
m.addClient(client)
go client.readMessages()
go client.writeMessages()
}
// addClient will add clients to our clientList
func (m *Manager) addClient(client *Client) {
// Lock so we can manipulate
m.Lock()
defer m.Unlock()
// Add Client
m.clients[client] = true
}
// removeClient will remove the client and clean up
func (m *Manager) removeClient(client *Client) {
m.Lock()
defer m.Unlock()
// Check if Client exists, then delete it
if _, ok := m.clients[client]; ok {
// close connection
client.connection.Close()
// remove
delete(m.clients, client)
}
}