duai3681 2015-10-26 06:53
浏览 57
已采纳

如何在Cookie中通过地图传递多个值

Got stuck while passing multiple values in cookie. I'm not able to find a better way for managing session and cookies. Trying to use github.com/gorilla/securecookie this package.

loginMain.go

package main

import (
    "database/sql"
    "log"
    "net/http"
    "shambhavi/packages/loginPkg"   
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
)

var router = mux.NewRouter()
var db *sql.DB

func connectDb() *sql.DB {
    db, dberr := sql.Open("mysql", "root:root@tcp(127.0.0.1:8889)/shambhavi_db")
    if dberr != nil {
        log.Println(dberr)
    }
    return db
}
func login(w http.ResponseWriter, r *http.Request) {
    var db *sql.DB = connectDb()
    loginPkg.LoginOperation(w, r, db)

}

func main() {
    http.HandleFunc("/demo", login)
    http.Handle("/", router)
    err := http.ListenAndServe(port, nil) // setting listening port
if err != nil {
    log.Fatal("ListenAndServe: ", err)
}
}  

LoginPkg.go

package loginPkg

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "net/http"
    "shambhavi/packages/sessionPkg"

    _ "github.com/go-sql-driver/mysql"
)

var retMap = make(map[string]string)

func ErrorHandler(err error) {
    if err != nil {
        panic(err)
    }
}

func LoginOperation(w http.ResponseWriter, r *http.Request, db *sql.DB) {
    fmt.Println("In LoginOperation ")
    r.ParseForm()
    if len(r.Form["username"][0]) == 0 && len(r.Form["password"][0]) == 0 {
        fmt.Fprintf(w, "Something is blank !!!")
    } else {
        var lvl string
        var uFullName string
        err := db.QueryRow("SELECT lvl_flag FROM admin_instance WHERE user_name = ? AND passwd = ?", r.FormValue("username"), r.FormValue("password")).Scan(&lvl)

        er := db.QueryRow("SELECT emp_name FROM emp_detail WHERE emp_uname = ?", r.FormValue("username")).Scan(&uFullName)
        ErrorHandler(er)
        retMap["msg"] = "Login successfully"
        retMap["err"] = "Not Login"
        retMap["lvl"] = lvl
        retMap["fullName"] = uFullName
        b, _ := json.Marshal(retMap)
        if err != nil {
            fmt.Println(err)
            fmt.Fprintf(w, "%s", b)

        } else {
            if lvl == "1" || lvl == "2" || lvl == "3" {
                sessionPkg.SetSession(w, r, r.FormValue("username"), retMap) // Passing map to the fun, retMap
                fmt.Fprintf(w, "%s", b)
                usrnm := sessionPkg.GetUserName(r)
                fmt.Println("From session variable", usrnm)
            } else {
                fmt.Println("Chukala ....")
                fmt.Fprintf(w, "%s", b)
            }   
        }
    }
    defer db.Close()
}

The problem lies in following file....

sessionHandler.go

package sessionPkg

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gorilla/securecookie"
)

var cookieHandler = securecookie.New(
    securecookie.GenerateRandomKey(64),
    securecookie.GenerateRandomKey(32))


func SetSession(w http.ResponseWriter, r *http.Request, username string, retMap map[string]string) {

    sessionData := map[string]string{
        "userName": username,
        "lvl":      retMap["lvl"],
        "fullName": retMap["fullName"],
    }

    expiration := time.Now().Add(365 * 24 * time.Hour)

    //if encoded, err := cookieHandler.Encode("session", sessionData); err == nil {
    cookie := http.Cookie{
        Name:    "session",
        Value:   sessionData["userName"], //Here i want map or something else that can accept multiple values
        Expires: expiration,
        //MaxAge: 3600,
    }

    http.SetCookie(w, &cookie)
    //}
}

func GetUserName(request *http.Request) (userName string) {
    //fmt.Println(request.Cookie("session"))
    cookieValue := make(map[string]string)
    if cookie, err := request.Cookie("session"); err == nil {

        fmt.Println("cookieValue = ", cookie.Value)
        //if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
        //fmt.Println(cookie)
        cookieValue["userName"] = cookie.Value
        //fmt.Println(cookieValue["userName"])
        //}
        /*else {
            fmt.Println("Error ", err)
        }*/
    }
    return cookieValue["userName"]
}

