package main import ( "log" "net/http" "time" "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 user := session.Get(SessionUser); user == nil { session.Clear() session.Save() ctx.JSON(http.StatusUnauthorized, gin.H{"message": "需要登录"}) return } else if user.(*User).Expired < time.Now().Unix() { session.Clear() session.Save() ctx.JSON(http.StatusUnauthorized, gin.H{"message": "账号过期"}) return } } ctx.Next() } func login(ctx *gin.Context) { userName := ctx.PostForm("user") session := sessions.Default(ctx) if userName == "" { if tokenUser := session.Get(SessionUser); tokenUser != nil { ctx.JSON(http.StatusOK, gin.H{"user": tokenUser}) return } } if realPassword, ok := GlobalConfig.GetUser(userName); ok { pwd := ctx.PostForm("pwd") if realPassword == pwd { user := &User{Name: userName, Expired: time.Now().Unix() + 15, ConfigPath: "", Config: nil, } 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() ctx.JSON(http.StatusOK, gin.H{"message": "退出登录成功"}) } func userConfig(ctx *gin.Context) { session := sessions.Default(ctx) userSession := session.Get(SessionUser) // log.Println(user) if userSession == nil { ctx.JSON(http.StatusUnauthorized, gin.H{"error": "权限错误"}) return } user := userSession.(*User) user.Config = map[string]string{"a": "b", "ocean-app-id": "dasdsa"} ctx.JSON(http.StatusOK, gin.H{"message": "获取配置成功", "user": user.Name, "config": user.Config}) } 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")) }