Как сохранить сеанс в Голанге - PullRequest
0 голосов
/ 18 января 2019

Я пытаюсь сохранить зарегистрированный идентификатор пользователя в моем бэкэнде golang с помощью сеансов горилл и securecookie.

Вот мой сеанс пакета:

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)
}

У меня есть другой пакет, который проверяет электронную почту / пароль пользователя, который входит в систему.

Вот функция:

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})
}

Возвращенный идентификатор является правильным. Но сессия не сохраняется, как мне бы хотелось.

Если я добавлю session.GetSessionLoggedID(r) в конце функции checkpassword, я получу «none found».

Чего мне не хватает?

1 Ответ

0 голосов
/ 18 января 2019
// watch this line
if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {

storeAuth.Values["loggedID"] не равно bool, поэтому ok равно false, тогда вы получите "ничего не найдено"

Изменить на

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