frontend: stop refreshing cookies

Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
Ahmet Alp Balkan 2018-06-25 23:20:51 -07:00
parent e16172c14a
commit 36b7b9eb65
4 changed files with 21 additions and 29 deletions

View file

@ -6,6 +6,7 @@ import (
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/gorilla/mux" "github.com/gorilla/mux"
@ -17,16 +18,6 @@ var (
templates = template.Must(template.ParseGlob("templates/*.html")) templates = template.Must(template.ParseGlob("templates/*.html"))
) )
func refreshCookies(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
for _, c := range r.Cookies() {
c.MaxAge = cookieMaxAge
http.SetCookie(w, c)
}
next(w, r)
}
}
func ensureSessionID(next http.HandlerFunc) http.HandlerFunc { func ensureSessionID(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var sessionID string var sessionID string
@ -58,13 +49,11 @@ func (fe *frontendServer) homeHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
log.Printf("currencies: %+v", currencies)
products, err := fe.getProducts(r.Context()) products, err := fe.getProducts(r.Context())
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
log.Printf("# products: %d", len(products))
type productView struct { type productView struct {
Item *pb.Product Item *pb.Product
@ -87,6 +76,7 @@ func (fe *frontendServer) homeHandler(w http.ResponseWriter, r *http.Request) {
"user_currency": currentCurrency(r), "user_currency": currentCurrency(r),
"currencies": currencies, "currencies": currencies,
"products": ps, "products": ps,
"session_id": r.Context().Value(ctxKeySessionID{}),
}); err != nil { }); err != nil {
log.Println(err) log.Println(err)
} }
@ -98,7 +88,7 @@ func (fe *frontendServer) productHandler(w http.ResponseWriter, r *http.Request)
http.Error(w, "product id not specified", http.StatusBadRequest) http.Error(w, "product id not specified", http.StatusBadRequest)
return return
} }
log.Printf("[productHandler] id=%s", id) log.Printf("[productHandler] id=%s currency=%s", id, currentCurrency(r))
p, err := fe.getProduct(r.Context(), id) p, err := fe.getProduct(r.Context(), id)
if err != nil { if err != nil {
http.Error(w, fmt.Sprintf("could not retrieve product: %+v", err), http.StatusInternalServerError) http.Error(w, fmt.Sprintf("could not retrieve product: %+v", err), http.StatusInternalServerError)
@ -128,6 +118,7 @@ func (fe *frontendServer) productHandler(w http.ResponseWriter, r *http.Request)
"user_currency": currentCurrency(r), "user_currency": currentCurrency(r),
"currencies": currencies, "currencies": currencies,
"product": product, "product": product,
"session_id": r.Context().Value(ctxKeySessionID{}),
}); err != nil { }); err != nil {
log.Println(err) log.Println(err)
} }
@ -136,6 +127,7 @@ func (fe *frontendServer) productHandler(w http.ResponseWriter, r *http.Request)
func (fe *frontendServer) logoutHandler(w http.ResponseWriter, r *http.Request) { func (fe *frontendServer) logoutHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("[home] session_id=%+v", r.Context().Value(ctxKeySessionID{})) log.Printf("[home] session_id=%+v", r.Context().Value(ctxKeySessionID{}))
for _, c := range r.Cookies() { for _, c := range r.Cookies() {
c.Expires = time.Now().Add(-time.Hour * 24 * 365)
c.MaxAge = -1 c.MaxAge = -1
http.SetCookie(w, c) http.SetCookie(w, c)
} }
@ -144,8 +136,8 @@ func (fe *frontendServer) logoutHandler(w http.ResponseWriter, r *http.Request)
} }
func (fe *frontendServer) setCurrencyHandler(w http.ResponseWriter, r *http.Request) { func (fe *frontendServer) setCurrencyHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("[setCurrency] session_id=%+v", r.Context().Value(ctxKeySessionID{}))
cur := r.FormValue("currency_code") cur := r.FormValue("currency_code")
log.Printf("[setCurrency] session_id=%+v code=%s", r.Context().Value(ctxKeySessionID{}), cur)
if cur != "" { if cur != "" {
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
Name: cookieCurrency, Name: cookieCurrency,
@ -153,7 +145,11 @@ func (fe *frontendServer) setCurrencyHandler(w http.ResponseWriter, r *http.Requ
MaxAge: cookieMaxAge, MaxAge: cookieMaxAge,
}) })
} }
w.Header().Set("Location", "/") referer := r.Header.Get("referer")
if referer == "" {
referer = "/"
}
w.Header().Set("Location", referer)
w.WriteHeader(http.StatusFound) w.WriteHeader(http.StatusFound)
} }

View file

@ -16,8 +16,9 @@ const (
defaultCurrency = "USD" defaultCurrency = "USD"
cookieMaxAge = 60 * 60 * 48 cookieMaxAge = 60 * 60 * 48
cookieSessionID = "session-id" cookiePrefix = "shop_"
cookieCurrency = "currency" cookieSessionID = cookiePrefix + "session-id"
cookieCurrency = cookiePrefix + "currency"
) )
var ( var (
@ -62,18 +63,11 @@ func main() {
} }
r := mux.NewRouter() r := mux.NewRouter()
r.HandleFunc("/", refreshCookies( r.HandleFunc("/", ensureSessionID(svc.homeHandler)).Methods(http.MethodGet, http.MethodHead)
ensureSessionID( r.HandleFunc("/product/{id}", ensureSessionID(svc.productHandler)).Methods(http.MethodGet, http.MethodHead)
svc.homeHandler))).Methods(http.MethodGet, http.MethodHead) r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
r.HandleFunc("/product/{id}", refreshCookies(
ensureSessionID(
svc.productHandler))).Methods(http.MethodGet, http.MethodHead)
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/",
http.FileServer(http.Dir("./static/"))))
r.HandleFunc("/logout", svc.logoutHandler).Methods(http.MethodGet) r.HandleFunc("/logout", svc.logoutHandler).Methods(http.MethodGet)
r.HandleFunc("/setCurrency", refreshCookies( r.HandleFunc("/setCurrency", ensureSessionID(svc.setCurrencyHandler)).Methods(http.MethodPost)
ensureSessionID(
svc.setCurrencyHandler))).Methods(http.MethodPost)
log.Printf("starting server on :" + srvPort) log.Printf("starting server on :" + srvPort)
log.Fatal(http.ListenAndServe("localhost:"+srvPort, r)) log.Fatal(http.ListenAndServe("localhost:"+srvPort, r))
} }

View file

@ -1,5 +1,7 @@
{{ define "footer" }} {{ define "footer" }}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
session-id: {{$.session_id}}
</body> </body>
</html> </html>
{{ end }} {{ end }}

View file

@ -3,7 +3,7 @@
<main role="main"> <main role="main">
<div class="py-5"> <div class="py-5">
<div class="container bg-light px-lg-5 py-lg-5"> <div class="container bg-light py-3 px-lg-5 py-lg-5">
<div class="row"> <div class="row">
<div class="col-12 col-lg-5"> <div class="col-12 col-lg-5">
<img class="img-fluid" style="width: 100%;" <img class="img-fluid" style="width: 100%;"