mercredi 20 janvier 2016

Cant handle working with gorila sessions well (golang)

I'm writing a web server. So I've got 3 html files: login.html, index.html and test.html test.html is static (I mean no forms) but it has a link: exit (for to handle it by golang server), index.html has registration form. Login.html has login form.

My problem is next:
I already have record in my database, so I go localhost:8080/login.html
I put my email and password, and create session with my name from database.
After that I am redirecting to localhost:8080/
Logic is: if maxage of my session is not -1 and name field is not empty than redirect me to localhost:8080/test.html
But when I press Exit link (going to localhost:8080/exit) my session is getting maxage of -1, and I am redrecting to localhost:8080/
Somewhy I am not going to index.html but to test.html
The most interest thing is when I refresh page.
Console says: Maxage is -1 or name is nil. Sending index.html
But I am still seeing test.html

Code is below, help me. I am quite new in server programming, and I maybe I just dont understand some kind of basics.

Ok, I've also got such server.go file:

func main() {
    logger.Init("./log", 10, 2, 2, false)

    logger.Info("Starting server")

    go func() {
        http.HandleFunc("/", handler.ViewHandler)
        http.HandleFunc("/exit", handler.ExitHandler)
        http.HandleFunc("/reg", regHandler.RegistrationHandler)
        http.HandleFunc("/log", logHandler.LoginHandler)
        http.HandleFunc("/commonProfileParts/send", pageCreatorHandler.CreateHandler)
        http.ListenAndServe(":8080", nil)
        http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
    }()

    logger.Info("Server started")
}

Here is my ExitHandler:

    func ExitHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Exiting...")

    Store_ := context.Get(r, "key")

    Store := sessfunc.GetStore(Store_, "teststring")

    session, err := Store.Get(r, "test")
    if err != nil {
        fmt.Println(err)
    }

    if session != nil {
        fmt.Println("Trying to delete... Name is ", session.Values["name"].(string))
        session.Options.MaxAge = -1
    }

    fmt.Println("Setting MaxAge to -1")

    session.Save(r, w)

    http.Redirect(w, r, "/", 301)
}

Part of LogHandler:

func LoginHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()

    email := r.Form["email"][0]
    pass := r.Form["pass"][0]

    db, err := sql.Open(config.DBdriver, config.GetDBIdentify())
    if err != nil {
        logger.Error("ERROR : ", err)
        return
    }
    rows, err := db.Query("SELECT ID, PasswordHash FROM Applications WHERE Email = ?", email)
    if err != nil {
        logger.Error("ERROR : ", err)
        return
    }

    defer rows.Close()

    if rows.Next() {
        var passwordHash string
        var id int
        rows.Scan(&id, &passwordHash)

        if passwordHash == hashMaker.GetHashMD5(pass) {
            logger.Info("Successfully logged in")

            namerows, err := db.Query("SELECT Name FROM Profiles WHERE ID = ?", id)
            if err != nil {
                logger.Error("ERROR : ", err)
                return
            }

            defer namerows.Close()

            var name string

            namerows.Next()
            namerows.Scan(&name)

            Store_ := context.Get(r, "key")

            Store := sessfunc.GetStore(Store_, "teststring")

            session := sessfunc.GetOrCreateSession(r, "test", Store)

            session.Values["name"] = name

            session.Save(r, w)

        } else {
            logger.Warn("WRONG : ", "Wrong password")
        }
    } else {
        logger.Warn("WRONG : ", "No such user registered")
    }

    http.Redirect(w, r, "/", 301)
}

And finally ViewHandler:

func ViewHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[1:] //[1:] - is to delete "/"
    if title == "" {
        title = config.StartPage
    }

    fmt.Println("Loaded title: ", title)

    Store_ := context.Get(r, "key")

    Store := sessfunc.GetStore(Store_, "teststring")

    session, err := Store.Get(r, "test")
    if err != nil {
        fmt.Println(err)
    }

    if session != nil {
        fmt.Println("Session found")
        if session.Options.MaxAge != -1 && session.Values["name"] != nil {
            fmt.Println("MaxAge: ", session.Options.MaxAge)
            fmt.Println("Name: ", session.Values["name"])
            if title == config.StartPage {
                title = config.LoggedStartPage
                fmt.Println("Title is ", title)
            }
        } else {
            fmt.Println("MAx age is -1 or name is nil, title is ", title)
        }
    } else {
        fmt.Println("Session not found, title is ", title)
    }

    fmt.Println("Sending", title)
    logger.Info("Sending... ", title)
    p, err := loadPage(title)

    if err != nil {
        logger.Error("ERROR : ", err.Error())
        p, _ := loadPage(config.Page404)
        fmt.Fprintf(w, "%s", p.body) //wired way to send HTML page
        return
    }

    http.ServeFile(w, r, p.dir)
    logger.Info(p.dir, " has been sent")
}

I guess I have to add loadPage function:

type page struct {
    dir  string
    body []byte
}

func loadPage(title string) (*page, error) {
    logger.Info("Trying to load", title)

    body, err := ioutil.ReadFile(title)
    if err != nil {
        return nil, err
    }

    return &page{dir: config.HOMEDIR + title, body: body}, nil
}




Aucun commentaire:

Enregistrer un commentaire