sessions icon indicating copy to clipboard operation
sessions copied to clipboard

GetSession in gin-contrib/sessions returning nil of token

Open Gravgor opened this issue 1 year ago • 5 comments

0

So, i just created a backend setting session and getting session for my app. I would like to access via endpoint getting session i did that, but always session value returning nil even if i had set token inside session via SetSession function on userLogin.

I am using GIN framework + Gin/sessions on backend and Next.js on frontend.

I just tried checking session inside SetSession and there everything working fine, but when request come in from frontend hook, session returning nil which giving me message "Session expired" and error: true.

It should return me token and next check token via function and and the end return for the frontend token to let user enter /dashboard page.

I don't have any more idea why this happen and what can i do with that.

Code:

func GetSession(c *gin.Context) {
    session := sessions.Default(c)
    if value := session.Get("token"); value == nil {
        c.JSON(http.StatusUnauthorized, gin.H{
            "message": "No token present/Session expired",
            "error":   true,
        })
        return
    } else {
        token := value.(string)
        tokenCheck, _ := lib.CheckSecureToken(token)
        if tokenCheck == false {
            c.JSON(http.StatusUnauthorized, gin.H{
                "message": "Invalid token",
                "error":   true,
            })
            return
        }
        c.JSON(http.StatusOK, gin.H{
            "message": "Token present",
            "token":   value.(string),
            "error":   false,
        })
    }
    return
}
func SetSession(c *gin.Context, token string, status int) {
    session := sessions.Default(c)
    session.Set("token", token)
    err := session.Save()
    if err != nil {
        c.JSON(500, gin.H{
            "message": "Error saving session, user not logged in",
            "error":   true,
            "status":  500,
        })
    }
    c.JSON(status, gin.H{
        "message": "User logged in successfully",
        "token":   token,
        "error":   false,
        "status":  200,
    })
}
func SetupRouter() *gin.Engine {
    r := gin.Default()
    config := cors.DefaultConfig()
    store := cookie.NewStore([]byte("")) //Secret is set
    store.Options(sessions.Options{
        MaxAge: 60 * 60 * 24,
    })
    r.Use(sessions.Sessions("usersession", store))
    config.AllowOrigins = []string{"http://localhost:3000"}
    r.Use(cors.New(config))
    r.GET("/", home)

    //Auth routes
    authGroup := r.Group("/api/v1/auth")
    //authGroup.POST("/logout", logoutUser)
    //authGroup.POST("/refresh", refreshUser)
    //authGroup.POST("/forgot", forgotPassword)
    //authGroup.POST("/reset", resetPassword)
    authGroup.POST("/login", loginUser)
    authGroup.POST("/signup", createUser)
    authGroup.GET("/check", handler.GetSession)
func loginUser(c *gin.Context) {
    var user database.User
    err := c.BindJSON(&user)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "message": "User not found"})
        return
    }
    db, errS := database.LoginUser(&user)
    if errS != nil {
        c.JSON(http.StatusBadRequest, gin.H{"type": "Authentication Error", "message": "Invalid email or password", "status": "400"})
        return
    }
    token := lib.GenerateSecureToken(user.Email)
    if db.IsAdmin {
        adminToken := lib.GenerateAdminSecureToken(user.Email)
        cookieAdmin := adminToken
        handler.SetAdminSession(c, cookieAdmin, 200)
    }
    handler.SetSession(c, token, 200)
}

Gravgor avatar Jan 15 '23 18:01 Gravgor

Having similar issues with similar looking code.

jmillerv avatar Mar 24 '23 03:03 jmillerv

Facing similar issue, did you find the solution ?

VAISHAKH-GK avatar Apr 06 '23 17:04 VAISHAKH-GK

I haven't solved it yet. It's part of a side project for me, and I've had other issues to deal with. I might end up implementing sessions differently if I can't figure it out.

jmillerv avatar Apr 06 '23 18:04 jmillerv

maybe check your cookie is setting? similia issues . check backend Cors setting c.Header("Access-Control-Allow-Credentials", "true") and frontend request like me

` fetch(GET_USERINFO, {

    credentials: "include",  // <-- append this one
    method: "GET",
    headers: { "Content-Type": "application/json" },
  });

`

hunick1234 avatar May 05 '23 14:05 hunick1234

I'll try that and update here with what I find.

jmillerv avatar May 23 '23 16:05 jmillerv