简体   繁体   English

如何在Golang中保存会话

[英]How to save a session in golang

I'm trying to save a logged user ID in my golang backend with gorilla sessions and securecookie. 我正在尝试使用大猩猩会话和securecookie将记录的用户ID保存在golang后端中。

Here is my package session : 这是我的包裹会议:

package session

import (
    "fmt"
    "net/http"

    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(32))

//GetSessionLoggedID returns loggedID
func GetSessionLoggedID(r *http.Request) int {
    storeAuth, _ := store.Get(r, "authentication")
    if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {
        return storeAuth.Values["loggedID"].(int)
    }
    fmt.Println("none found")
    return 0
}

//SetSessionLoggedID sets cookie session user ID
func SetSessionLoggedID(w http.ResponseWriter, r *http.Request, id int) {
    storeAuth, err := store.Get(r, "authentication")
    if err != nil {
        fmt.Println(err.Error())
    }
    storeAuth.Options = &sessions.Options{HttpOnly: true, Secure: true, MaxAge: 2628000, Path: "/"}
    storeAuth.Values["loggedID"] = id
    storeAuth.Save(r, w)
}

I have another package that gets to verify email / password of a user that logs in. 我还有另一个软件包,可以用来验证登录用户的电子邮件/密码。

Here is the function : 这是函数:

func (handler *UserHandler) checkPassword(w http.ResponseWriter, r *http.Request) {
    var body struct {
        Email    string
        Password string
    }
    err := json.NewDecoder(r.Body).Decode(&body)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    loggedID, err := handler.UserUsecase.PasswordMatch(body.Email, body.Password)
    if err != nil || loggedID == 0 {
        http.Error(w, "Could not authenticate user", http.StatusUnauthorized)
        return
    }
    session.SetSessionLoggedID(w, r, loggedID)
    json.NewEncoder(w).Encode(struct {
        ID int `json:"id"`
    }{loggedID})
}

The ID returned is the proper one. 返回的ID是正确的ID。 But the session is not saving as I would have liked. 但是会话没有保存我想要的。

If I add a session.GetSessionLoggedID(r) at the end of checkpassword function, I get "none found". 如果在checkpassword函数的末尾添加session.GetSessionLoggedID(r) ,则会显示“未找到”。

What am I missing ? 我想念什么?

// watch this line
if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {

storeAuth.Values["loggedID"] is not bool , so ok is false , then you get "none found" storeAuth.Values["loggedID"]不是bool ,所以okfalse ,那么您将得到“未找到”

Change to 改成

    if auth, ok := storeAuth.Values["loggedID"]; ok{
        return auth.(int)
    }
    fmt.Println("none found")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM