Pārlūkot izejas kodu

Store login state in reverse proxy URL

It's easier and less complex than writing a Grav plugin to make backend
requests each time a page is loaded.
master
Immanuel Onyeka pirms 10 mēnešiem
vecāks
revīzija
3c7d506917
1 mainītis faili ar 31 papildinājumiem un 7 dzēšanām
  1. +31
    -7
      skouter.go

+ 31
- 7
skouter.go Parādīt failu

@@ -964,7 +964,7 @@ func setTokenCookie(id int, role string, w http.ResponseWriter) error {
func refreshToken(w http.ResponseWriter, db *sql.DB, r *http.Request) {
claims, _ := getClaims(r)
if !claims.Valid() {
if claims.Valid() != nil {
return
}
@@ -3571,7 +3571,7 @@ func api(w http.ResponseWriter, r *http.Request) {
login(w, db, r)
case match(p, "/api/token", &args) &&
r.Method == http.MethodGet && guard(r, 1):
getToken(w, db, r)
refreshToken(w, db, r)
case match(p, "/api/letterhead", &args) &&
r.Method == http.MethodPost && guard(r, 1):
clipLetterhead(w, db, r)
@@ -3717,19 +3717,43 @@ func route(w http.ResponseWriter, r *http.Request) {
page.Render(w)
}

// The grav frontend does not have controllers to communicate state
// with backend so the user's login status must be represented by a
// query parameter during proxy.
func setupProxy(r *httputil.ProxyRequest) {
proxyURL, err := url.Parse("http://localhost:8002")
if err != nil {
log.Fatal("invalid origin server URL")
}
r.In.ParseForm()
claims, _ := getClaims(r.In)
q := r.Out.URL.Query()
r.SetURL(proxyURL)
// Check if user is logged in, then set or delete the logged_in param
if claims.Valid() == nil {
q.Set("logged_in", "true")
} else {
q.Del("logged_in")
}
r.Out.URL.RawQuery = q.Encode()
}

func serve() {

files := http.FileServer(http.Dir(""))

proxy, err := url.Parse("http://localhost:8002")
if err != nil {
log.Fatal("invalid origin server URL")
proxy := &httputil.ReverseProxy{
Rewrite: setupProxy,
}

http.Handle("/assets/", files)
http.HandleFunc("/api/", api)
http.HandleFunc("/app", route)
http.Handle("/", httputil.NewSingleHostReverseProxy(proxy))
http.Handle("/", proxy)
log.Fatal(http.ListenAndServe(address, nil))
}



Notiek ielāde…
Atcelt
Saglabāt