From 1427babbcdcb73b14c4f90446d73b29b8fc0793a Mon Sep 17 00:00:00 2001 From: Jonni Liljamo Date: Thu, 19 Jan 2023 13:20:06 +0200 Subject: [PATCH] WIP(sdbapi): game creation API --- sdbapi/apierror/apierror.go | 1 + sdbapi/handlers/gamecreate.go | 61 +++++++++++++++++++++++++++++++++++ sdbapi/models/game.go | 4 +-- 3 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 sdbapi/handlers/gamecreate.go diff --git a/sdbapi/apierror/apierror.go b/sdbapi/apierror/apierror.go index a563a55..e0af99e 100644 --- a/sdbapi/apierror/apierror.go +++ b/sdbapi/apierror/apierror.go @@ -21,4 +21,5 @@ const ( UserCreationFailed string = "user creation failed" NotAuthorized string = "not authorized" GameNotFound string = "game not found" + GameCreationFailed string = "game creation failed" ) diff --git a/sdbapi/handlers/gamecreate.go b/sdbapi/handlers/gamecreate.go new file mode 100644 index 0000000..ab77f6a --- /dev/null +++ b/sdbapi/handlers/gamecreate.go @@ -0,0 +1,61 @@ +/* + * This file is part of sdbapi + * Copyright (C) 2022 Jonni Liljamo + * + * Licensed under GPL-3.0-only. + * See LICENSE for licensing information. + */ + +package handlers + +import ( + "api/apierror" + "api/auth" + "api/db" + "api/models" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v4" +) + +func CreateGame(c *gin.Context) { + // Auth should match a registered user + tokenString := c.Request.Header.Get("Authorization") + token, _ := jwt.ParseWithClaims(tokenString, &auth.JWTClaims{}, func(token *jwt.Token) (interface{}, error) { + return []byte(auth.JWTSecret), nil + }) + + var p1 models.User + + if claims, ok := token.Claims.(*auth.JWTClaims); ok && token.Valid { + // Check if the email in the claims matches a user in the database + // NOTE: Technically we should never end up here, but just in-case. + user, err := db.GetUserByEmail(claims.Email) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": apierror.NotAuthorized}) + c.Abort() + return + } else { + p1 = user + } + } else { + c.JSON(http.StatusNotFound, gin.H{"error": apierror.Placeholder}) + c.Abort() + return + } + + var game models.Game + + game.P1 = p1.ID + game.State = models.GAMESTATE_FORMING + + entry := db.DbConn.Create(&game) + if entry.Error != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": apierror.GameCreationFailed}) + c.Abort() + return + } + + c.JSON(http.StatusCreated, gin.H{"id": game.ID}) +} diff --git a/sdbapi/models/game.go b/sdbapi/models/game.go index 19a8a5b..f09c864 100644 --- a/sdbapi/models/game.go +++ b/sdbapi/models/game.go @@ -25,8 +25,8 @@ type Game struct { CreatedAt time.Time UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` - P1 User `json:"p1" gorm:"foreignkey:ID"` - P2 User `json:"p2" gorm:"foreignkey:ID"` + P1 string `json:"p1" gorm:"foreignkey:ID"` + P2 string `json:"p2" gorm:"foreignkey:ID"` State uint8 `json:"state" gorm:"type:smallint"` EndedAt time.Time `json:"ended_at" gorm:"type:timestamptz"` } -- 2.44.1