Home > front end >  Gin middleware context variable not preserving
Gin middleware context variable not preserving

Time:10-11

I am trying to get user's tasks by fetching them from database using user id gotten from gin context. The issue is in GetAllUsersTasks where userContext is <nil>. While in loggedIn the user from context fetches all the info. What am I missing here?

user.go

func loggedIn(c *gin.Context) {
    _, ok := c.Get("user")
    if ok != true {
        c.Status(http.StatusUnauthorized)
        return
    }
    c.Status(http.StatusOK)
}

func Authenticate(c *gin.Context) {
    cookieString, err := c.Cookie("jwt")
    if err != nil {
        log.Println(err.Error())
        return
    }

    user, err := getUserFromToken(cookieString)
    if err != nil {
        log.Println(err.Error())
        return
    }
    c.Set("user", *user)
}

func RegisterRoutes(router *gin.Engine) {

    //routes.GET("/:id", getUserById)
    //routes.DELETE("/:id", deleteUserById)

    routes := router.Group("/user")
    routes.POST("/login", loginUser)
    routes.POST("", createUser)

    routes.Use(Authenticate)
    routes.GET("/logout", logoutUser)
    routes.GET("/logged_in", loggedIn)
}

task.go

func GetAllUsersTasks(c *gin.Context) {
    userContext, ok := c.Get("user")
    if ok != true {
        c.Status(http.StatusUnauthorized)
    }
    u, ok := userContext.(db.User)
    if ok != true {
        c.Status(http.StatusUnauthorized)
    }

    allTasks, err := database.GetAllTasksByOwnerId(u.Id)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"GetAllTasksByOwnerId": err.Error()})
        return
    }
    c.JSON(http.StatusOK, allTasks)
}

func RegisterRoutes(router *gin.Engine) {
    routes := router.Group("/task")

    routes.Use(user.Authenticate)
    routes.GET("/all", GetAllUsersTasks)
}

CodePudding user response:

you should do like below:

func Authenticate() gin.HandlerFunc {
   return func(c *gin.Context) {

        cookieString, err := c.Cookie("jwt")
        if err != nil {
            log.Println(err.Error())
            return
        }

        user, err := getUserFromToken(cookieString)
        if err != nil {
            log.Println(err.Error())
            return
        }
        c.Set("user", *user)

   }
}

and write middleware like below:

routes.Use(Authenticate())

notice: about *user u should look at getUserFromToken() response

CodePudding user response:

Turns out the code is correct, I simply forgot to include credentials header in my fetch request from frontend..

  • Related