Skip to content

Commit

Permalink
feat: add DestinationMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
mxyng committed Jul 4, 2022
1 parent accc0b9 commit c5d4360
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
33 changes: 33 additions & 0 deletions internal/server/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"gorm.io/gorm"

"github.com/infrahq/infra/internal"
"github.com/infrahq/infra/internal/access"
"github.com/infrahq/infra/internal/logging"
"github.com/infrahq/infra/internal/server/data"
"github.com/infrahq/infra/internal/server/models"
Expand Down Expand Up @@ -48,6 +49,38 @@ func DatabaseMiddleware(db *gorm.DB) gin.HandlerFunc {
}
}

func DestinationMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
uniqueID := c.GetHeader("Infra-Destination")
if uniqueID != "" {
destinations, err := access.ListDestinations(c, uniqueID, "", models.Pagination{})
if err != nil {
return
}

switch len(destinations) {
case 0:
// destination does not exist yet, noop
case 1:
destination := destinations[0]
// only save if there's significant difference between LastSeenAt and Now
if time.Since(destination.LastSeenAt) > time.Second {
destination.LastSeenAt = time.Now()
if err := access.SaveDestination(c, &destination); err != nil {
sendAPIError(c, err)
return
}
}
default:
sendAPIError(c, fmt.Errorf("multiple destinations found for unique ID %q", uniqueID))
return
}
}

c.Next()
}
}

// AuthenticationMiddleware validates the incoming token
func AuthenticationMiddleware(a *API) gin.HandlerFunc {
return func(c *gin.Context) {
Expand Down
5 changes: 4 additions & 1 deletion internal/server/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ func (s *Server) GenerateRoutes(promRegistry prometheus.Registerer) Routes {
)
apiGroup.GET("/.well-known/jwks.json", a.wellKnownJWKsHandler)

authn := apiGroup.Group("/", AuthenticationMiddleware(a))
authn := apiGroup.Group("/",
AuthenticationMiddleware(a),
DestinationMiddleware(),
)

get(a, authn, "/api/users", a.ListUsers)
post(a, authn, "/api/users", a.CreateUser)
Expand Down

0 comments on commit c5d4360

Please sign in to comment.