Gorilla session package error : "securecookie: hash key is not set"

126 Views Asked by At

I created an HTTP API to register with the GIN HTTP package and Gorilla Sessions. But I get an error message like the following:

"error": "securecookie: hash key is not set"

here is my code :

package main

import(
    "github.com/joho/godotenv"
    "github.com/gin-gonic/gin"
    "github.com/gorilla/sessions"
    "os"
    "my-project/database"
)

type Register struct{
    Email string 'json:"email"' 
    Password string 'json:"password"'
}

var Store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

func Register(c *gin.Context){
    session, err := Store.Get(c.Request, "my-session")
    req := new(Register)
    err := c.ShouldBindJson(&req)
    if err != nil {
        c.Json(400, "failed to register")
        return
    }
    err = database.CreateUser(req)
    if err != nil {
        c.Json(500, "failed to create user")
        return
    }
    session.Values["email"] = req.Email
    err = session.Save(c.Request, c.Writer)
    if err != nil {
        c.Json(500, gin.H{"error":err.Error(),})
        return
    }
    c.Json(200, gin.H{
        "massage":"user created successfuly",
    })
}

func main(){
    err := godotenv.Load()
    if err != nil {
       panic(err)
    }
    r := gin.Default()
    r.Post("/register", Register)
    r.Run(":8080")
}

I want my postman to show JSON, like "User successfully created"

2

There are 2 best solutions below

1
luben On BEST ANSWER

This line is getting a key from ENV variable named SESSION_KEY:

var Store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

Most probably this variable is not set and that's why you get the error.

If you're running the program from terminal, check if it's there:

env | grep SESSION_KEY

If nothing comes out, then it's not and you should set it:

export SESSION_KEY="something"
0
Seva On

The issue is your Store variable is global and it is initialized before entering main() and thus before you load environment variables. You just need to move Store initialization after loading the environment.

func main(){    
    err := godotenv.Load()
    if err != nil {
       panic(err)
    }
    Store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

    r := gin.Default()
    r.POST("/register", webRegister)
    r.Run(":8080")
}

Also, gorilla cookie store saves all session data on the client. So, I would recommend adding an encryption key like this:

Store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")), []byte(os.Getenv("SESSION_ENC_KEY")))

And I would also recommend checking github.com/gin-contrib/sessions instead of using gorilla sessions directly. But it is a matter of preference.