aboutsummaryrefslogtreecommitdiff
path: root/weed/admin/dash/auth_middleware.go
blob: 87da656590eb8dd8db28fc207e3053f9df33de89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package dash

import (
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/seaweedfs/seaweedfs/weed/glog"
)

// ShowLogin displays the login page
func (s *AdminServer) ShowLogin(c *gin.Context) {
	// If authentication is not required, redirect to admin
	session := sessions.Default(c)
	if session.Get("authenticated") == true {
		c.Redirect(http.StatusSeeOther, "/admin")
		return
	}

	// For now, return a simple login form as JSON
	c.HTML(http.StatusOK, "login.html", gin.H{
		"title": "SeaweedFS Admin Login",
		"error": c.Query("error"),
	})
}

// HandleLogin handles login form submission
func (s *AdminServer) HandleLogin(username, password string) gin.HandlerFunc {
	return func(c *gin.Context) {
		loginUsername := c.PostForm("username")
		loginPassword := c.PostForm("password")

		if loginUsername == username && loginPassword == password {
			session := sessions.Default(c)
			// Clear any existing invalid session data before setting new values
			session.Clear()
			session.Set("authenticated", true)
			session.Set("username", loginUsername)
			if err := session.Save(); err != nil {
				// Log the detailed error server-side for diagnostics
				glog.Errorf("Failed to save session for user %s: %v", loginUsername, err)
				c.Redirect(http.StatusSeeOther, "/login?error=Unable to create session. Please try again or contact administrator.")
				return
			}

			c.Redirect(http.StatusSeeOther, "/admin")
			return
		}

		// Authentication failed
		c.Redirect(http.StatusSeeOther, "/login?error=Invalid credentials")
	}
}

// HandleLogout handles user logout
func (s *AdminServer) HandleLogout(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	if err := session.Save(); err != nil {
		glog.Warningf("Failed to save session during logout: %v", err)
	}
	c.Redirect(http.StatusSeeOther, "/login")
}