func chatHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { cookieToken, _ := r.Cookie("token") token := auth.NewUserToken() token.FromString(cookieToken.Value) chatToken, err := auth.MakeChatToken(db, token) if err != nil { internalServerError(w, err) return } var c http.Cookie c.Name = "chat_token" c.Value = chatToken.String() c.Secure = true http.SetCookie(w, &c) http.ServeFile(w, r, root+"/index.html") }
func defaultHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { cookieToken, err := r.Cookie("token") if err != nil { if err == http.ErrNoCookie { http.Redirect(w, r, "/auth", http.StatusSeeOther) return } internalServerError(w, err) return } token := auth.NewUserToken() err = token.FromString(cookieToken.Value) if err == nil { err = auth.CheckUserToken(db, token) } if err != nil { if _, ok := err.(auth.AuthError); ok { var c http.Cookie c.Name = "token" c.MaxAge = -1 c.Secure = true c.HttpOnly = true http.SetCookie(w, &c) http.Redirect(w, r, "/", http.StatusSeeOther) return } internalServerError(w, err) return } if r.URL.Path != "/" { http.Redirect(w, r, "/", http.StatusSeeOther) return } chatHandler(w, r, db) }
func (s *Server) Listen(db *sql.DB) { log.Println("Listening server...") s.db = db // websocket handler onConnected := func(ws *websocket.Conn) { defer func() { err := ws.Close() if err != nil { s.errCh <- err } }() var encodedToken string err := websocket.Message.Receive(ws, &encodedToken) if err != nil && err != io.EOF { log.Fatal(err) } token := auth.NewUserToken() err = token.FromString(encodedToken) if err != nil { log.Println(err) return } name, err := auth.CheckChatToken(db, token) if err != nil { log.Println(err) return } client := NewClient(ws, s, name) s.Add(client) client.Listen() } http.Handle(s.pattern, websocket.Handler(onConnected)) log.Println("Created handler") for { select { // Add new a client case c := <-s.addCh: log.Println("Added new client") s.clients[c.name] = c log.Println("Now", len(s.clients), "clients connected.") s.sendContacts(c) // del a client case c := <-s.delCh: log.Println("Delete client") delete(s.clients, c.name) case msg := <-s.msgCh: log.Println("Message:", *msg) s.handleMessage(msg) case cmd := <-s.cmdCh: log.Println("Command:", *cmd) s.handleCommand(cmd) case err := <-s.errCh: log.Println("Error:", err.Error()) case <-s.doneCh: return } } }