auth_middleware.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package dash
  2. import (
  3. "net/http"
  4. "github.com/gin-contrib/sessions"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // ShowLogin displays the login page
  8. func (s *AdminServer) ShowLogin(c *gin.Context) {
  9. // If authentication is not required, redirect to admin
  10. session := sessions.Default(c)
  11. if session.Get("authenticated") == true {
  12. c.Redirect(http.StatusSeeOther, "/admin")
  13. return
  14. }
  15. // For now, return a simple login form as JSON
  16. c.HTML(http.StatusOK, "login.html", gin.H{
  17. "title": "SeaweedFS Admin Login",
  18. "error": c.Query("error"),
  19. })
  20. }
  21. // HandleLogin handles login form submission
  22. func (s *AdminServer) HandleLogin(username, password string) gin.HandlerFunc {
  23. return func(c *gin.Context) {
  24. loginUsername := c.PostForm("username")
  25. loginPassword := c.PostForm("password")
  26. if loginUsername == username && loginPassword == password {
  27. session := sessions.Default(c)
  28. session.Set("authenticated", true)
  29. session.Set("username", loginUsername)
  30. session.Save()
  31. c.Redirect(http.StatusSeeOther, "/admin")
  32. return
  33. }
  34. // Authentication failed
  35. c.Redirect(http.StatusSeeOther, "/login?error=Invalid credentials")
  36. }
  37. }
  38. // HandleLogout handles user logout
  39. func (s *AdminServer) HandleLogout(c *gin.Context) {
  40. session := sessions.Default(c)
  41. session.Clear()
  42. session.Save()
  43. c.Redirect(http.StatusSeeOther, "/login")
  44. }