Compare commits

..

No commits in common. "469f6333107f2ad570369a6fa72779c50719174d" and "ac638c32763a40f69e6625c86a95dbe0218af13c" have entirely different histories.

5 changed files with 53 additions and 167 deletions

View File

@ -3,26 +3,20 @@ package controller
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/nrednav/cuid2"
"net/http"
)
// TODO: This struct should have a creation time
type Lobby struct {
LobbyOwner string
LobbyPlayers []string
LobbyPlayers [3]string
}
type LobbyResult struct {
LobbyId string
}
type LobbyCreateInput struct {
UserId string
}
// TODO: We should remove entries from this map when they expire.
// TODO: Define how long lobbies last
var lobbies = make(map[string]Lobby)
@ -36,25 +30,9 @@ func CreateLobby(writer http.ResponseWriter, request *http.Request) {
return
}
// Get the UserId from the JSON payload
decoder := json.NewDecoder(request.Body)
var data LobbyCreateInput
err := decoder.Decode(&data)
if err != nil {
fmt.Printf("Error in JSON decoding: %s\n", err)
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "{\"error\": \"%s\"}", err)
return
}
lobbyId := cuid2.Generate()
result := LobbyResult{LobbyId: lobbyId}
lobbies[lobbyId] = Lobby{
LobbyOwner: data.UserId,
LobbyPlayers: make([]string, 3),
}
log.Printf("Created lobby with id %s/%s", lobbyId, data.UserId)
jsonData, err := json.Marshal(result)
if err != nil {
@ -66,23 +44,3 @@ func CreateLobby(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "%s", jsonData)
}
// Verifies that the userId has access to the lobbyId
func VerifyLobbyAccess(userId, lobbyId string) bool {
lobby, ok := lobbies[lobbyId]
if !ok {
return false
}
if lobby.LobbyOwner == userId {
return true
}
for _, playerId := range lobby.LobbyPlayers {
if playerId == userId {
return true
}
}
return false
}

View File

@ -1,11 +1,9 @@
package controller
import (
"encoding/json"
"errors"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
)
@ -16,15 +14,10 @@ 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 error:", err)
log.Print("upgrade:", err)
return
}
defer conn.Close()
@ -32,81 +25,18 @@ func LobbyWsConnect(writer http.ResponseWriter, request *http.Request) {
for {
mt, message, err := conn.ReadMessage()
if err != nil {
log.Print("read error:", err)
log.Print("read:", err)
break
}
log.Printf("recv: %s, type: %d", message, mt)
var data LobbyMsg
err = json.Unmarshal(message, &data)
if err != nil {
log.Print("json error:", err)
break
}
switch data.Action {
case "auth":
err = authenticateConnection(mt, conn, data.Value)
default:
log.Print("no action :c")
}
time.Sleep(10 * time.Second)
err = conn.WriteMessage(mt, message)
if err != nil {
log.Print("error:", err)
log.Print("write:", err)
break
}
}
}
// Verifies that the user id & lobby id are valid, and that the user has permission to
// access the lobby
func authenticateConnection(mt int, conn *websocket.Conn, authInfo string) error {
// TODO: split userId by ','
var err error
var result string
authSections := strings.Split(authInfo, ",")
if len(authSections) != 2 {
err = errors.New("Expected 2 components to auth, in string " + authInfo)
result = "unauthenticated"
} else {
userId := authSections[0]
lobbyId := authSections[1]
if !VerifyLobbyAccess(userId, lobbyId) {
log.Printf("Unathorized to enter lobby: user %s to lobby %s", userId, lobbyId)
result = "unauthenticated"
} else {
_, ok := Users[userId]
// TODO: Verify lobby id
if ok {
result = "authenticated"
} else {
result = "unauthenticated"
}
}
}
if err != nil {
log.Print("auth error: ", err)
}
json, err := json.Marshal(LobbyMsg{
Action: "auth",
Value: result,
})
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,21 +1,12 @@
package controller
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/nrednav/cuid2"
"net/http"
)
var Users map[string]string = make(map[string]string)
type PersonInfo struct {
UserId string
Username string
}
func Register(username string) string {
uid := cuid2.Generate()
@ -25,41 +16,6 @@ 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,6 +10,7 @@ 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 {
@ -22,7 +23,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,15 +2,22 @@ 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()
@ -18,7 +25,7 @@ func main() {
wsRouter := mainRouter.PathPrefix("/ws").Subrouter()
// HTTP routes
httpRouter.HandleFunc("/register", controller.RegisterUser)
httpRouter.HandleFunc("/register", Register)
httpRouter.HandleFunc("/validate", controller.ValidateId)
httpRouter.HandleFunc("/lobby/new", controller.CreateLobby).Methods("POST")
@ -41,3 +48,37 @@ 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)
}