Gin: Is it possible to save currentUser to varible

Created on 8 Nov 2018  路  3Comments  路  Source: gin-gonic/gin

I check for currentUser in next way

users := router.Group("/users")
    {
        users.Use(checkCurrentUser())
        users.GET("/show", controllers.ShowUser)
    }

and it check it correctly, but very often this currentUser needed inside handler, for example to get all his associations (doesn't matter).

// ShowUser shows information about user
func ShowUser(c *gin.Context) {
    user := gerCurrentUser(c) // I do additional request to the DB
    c.HTML(200, "showUser", gin.H{
        "currentUser": user,
    })
}

And I have to do additional request to the DB, to get this record.

Is It possible to save currentUser somewhere and use it inside the handler?

question

Most helpful comment

So I found how I can do it
Function Set() helped me
I can use it in me checkCurrentUser()

func checkCurrentUser() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)
        userID := session.Get("userID")
        user := new(models.User)
        configs.DB.First(&user, userID)
        if configs.DB.NewRecord(user) {
            c.Redirect(http.StatusPermanentRedirect, "/login")
        } else {
            c.Set("currentUser", user)
            c.Next()
        }
    }
}

and now I can get this instance with

currentUser := c.MustGet("currentUser")

Thx, issue may be closed!

All 3 comments

You can use redis

you can use session, jwt, redis..etc...

So I found how I can do it
Function Set() helped me
I can use it in me checkCurrentUser()

func checkCurrentUser() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)
        userID := session.Get("userID")
        user := new(models.User)
        configs.DB.First(&user, userID)
        if configs.DB.NewRecord(user) {
            c.Redirect(http.StatusPermanentRedirect, "/login")
        } else {
            c.Set("currentUser", user)
            c.Next()
        }
    }
}

and now I can get this instance with

currentUser := c.MustGet("currentUser")

Thx, issue may be closed!

Was this page helpful?
0 / 5 - 0 ratings