du8442 2019-01-18 11:21
浏览 140
已采纳

如何在Golang中保存会话

I'm trying to save a logged user ID in my golang backend with gorilla sessions and securecookie.

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. 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".

What am I missing ?

  • 写回答

1条回答 默认 最新

  • dongyaofu0599 2019-01-18 11:36
    关注
    // 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"

    Change to

        if auth, ok := storeAuth.Values["loggedID"]; ok{
            return auth.(int)
        }
        fmt.Println("none found")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效