DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

1427babbcdcb73b14c4f90446d73b29b8fc0793a — Jonni Liljamo 1 year, 11 months ago 52a6bf5
WIP(sdbapi): game creation API
3 files changed, 64 insertions(+), 2 deletions(-)

M sdbapi/apierror/apierror.go
A sdbapi/handlers/gamecreate.go
M sdbapi/models/game.go
M sdbapi/apierror/apierror.go => sdbapi/apierror/apierror.go +1 -0
@@ 21,4 21,5 @@ const (
	UserCreationFailed string = "user creation failed"
	NotAuthorized      string = "not authorized"
	GameNotFound       string = "game not found"
	GameCreationFailed string = "game creation failed"
)

A sdbapi/handlers/gamecreate.go => sdbapi/handlers/gamecreate.go +61 -0
@@ 0,0 1,61 @@
/*
 * This file is part of sdbapi
 * Copyright (C) 2022 Jonni Liljamo <jonni@liljamo.com>
 *
 * 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})
}

M sdbapi/models/game.go => sdbapi/models/game.go +2 -2
@@ 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"`
}