middleware.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package dash
  2. import (
  3. "net/http"
  4. "github.com/gin-contrib/sessions"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // RequireAuth checks if user is authenticated
  8. func RequireAuth() gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. session := sessions.Default(c)
  11. authenticated := session.Get("authenticated")
  12. username := session.Get("username")
  13. if authenticated != true || username == nil {
  14. c.Redirect(http.StatusTemporaryRedirect, "/login")
  15. c.Abort()
  16. return
  17. }
  18. // Set username in context for use in handlers
  19. c.Set("username", username)
  20. c.Next()
  21. }
  22. }
  23. // RequireAuthAPI checks if user is authenticated for API endpoints
  24. // Returns JSON error instead of redirecting to login page
  25. func RequireAuthAPI() gin.HandlerFunc {
  26. return func(c *gin.Context) {
  27. session := sessions.Default(c)
  28. authenticated := session.Get("authenticated")
  29. username := session.Get("username")
  30. if authenticated != true || username == nil {
  31. c.JSON(http.StatusUnauthorized, gin.H{
  32. "error": "Authentication required",
  33. "message": "Please log in to access this endpoint",
  34. })
  35. c.Abort()
  36. return
  37. }
  38. // Set username in context for use in handlers
  39. c.Set("username", username)
  40. c.Next()
  41. }
  42. }