/*func GetFullName(request *http.Request) (fullName string) {
    fmt.Println("In GetFullName")
    cookieValue := make(map[string]string)
    if cookie2, err := request.Cookie("session"); err == nil {

        fmt.Println("cookieValue = ", cookie2.Value)
        //if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
        fmt.Println(cookie2)
        cookieValue["fullName"] = cookie2.Value
        fmt.Println(cookieValue["fullName"])
        //}
    }
    return cookieValue["fullName"]
}*/

func ClearSession(response http.ResponseWriter) {
    cookie := &http.Cookie{
        Name:   "session",
        Value:  "",
        Path:   "/",
        MaxAge: -1,
    }
    http.SetCookie(response, cookie)
}

Problem indicated in code by comment. I want to use session like in PHP. Suggest the better way to secure the cookie and maintain the session. Give some explanation too.

Edited: Explain cookieHandler.Encode() and cookieHandler.Decode(). It is not decoding the data which is passed to it.

  • 写回答

1条回答 默认 最新

  • duanhuang7591 2015-10-26 08:02
    关注
    • var retMap = make(map[string]string) is a global map that you both read and write to, which is unsafe: when you have more than one user concurrently you will be overwriting the contents of this map.

    • You aren't using the securecookie package to encode your cookie values at all - in fact it's not clear where you're using it at all.

      cookie := http.Cookie{
          Name:    "session",
          // This should be encoded.
          Value:   sessionData["userName"], //Here i want map or something else that can accept multiple values
          Expires: expiration,
          //MaxAge: 3600,
      }
      
    • Too many packages: you have a loginpackage, a sessionpackage and a package main. Packages should fulfil a 'theme' - an auth package might make more sense, or even just a single package main until you get more familiar with Go.

    • You're not hashing your passwords - storing the plain text password in the database and looking it up with the value of r.FormValue("password") is extremely insecure. Read this to see how to hash passwords safely in Go: Golang/App Engine - securely hashing a user's password

    • You should be using the gorilla/sessions package rather than the lower-level securecookie package.

    Modifying the gorilla/sessions example in the documentation:

    package main
    
    import (
        "net/http"
        "github.com/gorilla/sessions"
    )
    
    // Use the CookieStore
    var store = sessions.NewCookieStore([]byte("something-very-secret"))
    
    func LoginOperation(w http.ResponseWriter, r *http.Request) {
        // Your existing DB code - shorter to make the example here clearer
        err := db.QueryRow("SELECT lvl_flag FROM admin_instance WHERE user_name = ? AND passwd = ?", r.FormValue("username"), r.FormValue("password")).Scan(&lvl)
    
        // Don't use a global map - create a new one
        userDetails := make(map[string]string)
        userDetails["msg"] = "Login successfully"
        userDetails["err"] = "Not Login"
        userDetails["lvl"] = lvl
        userDetails["fullName"] = uFullName
    
        // Get a session (existing/new)
        session, err := store.Get(r, "session-name")
        if err != nil {
            http.Error(w, err.Error(), 500)
            return
        }
    
        // Set some session values.
        session.Values["userDetails"] = userDetails
        // Save it before we write to the response/return from the handler.
        session.Save(r, w)
    }
    

    Later, if you want to retrieve the details:

    func RequireAuth(w http.ResponseWriter, r *http.Request) {
        // Get a session (existing/new)
        session, err := store.Get(r, "session-name")
        if err != nil {
            http.Error(w, err.Error(), 500)
            return
        }
    
        // Type assert our userDetails map out of the session's map[string]interface{}
        userDetails, ok := session.Values["userDetails"].(map[string]string)
        if !ok {
            // User does not have an existing session - treat them as not logged in and/or re-direct them to your login page.
            http.Error(w, http.StatusCode(401), 401)
            return
        }
    
    
        // Check the user details - e.g. if userDetails["lvl"] == "ACTIVE" { ... }
        // TODO
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?