From 5e6775c9c1efbbd3b08363ffda421a5996dc7143 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Thu, 1 Aug 2024 21:07:37 +0900 Subject: refactor: specify `operationId` in OpenAPI spec --- backend/api/handlers.go | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) (limited to 'backend/api/handlers.go') diff --git a/backend/api/handlers.go b/backend/api/handlers.go index c96cd2a..a250629 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -33,10 +33,10 @@ func NewHandler(queries *db.Queries, hubs GameHubsInterface) *ApiHandler { } } -func (h *ApiHandler) GetAdminGames(ctx context.Context, request GetAdminGamesRequestObject) (GetAdminGamesResponseObject, error) { +func (h *ApiHandler) AdminGetGames(ctx context.Context, request AdminGetGamesRequestObject) (AdminGetGamesResponseObject, error) { user := ctx.Value("user").(*auth.JWTClaims) if !user.IsAdmin { - return GetAdminGames403JSONResponse{ + return AdminGetGames403JSONResponse{ Message: "Forbidden", }, nil } @@ -71,15 +71,15 @@ func (h *ApiHandler) GetAdminGames(ctx context.Context, request GetAdminGamesReq Problem: problem, } } - return GetAdminGames200JSONResponse{ + return AdminGetGames200JSONResponse{ Games: games, }, nil } -func (h *ApiHandler) GetAdminGamesGameId(ctx context.Context, request GetAdminGamesGameIdRequestObject) (GetAdminGamesGameIdResponseObject, error) { +func (h *ApiHandler) AdminGetGame(ctx context.Context, request AdminGetGameRequestObject) (AdminGetGameResponseObject, error) { user := ctx.Value("user").(*auth.JWTClaims) if !user.IsAdmin { - return GetAdminGamesGameId403JSONResponse{ + return AdminGetGame403JSONResponse{ Message: "Forbidden", }, nil } @@ -87,7 +87,7 @@ func (h *ApiHandler) GetAdminGamesGameId(ctx context.Context, request GetAdminGa row, err := h.q.GetGameById(ctx, int32(gameId)) if err != nil { if errors.Is(err, pgx.ErrNoRows) { - return GetAdminGamesGameId404JSONResponse{ + return AdminGetGame404JSONResponse{ Message: "Game not found", }, nil } else { @@ -118,15 +118,15 @@ func (h *ApiHandler) GetAdminGamesGameId(ctx context.Context, request GetAdminGa StartedAt: startedAt, Problem: problem, } - return GetAdminGamesGameId200JSONResponse{ + return AdminGetGame200JSONResponse{ Game: game, }, nil } -func (h *ApiHandler) PutAdminGamesGameId(ctx context.Context, request PutAdminGamesGameIdRequestObject) (PutAdminGamesGameIdResponseObject, error) { +func (h *ApiHandler) AdminPutGame(ctx context.Context, request AdminPutGameRequestObject) (AdminPutGameResponseObject, error) { user := ctx.Value("user").(*auth.JWTClaims) if !user.IsAdmin { - return PutAdminGamesGameId403JSONResponse{ + return AdminPutGame403JSONResponse{ Message: "Forbidden", }, nil } @@ -140,7 +140,7 @@ func (h *ApiHandler) PutAdminGamesGameId(ctx context.Context, request PutAdminGa game, err := h.q.GetGameById(ctx, int32(gameID)) if err != nil { if err == pgx.ErrNoRows { - return PutAdminGamesGameId404JSONResponse{ + return AdminPutGame404JSONResponse{ Message: "Game not found", }, nil } else { @@ -202,18 +202,18 @@ func (h *ApiHandler) PutAdminGamesGameId(ctx context.Context, request PutAdminGa ProblemID: changedProblemID, }) if err != nil { - return PutAdminGamesGameId400JSONResponse{ + return AdminPutGame400JSONResponse{ Message: err.Error(), }, nil } - return PutAdminGamesGameId204Response{}, nil + return AdminPutGame204Response{}, nil } -func (h *ApiHandler) GetAdminUsers(ctx context.Context, request GetAdminUsersRequestObject) (GetAdminUsersResponseObject, error) { +func (h *ApiHandler) AdminGetUsers(ctx context.Context, request AdminGetUsersRequestObject) (AdminGetUsersResponseObject, error) { user := ctx.Value("user").(*auth.JWTClaims) if !user.IsAdmin { - return GetAdminUsers403JSONResponse{ + return AdminGetUsers403JSONResponse{ Message: "Forbidden", }, nil } @@ -231,7 +231,7 @@ func (h *ApiHandler) GetAdminUsers(ctx context.Context, request GetAdminUsersReq IsAdmin: u.IsAdmin, } } - return GetAdminUsers200JSONResponse{ + return AdminGetUsers200JSONResponse{ Users: responseUsers, }, nil } @@ -357,14 +357,14 @@ func (h *ApiHandler) GetGames(ctx context.Context, request GetGamesRequestObject } } -func (h *ApiHandler) GetGamesGameId(ctx context.Context, request GetGamesGameIdRequestObject) (GetGamesGameIdResponseObject, error) { +func (h *ApiHandler) GetGame(ctx context.Context, request GetGameRequestObject) (GetGameResponseObject, error) { user := ctx.Value("user").(*auth.JWTClaims) // TODO: check user permission gameId := request.GameId row, err := h.q.GetGameById(ctx, int32(gameId)) if err != nil { if errors.Is(err, pgx.ErrNoRows) { - return GetGamesGameId404JSONResponse{ + return GetGame404JSONResponse{ Message: "Game not found", }, nil } else { @@ -397,7 +397,7 @@ func (h *ApiHandler) GetGamesGameId(ctx context.Context, request GetGamesGameIdR StartedAt: startedAt, Problem: problem, } - return GetGamesGameId200JSONResponse{ + return GetGame200JSONResponse{ Game: game, }, nil } -- cgit v1.2.3-70-g09d2 From 6767acd3d9cc2cf5b778048ec6339b8c9123fbb5 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Thu, 1 Aug 2024 21:08:31 +0900 Subject: refactor(backend): wrap ApiHandler with user authentication --- backend/api/handler_wrapper.go | 134 +++++++++++++++++++++++++++ backend/api/handlers.go | 93 ++----------------- backend/gen/api_handler_wrapper_gen.go | 164 +++++++++++++++++++++++++++++++++ backend/gen/gen.go | 1 + backend/main.go | 4 +- 5 files changed, 307 insertions(+), 89 deletions(-) create mode 100644 backend/api/handler_wrapper.go create mode 100644 backend/gen/api_handler_wrapper_gen.go (limited to 'backend/api/handlers.go') diff --git a/backend/api/handler_wrapper.go b/backend/api/handler_wrapper.go new file mode 100644 index 0000000..37a199b --- /dev/null +++ b/backend/api/handler_wrapper.go @@ -0,0 +1,134 @@ +// Code generated by go generate; DO NOT EDIT. + +package api + +import ( + "context" + "errors" + "strings" + + "github.com/nsfisis/iosdc-japan-2024-albatross/backend/auth" + "github.com/nsfisis/iosdc-japan-2024-albatross/backend/db" +) + +var _ StrictServerInterface = (*ApiHandlerWrapper)(nil) + +type ApiHandlerWrapper struct { + innerHandler ApiHandler +} + +func NewHandler(queries *db.Queries, hubs GameHubsInterface) *ApiHandlerWrapper { + return &ApiHandlerWrapper{ + innerHandler: ApiHandler{ + q: queries, + hubs: hubs, + }, + } +} + +func parseJWTClaimsFromAuthorizationHeader(authorization string) (*auth.JWTClaims, error) { + const prefix = "Bearer " + if !strings.HasPrefix(authorization, prefix) { + return nil, errors.New("invalid authorization header") + } + token := authorization[len(prefix):] + claims, err := auth.ParseJWT(token) + if err != nil { + return nil, err + } + return claims, nil +} + +func (h *ApiHandlerWrapper) AdminGetGame(ctx context.Context, request AdminGetGameRequestObject) (AdminGetGameResponseObject, error) { + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return AdminGetGame401JSONResponse{ + Message: "Unauthorized", + }, nil + } + if !user.IsAdmin { + return AdminGetGame403JSONResponse{ + Message: "Forbidden", + }, nil + } + return h.innerHandler.AdminGetGame(ctx, request, user) +} + +func (h *ApiHandlerWrapper) AdminGetGames(ctx context.Context, request AdminGetGamesRequestObject) (AdminGetGamesResponseObject, error) { + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return AdminGetGames401JSONResponse{ + Message: "Unauthorized", + }, nil + } + if !user.IsAdmin { + return AdminGetGames403JSONResponse{ + Message: "Forbidden", + }, nil + } + return h.innerHandler.AdminGetGames(ctx, request, user) +} + +func (h *ApiHandlerWrapper) AdminGetUsers(ctx context.Context, request AdminGetUsersRequestObject) (AdminGetUsersResponseObject, error) { + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return AdminGetUsers401JSONResponse{ + Message: "Unauthorized", + }, nil + } + if !user.IsAdmin { + return AdminGetUsers403JSONResponse{ + Message: "Forbidden", + }, nil + } + return h.innerHandler.AdminGetUsers(ctx, request, user) +} + +func (h *ApiHandlerWrapper) AdminPutGame(ctx context.Context, request AdminPutGameRequestObject) (AdminPutGameResponseObject, error) { + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return AdminPutGame401JSONResponse{ + Message: "Unauthorized", + }, nil + } + if !user.IsAdmin { + return AdminPutGame403JSONResponse{ + Message: "Forbidden", + }, nil + } + return h.innerHandler.AdminPutGame(ctx, request, user) +} + +func (h *ApiHandlerWrapper) GetGame(ctx context.Context, request GetGameRequestObject) (GetGameResponseObject, error) { + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return GetGame401JSONResponse{ + Message: "Unauthorized", + }, nil + } + return h.innerHandler.GetGame(ctx, request, user) +} + +func (h *ApiHandlerWrapper) GetGames(ctx context.Context, request GetGamesRequestObject) (GetGamesResponseObject, error) { + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return GetGames401JSONResponse{ + Message: "Unauthorized", + }, nil + } + return h.innerHandler.GetGames(ctx, request, user) +} + +func (h *ApiHandlerWrapper) GetToken(ctx context.Context, request GetTokenRequestObject) (GetTokenResponseObject, error) { + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return GetToken401JSONResponse{ + Message: "Unauthorized", + }, nil + } + return h.innerHandler.GetToken(ctx, request, user) +} + +func (h *ApiHandlerWrapper) PostLogin(ctx context.Context, request PostLoginRequestObject) (PostLoginResponseObject, error) { + return h.innerHandler.PostLogin(ctx, request) +} diff --git a/backend/api/handlers.go b/backend/api/handlers.go index a250629..ea9ddea 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -4,7 +4,6 @@ import ( "context" "errors" "net/http" - "strings" "time" "github.com/jackc/pgx/v5" @@ -15,8 +14,6 @@ import ( "github.com/nsfisis/iosdc-japan-2024-albatross/backend/db" ) -var _ StrictServerInterface = (*ApiHandler)(nil) - type ApiHandler struct { q *db.Queries hubs GameHubsInterface @@ -26,20 +23,7 @@ type GameHubsInterface interface { StartGame(gameID int) error } -func NewHandler(queries *db.Queries, hubs GameHubsInterface) *ApiHandler { - return &ApiHandler{ - q: queries, - hubs: hubs, - } -} - -func (h *ApiHandler) AdminGetGames(ctx context.Context, request AdminGetGamesRequestObject) (AdminGetGamesResponseObject, error) { - user := ctx.Value("user").(*auth.JWTClaims) - if !user.IsAdmin { - return AdminGetGames403JSONResponse{ - Message: "Forbidden", - }, nil - } +func (h *ApiHandler) AdminGetGames(ctx context.Context, request AdminGetGamesRequestObject, user *auth.JWTClaims) (AdminGetGamesResponseObject, error) { gameRows, err := h.q.ListGames(ctx) if err != nil { return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) @@ -76,13 +60,7 @@ func (h *ApiHandler) AdminGetGames(ctx context.Context, request AdminGetGamesReq }, nil } -func (h *ApiHandler) AdminGetGame(ctx context.Context, request AdminGetGameRequestObject) (AdminGetGameResponseObject, error) { - user := ctx.Value("user").(*auth.JWTClaims) - if !user.IsAdmin { - return AdminGetGame403JSONResponse{ - Message: "Forbidden", - }, nil - } +func (h *ApiHandler) AdminGetGame(ctx context.Context, request AdminGetGameRequestObject, user *auth.JWTClaims) (AdminGetGameResponseObject, error) { gameId := request.GameId row, err := h.q.GetGameById(ctx, int32(gameId)) if err != nil { @@ -123,13 +101,7 @@ func (h *ApiHandler) AdminGetGame(ctx context.Context, request AdminGetGameReque }, nil } -func (h *ApiHandler) AdminPutGame(ctx context.Context, request AdminPutGameRequestObject) (AdminPutGameResponseObject, error) { - user := ctx.Value("user").(*auth.JWTClaims) - if !user.IsAdmin { - return AdminPutGame403JSONResponse{ - Message: "Forbidden", - }, nil - } +func (h *ApiHandler) AdminPutGame(ctx context.Context, request AdminPutGameRequestObject, user *auth.JWTClaims) (AdminPutGameResponseObject, error) { gameID := request.GameId displayName := request.Body.DisplayName durationSeconds := request.Body.DurationSeconds @@ -210,13 +182,7 @@ func (h *ApiHandler) AdminPutGame(ctx context.Context, request AdminPutGameReque return AdminPutGame204Response{}, nil } -func (h *ApiHandler) AdminGetUsers(ctx context.Context, request AdminGetUsersRequestObject) (AdminGetUsersResponseObject, error) { - user := ctx.Value("user").(*auth.JWTClaims) - if !user.IsAdmin { - return AdminGetUsers403JSONResponse{ - Message: "Forbidden", - }, nil - } +func (h *ApiHandler) AdminGetUsers(ctx context.Context, request AdminGetUsersRequestObject, user *auth.JWTClaims) (AdminGetUsersResponseObject, error) { users, err := h.q.ListUsers(ctx) if err != nil { return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) @@ -263,8 +229,7 @@ func (h *ApiHandler) PostLogin(ctx context.Context, request PostLoginRequestObje }, nil } -func (h *ApiHandler) GetToken(ctx context.Context, request GetTokenRequestObject) (GetTokenResponseObject, error) { - user := ctx.Value("user").(*auth.JWTClaims) +func (h *ApiHandler) GetToken(ctx context.Context, request GetTokenRequestObject, user *auth.JWTClaims) (GetTokenResponseObject, error) { newToken, err := auth.NewShortLivedJWT(user) if err != nil { return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) @@ -274,8 +239,7 @@ func (h *ApiHandler) GetToken(ctx context.Context, request GetTokenRequestObject }, nil } -func (h *ApiHandler) GetGames(ctx context.Context, request GetGamesRequestObject) (GetGamesResponseObject, error) { - user := ctx.Value("user").(*auth.JWTClaims) +func (h *ApiHandler) GetGames(ctx context.Context, request GetGamesRequestObject, user *auth.JWTClaims) (GetGamesResponseObject, error) { playerId := request.Params.PlayerId if !user.IsAdmin { if playerId == nil || *playerId != user.UserID { @@ -357,8 +321,7 @@ func (h *ApiHandler) GetGames(ctx context.Context, request GetGamesRequestObject } } -func (h *ApiHandler) GetGame(ctx context.Context, request GetGameRequestObject) (GetGameResponseObject, error) { - user := ctx.Value("user").(*auth.JWTClaims) +func (h *ApiHandler) GetGame(ctx context.Context, request GetGameRequestObject, user *auth.JWTClaims) (GetGameResponseObject, error) { // TODO: check user permission gameId := request.GameId row, err := h.q.GetGameById(ctx, int32(gameId)) @@ -401,45 +364,3 @@ func (h *ApiHandler) GetGame(ctx context.Context, request GetGameRequestObject) Game: game, }, nil } - -func _assertUserResponseIsCompatibleWithJWTClaims() { - var c auth.JWTClaims - var u User - u.UserId = c.UserID - u.Username = c.Username - u.DisplayName = c.DisplayName - u.IconPath = c.IconPath - u.IsAdmin = c.IsAdmin - _ = u -} - -func setupJWTFromAuthorizationHeader(c echo.Context) error { - authorization := c.Request().Header.Get("Authorization") - const prefix = "Bearer " - if !strings.HasPrefix(authorization, prefix) { - return echo.NewHTTPError(http.StatusUnauthorized) - } - token := authorization[len(prefix):] - claims, err := auth.ParseJWT(token) - if err != nil { - return echo.NewHTTPError(http.StatusUnauthorized, err.Error()) - } - c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), "user", claims))) - return nil -} - -func NewJWTMiddleware() StrictMiddlewareFunc { - return func(handler StrictHandlerFunc, operationID string) StrictHandlerFunc { - if operationID == "PostLogin" { - return handler - } - - return func(c echo.Context, request interface{}) (interface{}, error) { - err := setupJWTFromAuthorizationHeader(c) - if err != nil { - return nil, echo.NewHTTPError(http.StatusUnauthorized, err.Error()) - } - return handler(c, request) - } - } -} diff --git a/backend/gen/api_handler_wrapper_gen.go b/backend/gen/api_handler_wrapper_gen.go new file mode 100644 index 0000000..01d05bf --- /dev/null +++ b/backend/gen/api_handler_wrapper_gen.go @@ -0,0 +1,164 @@ +package main + +import ( + "bytes" + "flag" + "go/ast" + "go/format" + "go/parser" + "go/token" + "os" + "slices" + "strings" + "text/template" +) + +func main() { + inputFile := flag.String("i", "", "input file") + outputFile := flag.String("o", "", "output file") + flag.Parse() + + if inputFile == nil || *inputFile == "" || outputFile == nil || *outputFile == "" { + flag.PrintDefaults() + os.Exit(1) + } + + // Parse the input file + fileSet := token.NewFileSet() + parsedFile, err := parser.ParseFile(fileSet, *inputFile, nil, parser.SkipObjectResolution) + if err != nil { + panic(err) + } + + // Find methods in StrictServerInterface + var methods []string + for _, decl := range parsedFile.Decls { + genDecl, ok := decl.(*ast.GenDecl) + if !ok { + continue + } + for _, spec := range genDecl.Specs { + typeSpec, ok := spec.(*ast.TypeSpec) + if !ok { + continue + } + if typeSpec.Name.Name != "StrictServerInterface" { + continue + } + interfaceType, ok := typeSpec.Type.(*ast.InterfaceType) + if !ok { + continue + } + for _, method := range interfaceType.Methods.List { + if len(method.Names) != 0 { + methods = append(methods, method.Names[0].Name) + } + } + } + } + if len(methods) == 0 { + panic("StrictServerInterface not found") + } + slices.Sort(methods) + + type TemplateParameter struct { + Name string + RequiresLogin bool + RequiresAdminRole bool + } + templateParameters := make([]TemplateParameter, len(methods)) + for i, method := range methods { + templateParameters[i] = TemplateParameter{ + Name: method, + RequiresLogin: method != "PostLogin", + RequiresAdminRole: strings.Contains(method, "Admin"), + } + } + + // Generate code. + tmpl, err := template.New("code").Parse(templateText) + if err != nil { + panic(err) + } + + var buf bytes.Buffer + err = tmpl.Execute(&buf, templateParameters) + if err != nil { + panic(err) + } + + formatted, err := format.Source(buf.Bytes()) + if err != nil { + panic(err) + } + + err = os.WriteFile(*outputFile, formatted, 0644) + if err != nil { + panic(err) + } +} + +const templateText = `// Code generated by go generate; DO NOT EDIT. + +package api + +import ( + "context" + "errors" + "strings" + + "github.com/nsfisis/iosdc-japan-2024-albatross/backend/auth" + "github.com/nsfisis/iosdc-japan-2024-albatross/backend/db" +) + +var _ StrictServerInterface = (*ApiHandlerWrapper)(nil) + +type ApiHandlerWrapper struct { + innerHandler ApiHandler +} + +func NewHandler(queries *db.Queries, hubs GameHubsInterface) *ApiHandlerWrapper { + return &ApiHandlerWrapper{ + innerHandler: ApiHandler{ + q: queries, + hubs: hubs, + }, + } +} + +func parseJWTClaimsFromAuthorizationHeader(authorization string) (*auth.JWTClaims, error) { + const prefix = "Bearer " + if !strings.HasPrefix(authorization, prefix) { + return nil, errors.New("invalid authorization header") + } + token := authorization[len(prefix):] + claims, err := auth.ParseJWT(token) + if err != nil { + return nil, err + } + return claims, nil +} + +{{ range . }} + func (h *ApiHandlerWrapper) {{ .Name }}(ctx context.Context, request {{ .Name }}RequestObject) ({{ .Name }}ResponseObject, error) { + {{ if .RequiresLogin -}} + user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) + if err != nil { + return {{ .Name }}401JSONResponse{ + Message: "Unauthorized", + }, nil + } + {{ if .RequiresAdminRole -}} + if !user.IsAdmin { + return {{ .Name }}403JSONResponse{ + Message: "Forbidden", + }, nil + } + {{ end -}} + return h.innerHandler.{{ .Name }}(ctx, request, user) + {{ else -}} + return h.innerHandler.{{ .Name }}(ctx, request) + {{ end -}} + } +{{ end }} +` diff --git a/backend/gen/gen.go b/backend/gen/gen.go index 6af912d..6fb430f 100644 --- a/backend/gen/gen.go +++ b/backend/gen/gen.go @@ -2,3 +2,4 @@ package main //go:generate go run github.com/sqlc-dev/sqlc/cmd/sqlc generate //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen -config oapi-codegen.yaml ../../openapi.yaml +//go:generate go run ./api_handler_wrapper_gen.go -i ../api/generated.go -o ../api/handler_wrapper.go diff --git a/backend/main.go b/backend/main.go index d636af7..0257113 100644 --- a/backend/main.go +++ b/backend/main.go @@ -75,9 +75,7 @@ func main() { apiGroup := e.Group("/api") apiGroup.Use(oapimiddleware.OapiRequestValidator(openApiSpec)) apiHandler := api.NewHandler(queries, gameHubs) - api.RegisterHandlers(apiGroup, api.NewStrictHandler(apiHandler, []api.StrictMiddlewareFunc{ - api.NewJWTMiddleware(), - })) + api.RegisterHandlers(apiGroup, api.NewStrictHandler(apiHandler, nil)) gameHubs.Run() -- cgit v1.2.3-70-g09d2 From 72012983718a8d1f1d850e24e9af3a29fb20374a Mon Sep 17 00:00:00 2001 From: nsfisis Date: Thu, 1 Aug 2024 21:09:36 +0900 Subject: refactor: remove `player_id` parameter from `/api/games` --- backend/api/generated.go | 59 ++++++++++----------- backend/api/handlers.go | 99 ++++++++++-------------------------- frontend/app/.server/api/schema.d.ts | 4 +- frontend/app/routes/dashboard.tsx | 3 -- openapi.yaml | 5 -- 5 files changed, 54 insertions(+), 116 deletions(-) (limited to 'backend/api/handlers.go') diff --git a/backend/api/generated.go b/backend/api/generated.go index fe693f8..6de100a 100644 --- a/backend/api/generated.go +++ b/backend/api/generated.go @@ -241,7 +241,6 @@ type AdminGetUsersParams struct { // GetGamesParams defines parameters for GetGames. type GetGamesParams struct { - PlayerId *int `form:"player_id,omitempty" json:"player_id,omitempty"` Authorization string `json:"Authorization"` } @@ -806,12 +805,6 @@ func (w *ServerInterfaceWrapper) GetGames(ctx echo.Context) error { // Parameter object where we will unmarshal all parameters from the context var params GetGamesParams - // ------------- Optional query parameter "player_id" ------------- - - err = runtime.BindQueryParameter("form", true, false, "player_id", ctx.QueryParams(), ¶ms.PlayerId) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter player_id: %s", err)) - } headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- @@ -1561,32 +1554,32 @@ func (sh *strictHandler) GetToken(ctx echo.Context, params GetTokenParams) error // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xZbW/bNhD+Kxo3oBugxY4TFJ2/ZVmXdeg2o2mwD0Vg0NLZZkaRKkk18Qr994GkXkxL", - "tmhHfcngfmgSiXd67uU53pEfUcSTlDNgSqLxRySjJSTY/HqFE9A/U8FTEIqAeRoTmVK8mrLiLTzgJKWA", - "xmZ9cIpCpFap/lsqQdgC5SGKM4EV4WwqIeIslo7c2fNhJUKYggUILbPACUxJ7Cw9bVuYCj6jkOiF3wmY", - "ozH6dlDbNCgMGkyKZXmIpMJCQTzFytH+0/nz5y/OXwxb4UiFlbWXZQkav0MR5RJiFKJ7TBRhiykwJbSP", - "6ifmO0gjhBQLQMWXtVOMffaXOWFELiFGt+GaMyv1G87MQyTgfUYExBpF6aUSYOjGp8X1t5VKPruDSGnj", - "dOQmFK9A/AFS4oUxlDP4a47G73a7tSF6PbpEebin0OXoGuW3bUj0m8PBXI6uXzIlVgchegM4Pkzyksew", - "3R7ztskrrHBXDm/TNsErynGsQ2ljq1nNpEJjlJrl42gkx5H+bldCmbehReOVKhsQGnZFhbV1aqeCMPX9", - "s9+AUh4G91zQ+Jtn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OQ6mdub7wPDNPn+ri4uYv1mtV2fD30m/e+kq+JjnxuBj5vleuL1hiBbuxkOssoXQZZGmNV", + "Vp1+16x9xT5gSuKgyLhOubuu+1TzTzX/mJp/a5hQlf26x9Mz2O5B59aselqDTmWZ16BjBvZdg45Vuc+g", + "YyVO7P2qBh1MaRkYTYTts/5pzD+N+d/qmO874J9m+9Nsf+rzntpsrxlO+dze/qdcOog95lK9Nku6GpxT", + "LOUDF/Ha9+Xi6WB47pqcj/yawMraVGx9d9AweUx9UPwfWPuI9aj/na38v/u7nlHiE/3GkKsZCExpqCUJ", + "B59q1I0ExHovTOUnGXfLaAZcBFU41yYZCSKwaW0yvHL9ppPrrVnwtLq3bz2fPtOB5CiNcsGF+pGSDxAH", + "2FgdWD/leZ7/FwAA///GgvoRhDAAAA==", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/backend/api/handlers.go b/backend/api/handlers.go index ea9ddea..164682d 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -240,85 +240,40 @@ func (h *ApiHandler) GetToken(ctx context.Context, request GetTokenRequestObject } func (h *ApiHandler) GetGames(ctx context.Context, request GetGamesRequestObject, user *auth.JWTClaims) (GetGamesResponseObject, error) { - playerId := request.Params.PlayerId - if !user.IsAdmin { - if playerId == nil || *playerId != user.UserID { - return GetGames403JSONResponse{ - Message: "Forbidden", - }, nil - } + gameRows, err := h.q.ListGamesForPlayer(ctx, int32(user.UserID)) + if err != nil { + return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } - if playerId == nil { - gameRows, err := h.q.ListGames(ctx) - if err != nil { - return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) + games := make([]Game, len(gameRows)) + for i, row := range gameRows { + var startedAt *int + if row.StartedAt.Valid { + startedAtTimestamp := int(row.StartedAt.Time.Unix()) + startedAt = &startedAtTimestamp } - games := make([]Game, len(gameRows)) - for i, row := range gameRows { - var startedAt *int - if row.StartedAt.Valid { - startedAtTimestamp := int(row.StartedAt.Time.Unix()) - startedAt = &startedAtTimestamp - } - var problem *Problem - if row.ProblemID != nil { - if row.Title == nil || row.Description == nil { - panic("inconsistent data") - } - problem = &Problem{ - ProblemId: int(*row.ProblemID), - Title: *row.Title, - Description: *row.Description, - } + var problem *Problem + if row.ProblemID != nil { + if row.Title == nil || row.Description == nil { + panic("inconsistent data") } - games[i] = Game{ - GameId: int(row.GameID), - State: GameState(row.State), - DisplayName: row.DisplayName, - DurationSeconds: int(row.DurationSeconds), - StartedAt: startedAt, - Problem: problem, + problem = &Problem{ + ProblemId: int(*row.ProblemID), + Title: *row.Title, + Description: *row.Description, } } - return GetGames200JSONResponse{ - Games: games, - }, nil - } else { - gameRows, err := h.q.ListGamesForPlayer(ctx, int32(*playerId)) - if err != nil { - return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) - } - games := make([]Game, len(gameRows)) - for i, row := range gameRows { - var startedAt *int - if row.StartedAt.Valid { - startedAtTimestamp := int(row.StartedAt.Time.Unix()) - startedAt = &startedAtTimestamp - } - var problem *Problem - if row.ProblemID != nil { - if row.Title == nil || row.Description == nil { - panic("inconsistent data") - } - problem = &Problem{ - ProblemId: int(*row.ProblemID), - Title: *row.Title, - Description: *row.Description, - } - } - games[i] = Game{ - GameId: int(row.GameID), - State: GameState(row.State), - DisplayName: row.DisplayName, - DurationSeconds: int(row.DurationSeconds), - StartedAt: startedAt, - Problem: problem, - } + games[i] = Game{ + GameId: int(row.GameID), + State: GameState(row.State), + DisplayName: row.DisplayName, + DurationSeconds: int(row.DurationSeconds), + StartedAt: startedAt, + Problem: problem, } - return GetGames200JSONResponse{ - Games: games, - }, nil } + return GetGames200JSONResponse{ + Games: games, + }, nil } func (h *ApiHandler) GetGame(ctx context.Context, request GetGameRequestObject, user *auth.JWTClaims) (GetGameResponseObject, error) { diff --git a/frontend/app/.server/api/schema.d.ts b/frontend/app/.server/api/schema.d.ts index 3ef97ab..1adfc86 100644 --- a/frontend/app/.server/api/schema.d.ts +++ b/frontend/app/.server/api/schema.d.ts @@ -349,9 +349,7 @@ export interface operations { }; getGames: { parameters: { - query?: { - player_id?: number; - }; + query?: never; header: { Authorization: string; }; diff --git a/frontend/app/routes/dashboard.tsx b/frontend/app/routes/dashboard.tsx index 3cc8e13..08780f9 100644 --- a/frontend/app/routes/dashboard.tsx +++ b/frontend/app/routes/dashboard.tsx @@ -17,9 +17,6 @@ export async function loader({ request }: LoaderFunctionArgs) { } const { data, error } = await apiClient.GET("/games", { params: { - query: { - player_id: user.user_id, - }, header: { Authorization: `Bearer ${token}`, }, diff --git a/openapi.yaml b/openapi.yaml index fe1e4fa..637ea3d 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -88,11 +88,6 @@ paths: operationId: getGames summary: List games parameters: - - in: query - name: player_id - schema: - type: integer - required: false - in: header name: Authorization schema: -- cgit v1.2.3-70-g09d2 From ebb1129ae9ef16139a32bf899d42009176642299 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Thu, 1 Aug 2024 21:10:42 +0900 Subject: refactor: simplify parameter definitions in OpenAPI spec --- backend/api/generated.go | 110 ++++++++++++++++++----------------- backend/api/handlers.go | 12 ++-- frontend/app/.server/api/schema.d.ts | 25 ++++---- openapi.yaml | 73 ++++++++--------------- 4 files changed, 101 insertions(+), 119 deletions(-) (limited to 'backend/api/handlers.go') diff --git a/backend/api/generated.go b/backend/api/generated.go index 6de100a..47dd905 100644 --- a/backend/api/generated.go +++ b/backend/api/generated.go @@ -207,14 +207,20 @@ type User struct { Username string `json:"username"` } +// HeaderAuthorization defines model for header_authorization. +type HeaderAuthorization = string + +// PathGameId defines model for path_game_id. +type PathGameId = int + // AdminGetGamesParams defines parameters for AdminGetGames. type AdminGetGamesParams struct { - Authorization string `json:"Authorization"` + Authorization HeaderAuthorization `json:"Authorization"` } // AdminGetGameParams defines parameters for AdminGetGame. type AdminGetGameParams struct { - Authorization string `json:"Authorization"` + Authorization HeaderAuthorization `json:"Authorization"` } // AdminPutGameJSONBody defines parameters for AdminPutGame. @@ -228,7 +234,7 @@ type AdminPutGameJSONBody struct { // AdminPutGameParams defines parameters for AdminPutGame. type AdminPutGameParams struct { - Authorization string `json:"Authorization"` + Authorization HeaderAuthorization `json:"Authorization"` } // AdminPutGameJSONBodyState defines parameters for AdminPutGame. @@ -236,17 +242,17 @@ type AdminPutGameJSONBodyState string // AdminGetUsersParams defines parameters for AdminGetUsers. type AdminGetUsersParams struct { - Authorization string `json:"Authorization"` + Authorization HeaderAuthorization `json:"Authorization"` } // GetGamesParams defines parameters for GetGames. type GetGamesParams struct { - Authorization string `json:"Authorization"` + Authorization HeaderAuthorization `json:"Authorization"` } // GetGameParams defines parameters for GetGame. type GetGameParams struct { - Authorization string `json:"Authorization"` + Authorization HeaderAuthorization `json:"Authorization"` } // PostLoginJSONBody defines parameters for PostLogin. @@ -257,7 +263,7 @@ type PostLoginJSONBody struct { // GetTokenParams defines parameters for GetToken. type GetTokenParams struct { - Authorization string `json:"Authorization"` + Authorization HeaderAuthorization `json:"Authorization"` } // AdminPutGameJSONRequestBody defines body for AdminPutGame for application/json ContentType. @@ -635,10 +641,10 @@ type ServerInterface interface { AdminGetGames(ctx echo.Context, params AdminGetGamesParams) error // Get a game // (GET /admin/games/{game_id}) - AdminGetGame(ctx echo.Context, gameId int, params AdminGetGameParams) error + AdminGetGame(ctx echo.Context, gameId PathGameId, params AdminGetGameParams) error // Update a game // (PUT /admin/games/{game_id}) - AdminPutGame(ctx echo.Context, gameId int, params AdminPutGameParams) error + AdminPutGame(ctx echo.Context, gameId PathGameId, params AdminPutGameParams) error // List all users // (GET /admin/users) AdminGetUsers(ctx echo.Context, params AdminGetUsersParams) error @@ -647,7 +653,7 @@ type ServerInterface interface { GetGames(ctx echo.Context, params GetGamesParams) error // Get a game // (GET /games/{game_id}) - GetGame(ctx echo.Context, gameId int, params GetGameParams) error + GetGame(ctx echo.Context, gameId PathGameId, params GetGameParams) error // User login // (POST /login) PostLogin(ctx echo.Context) error @@ -671,7 +677,7 @@ func (w *ServerInterfaceWrapper) AdminGetGames(ctx echo.Context) error { headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- if valueList, found := headers[http.CanonicalHeaderKey("Authorization")]; found { - var Authorization string + var Authorization HeaderAuthorization n := len(valueList) if n != 1 { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Authorization, got %d", n)) @@ -696,7 +702,7 @@ func (w *ServerInterfaceWrapper) AdminGetGames(ctx echo.Context) error { func (w *ServerInterfaceWrapper) AdminGetGame(ctx echo.Context) error { var err error // ------------- Path parameter "game_id" ------------- - var gameId int + var gameId PathGameId err = runtime.BindStyledParameterWithOptions("simple", "game_id", ctx.Param("game_id"), &gameId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) if err != nil { @@ -709,7 +715,7 @@ func (w *ServerInterfaceWrapper) AdminGetGame(ctx echo.Context) error { headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- if valueList, found := headers[http.CanonicalHeaderKey("Authorization")]; found { - var Authorization string + var Authorization HeaderAuthorization n := len(valueList) if n != 1 { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Authorization, got %d", n)) @@ -734,7 +740,7 @@ func (w *ServerInterfaceWrapper) AdminGetGame(ctx echo.Context) error { func (w *ServerInterfaceWrapper) AdminPutGame(ctx echo.Context) error { var err error // ------------- Path parameter "game_id" ------------- - var gameId int + var gameId PathGameId err = runtime.BindStyledParameterWithOptions("simple", "game_id", ctx.Param("game_id"), &gameId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) if err != nil { @@ -747,7 +753,7 @@ func (w *ServerInterfaceWrapper) AdminPutGame(ctx echo.Context) error { headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- if valueList, found := headers[http.CanonicalHeaderKey("Authorization")]; found { - var Authorization string + var Authorization HeaderAuthorization n := len(valueList) if n != 1 { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Authorization, got %d", n)) @@ -778,7 +784,7 @@ func (w *ServerInterfaceWrapper) AdminGetUsers(ctx echo.Context) error { headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- if valueList, found := headers[http.CanonicalHeaderKey("Authorization")]; found { - var Authorization string + var Authorization HeaderAuthorization n := len(valueList) if n != 1 { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Authorization, got %d", n)) @@ -809,7 +815,7 @@ func (w *ServerInterfaceWrapper) GetGames(ctx echo.Context) error { headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- if valueList, found := headers[http.CanonicalHeaderKey("Authorization")]; found { - var Authorization string + var Authorization HeaderAuthorization n := len(valueList) if n != 1 { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Authorization, got %d", n)) @@ -834,7 +840,7 @@ func (w *ServerInterfaceWrapper) GetGames(ctx echo.Context) error { func (w *ServerInterfaceWrapper) GetGame(ctx echo.Context) error { var err error // ------------- Path parameter "game_id" ------------- - var gameId int + var gameId PathGameId err = runtime.BindStyledParameterWithOptions("simple", "game_id", ctx.Param("game_id"), &gameId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) if err != nil { @@ -847,7 +853,7 @@ func (w *ServerInterfaceWrapper) GetGame(ctx echo.Context) error { headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- if valueList, found := headers[http.CanonicalHeaderKey("Authorization")]; found { - var Authorization string + var Authorization HeaderAuthorization n := len(valueList) if n != 1 { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Authorization, got %d", n)) @@ -887,7 +893,7 @@ func (w *ServerInterfaceWrapper) GetToken(ctx echo.Context) error { headers := ctx.Request().Header // ------------- Required header parameter "Authorization" ------------- if valueList, found := headers[http.CanonicalHeaderKey("Authorization")]; found { - var Authorization string + var Authorization HeaderAuthorization n := len(valueList) if n != 1 { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Authorization, got %d", n)) @@ -989,7 +995,7 @@ func (response AdminGetGames403JSONResponse) VisitAdminGetGamesResponse(w http.R } type AdminGetGameRequestObject struct { - GameId int `json:"game_id"` + GameId PathGameId `json:"game_id"` Params AdminGetGameParams } @@ -1042,7 +1048,7 @@ func (response AdminGetGame404JSONResponse) VisitAdminGetGameResponse(w http.Res } type AdminPutGameRequestObject struct { - GameId int `json:"game_id"` + GameId PathGameId `json:"game_id"` Params AdminPutGameParams Body *AdminPutGameJSONRequestBody } @@ -1186,7 +1192,7 @@ func (response GetGames403JSONResponse) VisitGetGamesResponse(w http.ResponseWri } type GetGameRequestObject struct { - GameId int `json:"game_id"` + GameId PathGameId `json:"game_id"` Params GetGameParams } @@ -1364,7 +1370,7 @@ func (sh *strictHandler) AdminGetGames(ctx echo.Context, params AdminGetGamesPar } // AdminGetGame operation middleware -func (sh *strictHandler) AdminGetGame(ctx echo.Context, gameId int, params AdminGetGameParams) error { +func (sh *strictHandler) AdminGetGame(ctx echo.Context, gameId PathGameId, params AdminGetGameParams) error { var request AdminGetGameRequestObject request.GameId = gameId @@ -1390,7 +1396,7 @@ func (sh *strictHandler) AdminGetGame(ctx echo.Context, gameId int, params Admin } // AdminPutGame operation middleware -func (sh *strictHandler) AdminPutGame(ctx echo.Context, gameId int, params AdminPutGameParams) error { +func (sh *strictHandler) AdminPutGame(ctx echo.Context, gameId PathGameId, params AdminPutGameParams) error { var request AdminPutGameRequestObject request.GameId = gameId @@ -1472,7 +1478,7 @@ func (sh *strictHandler) GetGames(ctx echo.Context, params GetGamesParams) error } // GetGame operation middleware -func (sh *strictHandler) GetGame(ctx echo.Context, gameId int, params GetGameParams) error { +func (sh *strictHandler) GetGame(ctx echo.Context, gameId PathGameId, params GetGameParams) error { var request GetGameRequestObject request.GameId = gameId @@ -1554,32 +1560,32 @@ func (sh *strictHandler) GetToken(ctx echo.Context, params GetTokenParams) error // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec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V+IrPN6OeOQB5ZbnGWTdHVHbYTzpGTWuG4w1k4KMBEnLy6k6DD4uiAyIDHBQdheu", + "QmSXvNJBEUXXKl6BynVN5O5wbJxZSWEDu0vpawlinyurX/mCBT9xcGlKIs4m5lKtwdIjCZ6D7N3yBTu5", + "TedOVjnBcUKa9p1hKuvkn3JOATNNnUlHeRmeuiyqSdtaaCg77VnusiKkdVlU4W7bVosjbMbNAGv9is7p", + "FCvBpQw0RMEwDe5gGpyP36EQfQEhTYih/sngpK/R8xQYTgkaodOT/kkf2YtM46Ke2bc3x4l12RxMUmgv", + "muurd7HeT9Ncgro0VGHj9nVDb1ST9Jy3s/mNtpJMOZN242G/X5QJBcxgwGlKSWTIe7fSJk19h9qMtAo/", + "UZBIn8JV1yaEhcBL5w2f3OCQRiqj90SqgM8Cy5GH6Kw/eIQuSd3Z1qF2zUr7eVxOlhJ8wDcEG+ynXWP/", + "mYspiWNgQRVWnapQyTdSZJYkWCxLvxROycNGqPceigvc3CvoO4r5cCdf44HhK+SIX2Y4MsHLEefG2scM", + "eM4M0PjPusb/O1fBjGesW8PXUpt5ewkqwFUopdmm5Bxnz56cnzOQ6kdub5sPtPhTPext7iC95qQdL3d+", + "s9YLeclzhGbztTZvVd6zVguPruxUOMsoXQZZGmNVFpB+1wn4jn3BlMRBEXGdpuG67GP5Ppbvx5Tva5MJ", + "VQWvOy89/+weMq4N1UscMir8XkOGGYl3DRlW5D5DhuU45uiLGjIwpaVjdLhvn6aPg/RxkP53D9K+I/Rx", + "ej5Oz8f26xmnZ52slM/thXjKpSNHx1yq94akq3k2xVLecRGvPbkWXwfDU9dA+8gLdlaWmWLrm4NmvMfU", + "B8X/grV3nXv972Tl/91PXUaIj/cbs6fOQGBKQy2TcPC1JtBIQKz3wlR+lSm09GbARVC5c23AkCACG9Ym", + "wivTbzqEPhqCl9hu/dej5omOHUcBlAsu1PeUfIE4wEbrwNopz/P8nwAAAP//7jff808wAAA=", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/backend/api/handlers.go b/backend/api/handlers.go index 164682d..26f7a7d 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -61,8 +61,8 @@ func (h *ApiHandler) AdminGetGames(ctx context.Context, request AdminGetGamesReq } func (h *ApiHandler) AdminGetGame(ctx context.Context, request AdminGetGameRequestObject, user *auth.JWTClaims) (AdminGetGameResponseObject, error) { - gameId := request.GameId - row, err := h.q.GetGameById(ctx, int32(gameId)) + gameID := request.GameId + row, err := h.q.GetGameById(ctx, int32(gameID)) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return AdminGetGame404JSONResponse{ @@ -205,14 +205,14 @@ func (h *ApiHandler) AdminGetUsers(ctx context.Context, request AdminGetUsersReq func (h *ApiHandler) PostLogin(ctx context.Context, request PostLoginRequestObject) (PostLoginResponseObject, error) { username := request.Body.Username password := request.Body.Password - userId, err := auth.Login(ctx, h.q, username, password) + userID, err := auth.Login(ctx, h.q, username, password) if err != nil { return PostLogin401JSONResponse{ Message: "Invalid username or password", }, nil } - user, err := h.q.GetUserById(ctx, int32(userId)) + user, err := h.q.GetUserById(ctx, int32(userID)) if err != nil { return PostLogin401JSONResponse{ Message: "Invalid username or password", @@ -278,8 +278,8 @@ func (h *ApiHandler) GetGames(ctx context.Context, request GetGamesRequestObject func (h *ApiHandler) GetGame(ctx context.Context, request GetGameRequestObject, user *auth.JWTClaims) (GetGameResponseObject, error) { // TODO: check user permission - gameId := request.GameId - row, err := h.q.GetGameById(ctx, int32(gameId)) + gameID := request.GameId + row, err := h.q.GetGameById(ctx, int32(gameID)) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return GetGame404JSONResponse{ diff --git a/frontend/app/.server/api/schema.d.ts b/frontend/app/.server/api/schema.d.ts index 1adfc86..37e9b8c 100644 --- a/frontend/app/.server/api/schema.d.ts +++ b/frontend/app/.server/api/schema.d.ts @@ -259,7 +259,10 @@ export interface components { }; }; responses: never; - parameters: never; + parameters: { + header_authorization: string; + path_game_id: number; + }; requestBodies: never; headers: never; pathItems: never; @@ -314,7 +317,7 @@ export interface operations { parameters: { query?: never; header: { - Authorization: string; + Authorization: components["parameters"]["header_authorization"]; }; path?: never; cookie?: never; @@ -351,7 +354,7 @@ export interface operations { parameters: { query?: never; header: { - Authorization: string; + Authorization: components["parameters"]["header_authorization"]; }; path?: never; cookie?: never; @@ -399,10 +402,10 @@ export interface operations { parameters: { query?: never; header: { - Authorization: string; + Authorization: components["parameters"]["header_authorization"]; }; path: { - game_id: number; + game_id: components["parameters"]["path_game_id"]; }; cookie?: never; }; @@ -461,7 +464,7 @@ export interface operations { parameters: { query?: never; header: { - Authorization: string; + Authorization: components["parameters"]["header_authorization"]; }; path?: never; cookie?: never; @@ -509,7 +512,7 @@ export interface operations { parameters: { query?: never; header: { - Authorization: string; + Authorization: components["parameters"]["header_authorization"]; }; path?: never; cookie?: never; @@ -557,10 +560,10 @@ export interface operations { parameters: { query?: never; header: { - Authorization: string; + Authorization: components["parameters"]["header_authorization"]; }; path: { - game_id: number; + game_id: components["parameters"]["path_game_id"]; }; cookie?: never; }; @@ -619,10 +622,10 @@ export interface operations { parameters: { query?: never; header: { - Authorization: string; + Authorization: components["parameters"]["header_authorization"]; }; path: { - game_id: number; + game_id: components["parameters"]["path_game_id"]; }; cookie?: never; }; diff --git a/openapi.yaml b/openapi.yaml index 637ea3d..1dd4614 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -53,11 +53,7 @@ paths: operationId: getToken summary: Get a short-lived access token parameters: - - in: header - name: Authorization - schema: - type: string - required: true + - $ref: '#/components/parameters/header_authorization' responses: '200': description: Successfully authenticated @@ -88,11 +84,7 @@ paths: operationId: getGames summary: List games parameters: - - in: header - name: Authorization - schema: - type: string - required: true + - $ref: '#/components/parameters/header_authorization' responses: '200': description: List of games @@ -136,16 +128,8 @@ paths: operationId: getGame summary: Get a game parameters: - - in: path - name: game_id - schema: - type: integer - required: true - - in: header - name: Authorization - schema: - type: string - required: true + - $ref: '#/components/parameters/header_authorization' + - $ref: '#/components/parameters/path_game_id' responses: '200': description: A game @@ -199,11 +183,7 @@ paths: operationId: adminGetUsers summary: List all users parameters: - - in: header - name: Authorization - schema: - type: string - required: true + - $ref: '#/components/parameters/header_authorization' responses: '200': description: List of users @@ -247,11 +227,7 @@ paths: operationId: adminGetGames summary: List games parameters: - - in: header - name: Authorization - schema: - type: string - required: true + - $ref: '#/components/parameters/header_authorization' responses: '200': description: List of games @@ -295,16 +271,8 @@ paths: operationId: adminGetGame summary: Get a game parameters: - - in: path - name: game_id - schema: - type: integer - required: true - - in: header - name: Authorization - schema: - type: string - required: true + - $ref: '#/components/parameters/header_authorization' + - $ref: '#/components/parameters/path_game_id' responses: '200': description: A game @@ -357,16 +325,8 @@ paths: operationId: adminPutGame summary: Update a game parameters: - - in: path - name: game_id - schema: - type: integer - required: true - - in: header - name: Authorization - schema: - type: string - required: true + - $ref: '#/components/parameters/header_authorization' + - $ref: '#/components/parameters/path_game_id' requestBody: required: true content: @@ -451,6 +411,19 @@ paths: required: - message components: + parameters: + header_authorization: + in: header + name: Authorization + schema: + type: string + required: true + path_game_id: + in: path + name: game_id + schema: + type: integer + required: true schemas: User: type: object -- cgit v1.2.3-70-g09d2 From d4b76effa883fc191b82027e7d76d1f34fcc2992 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Thu, 1 Aug 2024 21:11:12 +0900 Subject: refactor: simplify error responses in OpenAPI spec --- backend/api/generated.go | 149 ++++++++---------- backend/api/handler_wrapper.go | 44 ++++-- backend/api/handlers.go | 24 ++- backend/gen/api_handler_wrapper_gen.go | 8 +- frontend/app/.server/api/schema.d.ts | 277 +++++++-------------------------- openapi.yaml | 249 ++++++----------------------- 6 files changed, 237 insertions(+), 514 deletions(-) (limited to 'backend/api/handlers.go') diff --git a/backend/api/generated.go b/backend/api/generated.go index 47dd905..a643833 100644 --- a/backend/api/generated.go +++ b/backend/api/generated.go @@ -54,6 +54,11 @@ const ( AdminPutGameJSONBodyStateWaitingStart AdminPutGameJSONBodyState = "waiting_start" ) +// Error defines model for Error. +type Error struct { + Message string `json:"message"` +} + // Game defines model for Game. type Game struct { DisplayName string `json:"display_name"` @@ -213,6 +218,18 @@ type HeaderAuthorization = string // PathGameId defines model for path_game_id. type PathGameId = int +// BadRequest defines model for BadRequest. +type BadRequest = Error + +// Forbidden defines model for Forbidden. +type Forbidden = Error + +// NotFound defines model for NotFound. +type NotFound = Error + +// Unauthorized defines model for Unauthorized. +type Unauthorized = Error + // AdminGetGamesParams defines parameters for AdminGetGames. type AdminGetGamesParams struct { Authorization HeaderAuthorization `json:"Authorization"` @@ -953,6 +970,14 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL } +type BadRequestJSONResponse Error + +type ForbiddenJSONResponse Error + +type NotFoundJSONResponse Error + +type UnauthorizedJSONResponse Error + type AdminGetGamesRequestObject struct { Params AdminGetGamesParams } @@ -972,9 +997,7 @@ func (response AdminGetGames200JSONResponse) VisitAdminGetGamesResponse(w http.R return json.NewEncoder(w).Encode(response) } -type AdminGetGames401JSONResponse struct { - Message string `json:"message"` -} +type AdminGetGames401JSONResponse struct{ UnauthorizedJSONResponse } func (response AdminGetGames401JSONResponse) VisitAdminGetGamesResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -983,9 +1006,7 @@ func (response AdminGetGames401JSONResponse) VisitAdminGetGamesResponse(w http.R return json.NewEncoder(w).Encode(response) } -type AdminGetGames403JSONResponse struct { - Message string `json:"message"` -} +type AdminGetGames403JSONResponse struct{ ForbiddenJSONResponse } func (response AdminGetGames403JSONResponse) VisitAdminGetGamesResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1014,9 +1035,7 @@ func (response AdminGetGame200JSONResponse) VisitAdminGetGameResponse(w http.Res return json.NewEncoder(w).Encode(response) } -type AdminGetGame401JSONResponse struct { - Message string `json:"message"` -} +type AdminGetGame401JSONResponse struct{ UnauthorizedJSONResponse } func (response AdminGetGame401JSONResponse) VisitAdminGetGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1025,9 +1044,7 @@ func (response AdminGetGame401JSONResponse) VisitAdminGetGameResponse(w http.Res return json.NewEncoder(w).Encode(response) } -type AdminGetGame403JSONResponse struct { - Message string `json:"message"` -} +type AdminGetGame403JSONResponse struct{ ForbiddenJSONResponse } func (response AdminGetGame403JSONResponse) VisitAdminGetGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1036,9 +1053,7 @@ func (response AdminGetGame403JSONResponse) VisitAdminGetGameResponse(w http.Res return json.NewEncoder(w).Encode(response) } -type AdminGetGame404JSONResponse struct { - Message string `json:"message"` -} +type AdminGetGame404JSONResponse struct{ NotFoundJSONResponse } func (response AdminGetGame404JSONResponse) VisitAdminGetGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1065,9 +1080,7 @@ func (response AdminPutGame204Response) VisitAdminPutGameResponse(w http.Respons return nil } -type AdminPutGame400JSONResponse struct { - Message string `json:"message"` -} +type AdminPutGame400JSONResponse struct{ BadRequestJSONResponse } func (response AdminPutGame400JSONResponse) VisitAdminPutGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1076,9 +1089,7 @@ func (response AdminPutGame400JSONResponse) VisitAdminPutGameResponse(w http.Res return json.NewEncoder(w).Encode(response) } -type AdminPutGame401JSONResponse struct { - Message string `json:"message"` -} +type AdminPutGame401JSONResponse struct{ UnauthorizedJSONResponse } func (response AdminPutGame401JSONResponse) VisitAdminPutGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1087,9 +1098,7 @@ func (response AdminPutGame401JSONResponse) VisitAdminPutGameResponse(w http.Res return json.NewEncoder(w).Encode(response) } -type AdminPutGame403JSONResponse struct { - Message string `json:"message"` -} +type AdminPutGame403JSONResponse struct{ ForbiddenJSONResponse } func (response AdminPutGame403JSONResponse) VisitAdminPutGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1098,9 +1107,7 @@ func (response AdminPutGame403JSONResponse) VisitAdminPutGameResponse(w http.Res return json.NewEncoder(w).Encode(response) } -type AdminPutGame404JSONResponse struct { - Message string `json:"message"` -} +type AdminPutGame404JSONResponse struct{ NotFoundJSONResponse } func (response AdminPutGame404JSONResponse) VisitAdminPutGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1128,9 +1135,7 @@ func (response AdminGetUsers200JSONResponse) VisitAdminGetUsersResponse(w http.R return json.NewEncoder(w).Encode(response) } -type AdminGetUsers401JSONResponse struct { - Message string `json:"message"` -} +type AdminGetUsers401JSONResponse struct{ UnauthorizedJSONResponse } func (response AdminGetUsers401JSONResponse) VisitAdminGetUsersResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1139,9 +1144,7 @@ func (response AdminGetUsers401JSONResponse) VisitAdminGetUsersResponse(w http.R return json.NewEncoder(w).Encode(response) } -type AdminGetUsers403JSONResponse struct { - Message string `json:"message"` -} +type AdminGetUsers403JSONResponse struct{ ForbiddenJSONResponse } func (response AdminGetUsers403JSONResponse) VisitAdminGetUsersResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1169,9 +1172,7 @@ func (response GetGames200JSONResponse) VisitGetGamesResponse(w http.ResponseWri return json.NewEncoder(w).Encode(response) } -type GetGames401JSONResponse struct { - Message string `json:"message"` -} +type GetGames401JSONResponse struct{ UnauthorizedJSONResponse } func (response GetGames401JSONResponse) VisitGetGamesResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1180,9 +1181,7 @@ func (response GetGames401JSONResponse) VisitGetGamesResponse(w http.ResponseWri return json.NewEncoder(w).Encode(response) } -type GetGames403JSONResponse struct { - Message string `json:"message"` -} +type GetGames403JSONResponse struct{ ForbiddenJSONResponse } func (response GetGames403JSONResponse) VisitGetGamesResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1211,9 +1210,7 @@ func (response GetGame200JSONResponse) VisitGetGameResponse(w http.ResponseWrite return json.NewEncoder(w).Encode(response) } -type GetGame401JSONResponse struct { - Message string `json:"message"` -} +type GetGame401JSONResponse struct{ UnauthorizedJSONResponse } func (response GetGame401JSONResponse) VisitGetGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1222,9 +1219,7 @@ func (response GetGame401JSONResponse) VisitGetGameResponse(w http.ResponseWrite return json.NewEncoder(w).Encode(response) } -type GetGame403JSONResponse struct { - Message string `json:"message"` -} +type GetGame403JSONResponse struct{ ForbiddenJSONResponse } func (response GetGame403JSONResponse) VisitGetGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1233,9 +1228,7 @@ func (response GetGame403JSONResponse) VisitGetGameResponse(w http.ResponseWrite return json.NewEncoder(w).Encode(response) } -type GetGame404JSONResponse struct { - Message string `json:"message"` -} +type GetGame404JSONResponse struct{ NotFoundJSONResponse } func (response GetGame404JSONResponse) VisitGetGameResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1263,9 +1256,7 @@ func (response PostLogin200JSONResponse) VisitPostLoginResponse(w http.ResponseW return json.NewEncoder(w).Encode(response) } -type PostLogin401JSONResponse struct { - Message string `json:"message"` -} +type PostLogin401JSONResponse struct{ UnauthorizedJSONResponse } func (response PostLogin401JSONResponse) VisitPostLoginResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1293,9 +1284,7 @@ func (response GetToken200JSONResponse) VisitGetTokenResponse(w http.ResponseWri return json.NewEncoder(w).Encode(response) } -type GetToken401JSONResponse struct { - Message string `json:"message"` -} +type GetToken401JSONResponse struct{ UnauthorizedJSONResponse } func (response GetToken401JSONResponse) VisitGetTokenResponse(w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") @@ -1560,32 +1549,32 @@ func (sh *strictHandler) GetToken(ctx echo.Context, params GetTokenParams) error // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec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eG", + "Wt2jxWsT2ohvQ/MXltHywIbJltUd07VT7d73d0vc/xJuiZou5hBJ1/3tVn8wI53qdjDy1uzXlOytEdoJ", + "osdOKCwTyuP30OY9UcuFuxuoXTHsL0heBXY9VD1XWA9A7Zva1/Xhl6vGSkMMnNv02rKP5faliCz+dfp5", + "nVIbZb9WX+PxDsQ9C5RbnyfJ+itRu2E8aI2aNA3GhkvXB0/rNHi3JCIgIsBB1V24LiKz5JUOkshk48Yr", + "UbnGRO4Ox/DMaLKHZq5DXwng+4ysfmdLGvzKwHVSEjE61SNcS2RAUrwAMbhhS3p0ky2comKK45TY/p3j", + "RDTJP2MsAawHnLlwXC+jE5dH1db2KRSUTn9WVtaUtIZFNe62b5U6QudM/4A1cUVnyQxLzoQIFEROcRLc", + "wiw4m7xCIfoIXJjZ5vDo+Gio0LMMKM4IGqOTo+HREJmxuQ7RQNsdLHBqQrYAnRQqinp89SpW9tSeC5AX", + "eldozfq39EbNloHzXUBxvTFgHw2He017babV+ImEVPhcXM3dhDDneOWc8IktAbFnyK+JkAGbB0aiCNHp", + "8HgbhPrMA3vyrIROuoXWBvSqpuRpivmqglDaL0IrqoNP5ayy8IpvT+ENO+WsNzefgQ5+JHAE3SvmZ9rb", + "DxZsJXHaLVG/srHZcQEywDXgLN9GgUn+xSmg3548Z2Z8d2D0H+pNyfaS7NV4drwK8WteH8mrEUe+2C9b", + "i1Z+n7Z6InRp2ux5niSrIM9iLKtsGXZzf+0N7deRlVf6gHViNte26hO6i/GV3vUYi3GN36sY69axqxgb", + "lfsUYyPx5YoxTpIKg4rs7gbrW2/1FfVWvl3Vt4bqf9FQKUokbGF+dGZMOJgwYUK+1lv6anEyLMQt4/HG", + "WLN8ejw6cfU49/wRSysyl6avDyr792GhZH/DxuzkTv0drf3vHidpJT6UtNoRRTegUkGtGLc3Te3yL4AH", + "hjiaQ/Xhtl0m7/SGx1gh/lNxMbktlozLnxPyEeIAa3OBAVgURfFvAAAA//89QklP/CgAAA==", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/backend/api/handler_wrapper.go b/backend/api/handler_wrapper.go index 37a199b..939e37a 100644 --- a/backend/api/handler_wrapper.go +++ b/backend/api/handler_wrapper.go @@ -43,12 +43,16 @@ func (h *ApiHandlerWrapper) AdminGetGame(ctx context.Context, request AdminGetGa user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return AdminGetGame401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } if !user.IsAdmin { return AdminGetGame403JSONResponse{ - Message: "Forbidden", + ForbiddenJSONResponse: ForbiddenJSONResponse{ + Message: "Forbidden", + }, }, nil } return h.innerHandler.AdminGetGame(ctx, request, user) @@ -58,12 +62,16 @@ func (h *ApiHandlerWrapper) AdminGetGames(ctx context.Context, request AdminGetG user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return AdminGetGames401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } if !user.IsAdmin { return AdminGetGames403JSONResponse{ - Message: "Forbidden", + ForbiddenJSONResponse: ForbiddenJSONResponse{ + Message: "Forbidden", + }, }, nil } return h.innerHandler.AdminGetGames(ctx, request, user) @@ -73,12 +81,16 @@ func (h *ApiHandlerWrapper) AdminGetUsers(ctx context.Context, request AdminGetU user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return AdminGetUsers401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } if !user.IsAdmin { return AdminGetUsers403JSONResponse{ - Message: "Forbidden", + ForbiddenJSONResponse: ForbiddenJSONResponse{ + Message: "Forbidden", + }, }, nil } return h.innerHandler.AdminGetUsers(ctx, request, user) @@ -88,12 +100,16 @@ func (h *ApiHandlerWrapper) AdminPutGame(ctx context.Context, request AdminPutGa user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return AdminPutGame401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } if !user.IsAdmin { return AdminPutGame403JSONResponse{ - Message: "Forbidden", + ForbiddenJSONResponse: ForbiddenJSONResponse{ + Message: "Forbidden", + }, }, nil } return h.innerHandler.AdminPutGame(ctx, request, user) @@ -103,7 +119,9 @@ func (h *ApiHandlerWrapper) GetGame(ctx context.Context, request GetGameRequestO user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return GetGame401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } return h.innerHandler.GetGame(ctx, request, user) @@ -113,7 +131,9 @@ func (h *ApiHandlerWrapper) GetGames(ctx context.Context, request GetGamesReques user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return GetGames401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } return h.innerHandler.GetGames(ctx, request, user) @@ -123,7 +143,9 @@ func (h *ApiHandlerWrapper) GetToken(ctx context.Context, request GetTokenReques user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return GetToken401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } return h.innerHandler.GetToken(ctx, request, user) diff --git a/backend/api/handlers.go b/backend/api/handlers.go index 26f7a7d..35fc9f7 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -66,7 +66,9 @@ func (h *ApiHandler) AdminGetGame(ctx context.Context, request AdminGetGameReque if err != nil { if errors.Is(err, pgx.ErrNoRows) { return AdminGetGame404JSONResponse{ - Message: "Game not found", + NotFoundJSONResponse: NotFoundJSONResponse{ + Message: "Game not found", + }, }, nil } else { return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) @@ -113,7 +115,9 @@ func (h *ApiHandler) AdminPutGame(ctx context.Context, request AdminPutGameReque if err != nil { if err == pgx.ErrNoRows { return AdminPutGame404JSONResponse{ - Message: "Game not found", + NotFoundJSONResponse: NotFoundJSONResponse{ + Message: "Game not found", + }, }, nil } else { return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) @@ -175,7 +179,9 @@ func (h *ApiHandler) AdminPutGame(ctx context.Context, request AdminPutGameReque }) if err != nil { return AdminPutGame400JSONResponse{ - Message: err.Error(), + BadRequestJSONResponse: BadRequestJSONResponse{ + Message: err.Error(), + }, }, nil } @@ -208,14 +214,18 @@ func (h *ApiHandler) PostLogin(ctx context.Context, request PostLoginRequestObje userID, err := auth.Login(ctx, h.q, username, password) if err != nil { return PostLogin401JSONResponse{ - Message: "Invalid username or password", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Invalid username or password", + }, }, nil } user, err := h.q.GetUserById(ctx, int32(userID)) if err != nil { return PostLogin401JSONResponse{ - Message: "Invalid username or password", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Invalid username or password", + }, }, nil } @@ -283,7 +293,9 @@ func (h *ApiHandler) GetGame(ctx context.Context, request GetGameRequestObject, if err != nil { if errors.Is(err, pgx.ErrNoRows) { return GetGame404JSONResponse{ - Message: "Game not found", + NotFoundJSONResponse: NotFoundJSONResponse{ + Message: "Game not found", + }, }, nil } else { return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) diff --git a/backend/gen/api_handler_wrapper_gen.go b/backend/gen/api_handler_wrapper_gen.go index 01d05bf..7fd34b2 100644 --- a/backend/gen/api_handler_wrapper_gen.go +++ b/backend/gen/api_handler_wrapper_gen.go @@ -145,13 +145,17 @@ func parseJWTClaimsFromAuthorizationHeader(authorization string) (*auth.JWTClaim user, err := parseJWTClaimsFromAuthorizationHeader(request.Params.Authorization) if err != nil { return {{ .Name }}401JSONResponse{ - Message: "Unauthorized", + UnauthorizedJSONResponse: UnauthorizedJSONResponse{ + Message: "Unauthorized", + }, }, nil } {{ if .RequiresAdminRole -}} if !user.IsAdmin { return {{ .Name }}403JSONResponse{ - Message: "Forbidden", + ForbiddenJSONResponse: ForbiddenJSONResponse{ + Message: "Forbidden", + }, }, nil } {{ end -}} diff --git a/frontend/app/.server/api/schema.d.ts b/frontend/app/.server/api/schema.d.ts index 37e9b8c..6198064 100644 --- a/frontend/app/.server/api/schema.d.ts +++ b/frontend/app/.server/api/schema.d.ts @@ -128,6 +128,10 @@ export interface paths { export type webhooks = Record; export interface components { schemas: { + Error: { + /** @example Invalid request */ + message: string; + }; User: { /** @example 123 */ user_id: number; @@ -258,7 +262,44 @@ export interface components { stderr: string; }; }; - responses: never; + responses: { + /** @description Bad request */ + BadRequest: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Unauthorized */ + Unauthorized: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Forbidden */ + Forbidden: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found */ + NotFound: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; parameters: { header_authorization: string; path_game_id: number; @@ -299,18 +340,7 @@ export interface operations { }; }; }; - /** @description Invalid username or password */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Invalid credentials */ - message: string; - }; - }; - }; + 401: components["responses"]["Unauthorized"]; }; }; getToken: { @@ -336,18 +366,7 @@ export interface operations { }; }; }; - /** @description Unauthorized */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Unauthorized */ - message: string; - }; - }; - }; + 401: components["responses"]["Unauthorized"]; }; }; getGames: { @@ -372,30 +391,8 @@ export interface operations { }; }; }; - /** @description Unauthorized */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Unauthorized */ - message: string; - }; - }; - }; - /** @description Forbidden */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Forbidden operation */ - message: string; - }; - }; - }; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["Forbidden"]; }; }; getGame: { @@ -422,42 +419,9 @@ export interface operations { }; }; }; - /** @description Unauthorized */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Unauthorized */ - message: string; - }; - }; - }; - /** @description Forbidden */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Forbidden operation */ - message: string; - }; - }; - }; - /** @description Not found */ - 404: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Not found */ - message: string; - }; - }; - }; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["Forbidden"]; + 404: components["responses"]["NotFound"]; }; }; adminGetUsers: { @@ -482,30 +446,8 @@ export interface operations { }; }; }; - /** @description Unauthorized */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Unauthorized */ - message: string; - }; - }; - }; - /** @description Forbidden */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Forbidden operation */ - message: string; - }; - }; - }; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["Forbidden"]; }; }; adminGetGames: { @@ -530,30 +472,8 @@ export interface operations { }; }; }; - /** @description Unauthorized */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Unauthorized */ - message: string; - }; - }; - }; - /** @description Forbidden */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Forbidden operation */ - message: string; - }; - }; - }; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["Forbidden"]; }; }; adminGetGame: { @@ -580,42 +500,9 @@ export interface operations { }; }; }; - /** @description Unauthorized */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Unauthorized */ - message: string; - }; - }; - }; - /** @description Forbidden */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Forbidden operation */ - message: string; - }; - }; - }; - /** @description Not found */ - 404: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Not found */ - message: string; - }; - }; - }; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["Forbidden"]; + 404: components["responses"]["NotFound"]; }; }; adminPutGame: { @@ -656,54 +543,10 @@ export interface operations { }; content?: never; }; - /** @description Invalid request */ - 400: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Invalid request */ - message: string; - }; - }; - }; - /** @description Unauthorized */ - 401: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Unauthorized */ - message: string; - }; - }; - }; - /** @description Forbidden */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Forbidden operation */ - message: string; - }; - }; - }; - /** @description Not found */ - 404: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @example Not found */ - message: string; - }; - }; - }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["Forbidden"]; + 404: components["responses"]["NotFound"]; }; }; } diff --git a/openapi.yaml b/openapi.yaml index 1dd4614..683fadf 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -37,17 +37,7 @@ paths: required: - token '401': - description: Invalid username or password - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Invalid credentials" - required: - - message + $ref: '#/components/responses/Unauthorized' /token: get: operationId: getToken @@ -68,17 +58,7 @@ paths: required: - token '401': - description: Unauthorized - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Unauthorized" - required: - - message + $ref: '#/components/responses/Unauthorized' /games: get: operationId: getGames @@ -100,29 +80,9 @@ paths: required: - games '401': - description: Unauthorized - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Unauthorized" - required: - - message + $ref: '#/components/responses/Unauthorized' '403': - description: Forbidden - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Forbidden operation" - required: - - message + $ref: '#/components/responses/Forbidden' /games/{game_id}: get: operationId: getGame @@ -143,41 +103,11 @@ paths: required: - game '401': - description: Unauthorized - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Unauthorized" - required: - - message + $ref: '#/components/responses/Unauthorized' '403': - description: Forbidden - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Forbidden operation" - required: - - message + $ref: '#/components/responses/Forbidden' '404': - description: Not found - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Not found" - required: - - message + $ref: '#/components/responses/NotFound' /admin/users: get: operationId: adminGetUsers @@ -199,29 +129,9 @@ paths: required: - users '401': - description: Unauthorized - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Unauthorized" - required: - - message + $ref: '#/components/responses/Unauthorized' '403': - description: Forbidden - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Forbidden operation" - required: - - message + $ref: '#/components/responses/Forbidden' /admin/games: get: operationId: adminGetGames @@ -243,29 +153,9 @@ paths: required: - games '401': - description: Unauthorized - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Unauthorized" - required: - - message + $ref: '#/components/responses/Unauthorized' '403': - description: Forbidden - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Forbidden operation" - required: - - message + $ref: '#/components/responses/Forbidden' /admin/games/{game_id}: get: operationId: adminGetGame @@ -286,41 +176,11 @@ paths: required: - game '401': - description: Unauthorized - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Unauthorized" - required: - - message + $ref: '#/components/responses/Unauthorized' '403': - description: Forbidden - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Forbidden operation" - required: - - message + $ref: '#/components/responses/Forbidden' '404': - description: Not found - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Not found" - required: - - message + $ref: '#/components/responses/NotFound' put: operationId: adminPutGame summary: Update a game @@ -363,53 +223,13 @@ paths: '204': description: Successfully updated '400': - description: Invalid request - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Invalid request" - required: - - message + $ref: '#/components/responses/BadRequest' '401': - description: Unauthorized - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Unauthorized" - required: - - message + $ref: '#/components/responses/Unauthorized' '403': - description: Forbidden - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Forbidden operation" - required: - - message + $ref: '#/components/responses/Forbidden' '404': - description: Not found - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Not found" - required: - - message + $ref: '#/components/responses/NotFound' components: parameters: header_authorization: @@ -424,7 +244,40 @@ components: schema: type: integer required: true + responses: + BadRequest: + description: Bad request + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unauthorized: + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Forbidden: + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + NotFound: + description: Not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' schemas: + Error: + type: object + properties: + message: + type: string + example: "Invalid request" + required: + - message User: type: object properties: -- cgit v1.2.3-70-g09d2