Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GetSession in gin-contrib/sessions returning nil of token #219

Open
Gravgor opened this issue Jan 15, 2023 · 5 comments
Open

GetSession in gin-contrib/sessions returning nil of token #219

Gravgor opened this issue Jan 15, 2023 · 5 comments

Comments

@Gravgor
Copy link

Gravgor commented Jan 15, 2023

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)
}
@jmillerv
Copy link

Having similar issues with similar looking code.

@VAISHAKH-GK
Copy link

Facing similar issue, did you find the solution ?

@jmillerv
Copy link

jmillerv commented Apr 6, 2023

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.

@hunick1234
Copy link

hunick1234 commented May 5, 2023

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" },
  });

`

@jmillerv
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants