Skip to content

Commit

Permalink
feat(middleware): Validate user on all endpoints
Browse files Browse the repository at this point in the history
Pass user validation as a middleware instead of a SuccessFunc. Add
redirect to signout endpoint if user is not found. Add error logging for
failed user validation.

Ref: #321

Signed-off-by: Jo Vandeginste <[email protected]>
  • Loading branch information
jovandeginste committed Nov 8, 2024
1 parent c6d4ea0 commit bbecd7d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
3 changes: 2 additions & 1 deletion pkg/app/api_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ func (a *App) apiRoutes(e *echo.Group) {

return ctx.Request().URL.Query().Get("api-key") != ""
},
SuccessHandler: a.ValidateUserMiddleware,
}))
apiGroup.Use(a.ValidateUserMiddleware)

apiGroup.Use(middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{
Validator: a.ValidateAPIKeyMiddleware,
KeyLookup: "query:api-key",
Expand Down
22 changes: 14 additions & 8 deletions pkg/app/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,20 @@ func (a *App) ValidateAdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
}
}

func (a *App) ValidateUserMiddleware(ctx echo.Context) {
if err := a.setUser(ctx); err != nil {
log.Warn(err.Error())
}
func (a *App) ValidateUserMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
if err := a.setUser(ctx); err != nil {
a.logger.Warn("error validating user", "error", err.Error())
return ctx.Redirect(http.StatusFound, a.echo.Reverse("user-signout"))
}

u := a.getCurrentUser(ctx)
if u.IsAnonymous() || !u.IsActive() {
a.logger.Warn("user is not found")
return ctx.Redirect(http.StatusFound, a.echo.Reverse("user-signout"))
}

u := a.getCurrentUser(ctx)
if u.IsAnonymous() {
panic("User is not found")
return next(ctx)
}
}

Expand All @@ -118,8 +124,8 @@ func (a *App) addRoutesSecure(e *echo.Group) *echo.Group {
log.Warn(err.Error())
return c.Redirect(http.StatusFound, a.echo.Reverse("user-signout"))
},
SuccessHandler: a.ValidateUserMiddleware,
}))
secureGroup.Use(a.ValidateUserMiddleware)

secureGroup.GET("/", a.dashboardHandler).Name = "dashboard"
secureGroup.GET("/statistics", a.statisticsHandler).Name = "statistics"
Expand Down

0 comments on commit bbecd7d

Please sign in to comment.