You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.8 KiB
70 lines
1.8 KiB
package api
|
|
|
|
import (
|
|
"context"
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/auth"
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/database"
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/models"
|
|
"git.aiterp.net/stufflog3/stufflog3-api/internal/slerrors"
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
func handler(key string, callback func(c *gin.Context) (interface{}, error)) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
res, err := callback(c)
|
|
if err != nil {
|
|
slerrors.Respond(c, err)
|
|
return
|
|
}
|
|
|
|
resJson := make(map[string]interface{}, 1)
|
|
resJson[key] = res
|
|
|
|
c.JSON(200, resJson)
|
|
}
|
|
}
|
|
|
|
func reqInt(c *gin.Context, key string) (int, error) {
|
|
v, err := strconv.Atoi(c.Param(key))
|
|
if err != nil {
|
|
return 0, slerrors.BadRequest(key + " parameter must be a number")
|
|
}
|
|
|
|
return v, nil
|
|
}
|
|
|
|
var scopeIdContextKey = struct{ stuff string }{stuff: "Things"}
|
|
|
|
func scopeIDMiddleware(db database.Database) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
scopeID, err := strconv.Atoi(c.Param("scope_id"))
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, slerrors.ErrorResponse{
|
|
Code: http.StatusBadRequest,
|
|
Message: "Invalid scope ID in path!",
|
|
})
|
|
|
|
return
|
|
}
|
|
|
|
scope, err := db.Scopes().Find(c.Request.Context(), scopeID, c.Request.Method != "GET")
|
|
if err != nil || !scope.HasMember(auth.UserID(c)) {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, slerrors.ErrorResponse{
|
|
Code: http.StatusNotFound,
|
|
Message: "Scope not found or you don't have permission to it!",
|
|
})
|
|
|
|
return
|
|
}
|
|
|
|
c.Request = c.Request.WithContext(
|
|
context.WithValue(c.Request.Context(), &scopeIdContextKey, scope),
|
|
)
|
|
}
|
|
}
|
|
|
|
func getScope(c *gin.Context) *models.Scope {
|
|
return c.Request.Context().Value(&scopeIdContextKey).(*models.Scope)
|
|
}
|