Compare commits

...

3 Commits

Author SHA1 Message Date
da97b0b7b6 Structure files 2024-05-16 17:15:52 -05:00
4866c6fe6b Create lobby 2024-05-16 16:17:41 -05:00
6b1a5c948f Add an id validation 2024-05-08 13:50:03 -05:00
5 changed files with 108 additions and 26 deletions

46
controller/lobby.go Normal file
View File

@ -0,0 +1,46 @@
package controller
import (
"encoding/json"
"fmt"
"github.com/nrednav/cuid2"
"net/http"
)
// TODO: This struct should have a creation time
type Lobby struct {
LobbyOwner string
LobbyPlayers [3]string
}
type LobbyResult struct {
LobbyId string
}
// TODO: We should remove entries from this map when they expire.
// TODO: Define how long lobbies last
var lobbies = make(map[string]Lobby)
func CreateLobby(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application/json")
authOk := AuthHeaderIsValid(request.Header.Get("Authorization"))
if !authOk {
writer.WriteHeader(http.StatusUnauthorized)
return
}
lobbyId := cuid2.Generate()
result := LobbyResult{LobbyId: lobbyId}
jsonData, err := json.Marshal(result)
if err != nil {
fmt.Printf("Error in JSON marshal: %s\n", err)
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "{\"error\": \"%s\"}", err)
return
}
fmt.Fprintf(writer, "%s", jsonData)
}

25
controller/session.go Normal file
View File

@ -0,0 +1,25 @@
package controller
import (
"github.com/nrednav/cuid2"
"net/http"
)
var Users map[string]string = make(map[string]string)
func Register(username string) string {
uid := cuid2.Generate()
// Store in the users map
Users[uid] = username
return uid
}
func ValidateId(writer http.ResponseWriter, request *http.Request) {
if AuthHeaderIsValid(request.Header.Get("Authorization")) {
writer.WriteHeader(http.StatusOK)
} else {
writer.WriteHeader(http.StatusUnauthorized)
}
}

29
controller/utils.go Normal file
View File

@ -0,0 +1,29 @@
package controller
import (
"fmt"
"net/http"
"strings"
)
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 {
// (try to) get the Bearer token
reqToken := authHeader
if !strings.HasPrefix(reqToken, "Bearer ") {
return false
}
bearerToken := reqToken[7:]
// Check that the token is in the global map
_, ok := (Users)[bearerToken]
return ok
}

2
go.mod
View File

@ -1,4 +1,4 @@
module git.araozu.dev/card-jong-be module card-jong-be
go 1.22.2 go 1.22.2

32
main.go
View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"card-jong-be/controller"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
@ -9,7 +10,6 @@ import (
"os" "os"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/nrednav/cuid2"
"github.com/rs/cors" "github.com/rs/cors"
) )
@ -18,16 +18,13 @@ type PersonInfo struct {
Username string Username string
} }
var users map[string]string
func main() { func main() {
fmt.Println("hello SEKAI!!") fmt.Println("hello SEKAI!!")
router := mux.NewRouter().PathPrefix("/api").Subrouter() router := mux.NewRouter().PathPrefix("/api").Subrouter()
// initialize the global users map
users = make(map[string]string)
router.HandleFunc("/register", Register) router.HandleFunc("/register", Register)
router.HandleFunc("/validate", controller.ValidateId)
router.HandleFunc("/lobby/new", controller.CreateLobby).Methods("POST")
port, ok := os.LookupEnv("PORT") port, ok := os.LookupEnv("PORT")
if !ok { if !ok {
@ -50,29 +47,20 @@ func Register(writer http.ResponseWriter, request *http.Request) {
requestUrl := request.URL requestUrl := request.URL
params, err := url.ParseQuery(requestUrl.RawQuery) params, err := url.ParseQuery(requestUrl.RawQuery)
if err != nil { if err != nil {
fmt.Printf("Error parsing URL parameters: %s\n", err) controller.WriteError(err, "Error parsing URL parameters", &writer)
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "{\"error\": \"%s\"}", err)
return return
} }
usernameArr, ok := params["username"] usernameArr, ok := params["username"]
if !ok { if !ok {
fmt.Println("username GET param not found") controller.WriteError(err, "username not found", &writer)
writer.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(writer, "{\"error\": \"username not found\"}")
return return
} }
username := usernameArr[0] username := usernameArr[0]
uid := cuid2.Generate()
// Store in the users map
users[uid] = username
// The result json // The result json
result := PersonInfo{ result := PersonInfo{
UserId: uid, UserId: controller.Register(username),
Username: username, Username: username,
} }
@ -80,9 +68,7 @@ func Register(writer http.ResponseWriter, request *http.Request) {
jsonData, err := json.Marshal(result) jsonData, err := json.Marshal(result)
if err != nil { if err != nil {
fmt.Printf("Error in JSON marshal: %s\n", err) controller.WriteError(err, "Error serializing JSON", &writer)
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "{\"error\": \"%s\"}", err)
return return
} }
@ -90,7 +76,3 @@ func Register(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "%s", jsonData) fmt.Fprintf(writer, "%s", jsonData)
} }
func ValidateId(writer http.ResponseWriter, request *http.Request) {
}