func TestDataSessions(t *testing.T) { pool := newConnPool(t) userID, err := data.CreateUser(pool, newUser()) if err != nil { t.Fatal(err) } sessionID := []byte("deadbeef") err = data.InsertSession(pool, &data.Session{ ID: data.NewBytes(sessionID), UserID: data.NewInt32(userID), }, ) if err != nil { t.Fatal(err) } user, err := data.SelectUserBySessionID(pool, sessionID) if err != nil { t.Fatal(err) } if user.ID.Value != userID { t.Errorf("Expected %v, got %v", userID, user.ID) } err = data.DeleteSession(pool, sessionID) if err != nil { t.Fatal(err) } _, err = data.SelectUserBySessionID(pool, sessionID) if err != data.ErrNotFound { t.Fatalf("Expected %v, got %v", data.ErrNotFound, err) } err = data.DeleteSession(pool, sessionID) if err != data.ErrNotFound { t.Fatalf("Expected %v, got %v", notFound, err) } }
func getUserFromSession(req *http.Request, pool *pgx.ConnPool) *data.User { token := req.Header.Get("X-Authentication") if token == "" { token = req.FormValue("session") } var sessionID []byte sessionID, err := hex.DecodeString(token) if err != nil { return nil } // TODO - this could be an error from no records found -- or the connection could be dead or we could have a syntax error... user, err := data.SelectUserBySessionID(pool, sessionID) if err != nil { return nil } return user }