ws impl. Authenticate via ws

master
Araozu 2024-05-25 16:17:48 -05:00
parent ac638c3276
commit 008cda9abd
4 changed files with 94 additions and 52 deletions

View File

@ -1,9 +1,9 @@
package controller
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
@ -14,10 +14,15 @@ var upgrader = websocket.Upgrader{
},
}
type LobbyMsg struct {
Action string `json:action`
Value string `json:value`
}
func LobbyWsConnect(writer http.ResponseWriter, request *http.Request) {
conn, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
log.Print("upgrade:", err)
log.Print("upgrade error:", err)
return
}
defer conn.Close()
@ -25,18 +30,53 @@ func LobbyWsConnect(writer http.ResponseWriter, request *http.Request) {
for {
mt, message, err := conn.ReadMessage()
if err != nil {
log.Print("read:", err)
log.Print("read error:", err)
break
}
log.Printf("recv: %s, type: %d", message, mt)
time.Sleep(10 * time.Second)
err = conn.WriteMessage(mt, message)
var data LobbyMsg
err = json.Unmarshal(message, &data)
if err != nil {
log.Print("write:", err)
log.Print("json error:", err)
break
}
switch data.Action {
case "auth":
err = validateUserId(mt, conn, data.Value)
default:
log.Print("no action :c")
}
if err != nil {
log.Print("error:", err)
break
}
}
}
func validateUserId(mt int, conn *websocket.Conn, userId string) error {
_, ok := Users[userId]
var responseJson LobbyMsg
if ok {
responseJson = LobbyMsg{Action: "auth", Value: "authorized"}
} else {
responseJson = LobbyMsg{Action: "auth", Value: "unauthorized"}
}
json, err := json.Marshal(responseJson)
if err != nil {
log.Print("json marshal: ", err)
return err
}
err = conn.WriteMessage(mt, json)
if err != nil {
log.Print("write error: ", err)
}
return err
}

View File

@ -1,12 +1,21 @@
package controller
import (
"github.com/nrednav/cuid2"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/nrednav/cuid2"
)
var Users map[string]string = make(map[string]string)
type PersonInfo struct {
UserId string
Username string
}
func Register(username string) string {
uid := cuid2.Generate()
@ -16,6 +25,41 @@ func Register(username string) string {
return uid
}
func RegisterUser(writer http.ResponseWriter, request *http.Request) {
requestUrl := request.URL
params, err := url.ParseQuery(requestUrl.RawQuery)
if err != nil {
WriteError(err, "Error parsing URL parameters", &writer)
return
}
usernameArr, ok := params["username"]
if !ok {
WriteError(err, "username not found", &writer)
return
}
username := usernameArr[0]
// The result json
result := PersonInfo{
UserId: Register(username),
Username: username,
}
writer.Header().Set("Content-Type", "application/json")
jsonData, err := json.Marshal(result)
if err != nil {
WriteError(err, "Error serializing JSON", &writer)
return
}
writer.WriteHeader(http.StatusOK)
fmt.Fprintf(writer, "%s", jsonData)
}
func ValidateId(writer http.ResponseWriter, request *http.Request) {
if AuthHeaderIsValid(request.Header.Get("Authorization")) {
writer.WriteHeader(http.StatusOK)

View File

@ -10,7 +10,6 @@ func WriteError(err error, message string, writer *http.ResponseWriter) {
fmt.Printf("Error: %s\n", err)
(*writer).WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(*writer, "{\"error\": \"%s\"}", message)
return
}
func AuthHeaderIsValid(authHeader string) bool {
@ -23,7 +22,7 @@ func AuthHeaderIsValid(authHeader string) bool {
bearerToken := reqToken[7:]
// Check that the token is in the global map
_, ok := (Users)[bearerToken]
_, ok := Users[bearerToken]
return ok
}

43
main.go
View File

@ -2,22 +2,15 @@ package main
import (
"card-jong-be/controller"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
type PersonInfo struct {
UserId string
Username string
}
func main() {
fmt.Println("hello SEKAI!!")
mainRouter := mux.NewRouter()
@ -25,7 +18,7 @@ func main() {
wsRouter := mainRouter.PathPrefix("/ws").Subrouter()
// HTTP routes
httpRouter.HandleFunc("/register", Register)
httpRouter.HandleFunc("/register", controller.RegisterUser)
httpRouter.HandleFunc("/validate", controller.ValidateId)
httpRouter.HandleFunc("/lobby/new", controller.CreateLobby).Methods("POST")
@ -48,37 +41,3 @@ func main() {
log.Fatal(http.ListenAndServe(":"+port, handler))
}
func Register(writer http.ResponseWriter, request *http.Request) {
requestUrl := request.URL
params, err := url.ParseQuery(requestUrl.RawQuery)
if err != nil {
controller.WriteError(err, "Error parsing URL parameters", &writer)
return
}
usernameArr, ok := params["username"]
if !ok {
controller.WriteError(err, "username not found", &writer)
return
}
username := usernameArr[0]
// The result json
result := PersonInfo{
UserId: controller.Register(username),
Username: username,
}
writer.Header().Set("Content-Type", "application/json")
jsonData, err := json.Marshal(result)
if err != nil {
controller.WriteError(err, "Error serializing JSON", &writer)
return
}
writer.WriteHeader(http.StatusOK)
fmt.Fprintf(writer, "%s", jsonData)
}