62 lines
1.9 KiB
Go
62 lines
1.9 KiB
Go
|
|
package transport
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
|
||
|
|
"github.com/geo-platform/tenant-api/internal/shared/response"
|
||
|
|
"github.com/geo-platform/tenant-api/internal/tenant/app"
|
||
|
|
"github.com/geo-platform/tenant-api/internal/tenant/repository"
|
||
|
|
)
|
||
|
|
|
||
|
|
type desktopClientKey struct{}
|
||
|
|
|
||
|
|
func DesktopClientMiddleware(repo repository.DesktopClientRepository) gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
token, err := bearerClientToken(c.GetHeader("Authorization"))
|
||
|
|
if err != nil {
|
||
|
|
response.Error(c, response.ErrUnauthorized(40130, "missing_client_token", "desktop client token is required"))
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
client, err := repo.GetByTokenHash(c.Request.Context(), app.HashDesktopClientToken(token))
|
||
|
|
if err != nil {
|
||
|
|
response.Error(c, response.ErrUnauthorized(40131, "invalid_client_token", "desktop client token is invalid or revoked"))
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
ctx := WithDesktopClient(c.Request.Context(), client)
|
||
|
|
c.Request = c.Request.WithContext(ctx)
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func WithDesktopClient(ctx context.Context, client *repository.DesktopClient) context.Context {
|
||
|
|
return context.WithValue(ctx, desktopClientKey{}, client)
|
||
|
|
}
|
||
|
|
|
||
|
|
func DesktopClientFromCtx(ctx context.Context) (*repository.DesktopClient, bool) {
|
||
|
|
client, ok := ctx.Value(desktopClientKey{}).(*repository.DesktopClient)
|
||
|
|
return client, ok && client != nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func MustDesktopClient(ctx context.Context) *repository.DesktopClient {
|
||
|
|
client, ok := DesktopClientFromCtx(ctx)
|
||
|
|
if !ok {
|
||
|
|
panic("desktop client not in context")
|
||
|
|
}
|
||
|
|
return client
|
||
|
|
}
|
||
|
|
|
||
|
|
func bearerClientToken(header string) (string, error) {
|
||
|
|
parts := strings.SplitN(strings.TrimSpace(header), " ", 2)
|
||
|
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "bearer") || strings.TrimSpace(parts[1]) == "" {
|
||
|
|
return "", response.ErrUnauthorized(40130, "missing_client_token", "desktop client token is required")
|
||
|
|
}
|
||
|
|
return strings.TrimSpace(parts[1]), nil
|
||
|
|
}
|