package main import ( "log" "net/http" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" ) const ( // SessionKey Session主Key SessionKey = "token" // SessionUser 用户登录的Session标签 SessionUser = "user" ) func auth(ctx *gin.Context) { if ctx.Request.RequestURI != "/api/login" { session := sessions.Default(ctx) if token := session.Get(SessionUser); token == nil { session.Clear() session.Save() ctx.JSON(http.StatusUnauthorized, gin.H{"message": "需要登录"}) return } } ctx.Next() } func login(ctx *gin.Context) { user := ctx.PostForm("user") session := sessions.Default(ctx) if user == "" { if tokenUser := session.Get(SessionUser); tokenUser != nil { ctx.JSON(http.StatusOK, gin.H{"user": tokenUser}) return } } if realPassword, ok := GlobalConfig.GetUser(user); ok { pwd := ctx.PostForm("pwd") if realPassword == pwd { session.Set(SessionUser, user) session.Save() ctx.JSON(http.StatusOK, gin.H{"message": "登录成功"}) return } ctx.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"}) return } ctx.JSON(http.StatusUnauthorized, gin.H{"error": "不存在该用户"}) return // ctx.Redirect(http.StatusOK, "/worker") // ctx.Next() } func logout(ctx *gin.Context) { session := sessions.Default(ctx) session.Clear() session.Save() } func userConfig(ctx *gin.Context) { session := sessions.Default(ctx) user := session.Get(SessionUser) // log.Println(user) if user == nil { ctx.JSON(http.StatusUnauthorized, gin.H{"error": "权限错误"}) return } ctx.JSON(http.StatusOK, gin.H{"message": "获取配置成功"}) } func main() { eg := gin.New() eg.Use(sessions.Sessions(SessionKey, cookie.NewStore([]byte("yame")))) eg.Use(auth) eg.POST("/api/login", login) eg.POST("/api/user/config", userConfig) eg.POST("/api/user/logout", logout) log.Fatal(eg.Run(":3001")) }