github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/blogweb_gin/controllers/session_controller.go (about)

     1  // 用于获取session,查看用户是否登录
     2  package controllers
     3  
     4  import (
     5  	"github.com/gin-contrib/sessions"
     6  	"github.com/gin-gonic/gin"
     7  	"github.com/qiuhoude/go-web/blogweb_gin/logs"
     8  	"net/http"
     9  )
    10  
    11  const (
    12  	SessionKey      = "loginSession" // 浏览器 cookie 的名字
    13  	SessionStoreKey = "loginuser"
    14  )
    15  
    16  func GetSession(c *gin.Context) bool {
    17  	session := sessions.Default(c)
    18  	loginuser := session.Get(SessionStoreKey)
    19  	logs.Info.Println("loginuser:", loginuser)
    20  	if loginuser != nil {
    21  		return true
    22  	} else {
    23  		return false
    24  	}
    25  }
    26  
    27  //退出
    28  func ExitGet(c *gin.Context) {
    29  	session := sessions.Default(c)
    30  	//清除该用户登录状态的数据
    31  	session.Delete(SessionStoreKey)
    32  	session.Save()
    33  	session.Clear()
    34  
    35  	logs.Info.Println("delete session...", session.Get(SessionStoreKey))
    36  	c.Redirect(http.StatusMovedPermanently, "/")
    37  }
    38  
    39  func IsLoginMiddle(c *gin.Context) {
    40  	if c.Request.Method == http.MethodGet && GetSession(c) {
    41  		c.Redirect(http.StatusMovedPermanently, "/")
    42  		return
    43  	}
    44  	c.Next()
    45  }
    46  
    47  // 需要登陆才能操作的中间件
    48  func NeedLoginMiddle(c *gin.Context) {
    49  	if !GetSession(c) {
    50  		c.Redirect(http.StatusMovedPermanently, "/login")
    51  		return
    52  	}
    53  	c.Next()
    54  }