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

如何在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")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题