Working cross domain too

This commit is contained in:
bel
2019-10-20 17:13:00 -06:00
parent b1247f8733
commit a0bf41e04e
4 changed files with 95 additions and 33 deletions

View File

@@ -15,11 +15,46 @@ func Authenticate(server string, w http.ResponseWriter, r *http.Request) error {
if err != nil {
return err
}
access, err := r.Cookie(oauth2.COOKIE)
if err == http.ErrNoCookie {
access, exists := findAccess(w, r)
if !exists {
return login(oauth2server, w, r)
}
return verify(access.Value, oauth2server, w, r)
return verify(access, oauth2server, w, r)
}
func findAccess(w http.ResponseWriter, r *http.Request) (string, bool) {
fresh, exists := findAccessFresh(w, r)
if exists {
return fresh, true
}
stable, exists := findAccessStable(w, r)
return stable, exists
}
func findAccessFresh(w http.ResponseWriter, r *http.Request) (string, bool) {
q := r.URL.Query()
access := q.Get(oauth2.COOKIE)
q.Del(oauth2.COOKIE)
r.URL.RawQuery = q.Encode()
if access == "" {
return "", false
}
cookie := &http.Cookie{
Name: oauth2.COOKIE,
Value: access,
SameSite: http.SameSiteLaxMode,
Path: "/",
}
http.SetCookie(w, cookie)
return access, true
}
func findAccessStable(w http.ResponseWriter, r *http.Request) (string, bool) {
access, err := r.Cookie(oauth2.COOKIE)
if err == http.ErrNoCookie {
return "", false
}
return access.Value, true
}
func login(oauth2server *url.URL, w http.ResponseWriter, r *http.Request) error {
@@ -29,13 +64,9 @@ func login(oauth2server *url.URL, w http.ResponseWriter, r *http.Request) error
if url.Scheme == "" {
url.Scheme = "http"
}
cookie := &http.Cookie{
Name: oauth2.REDIRECT,
Value: url.String(),
SameSite: http.SameSiteLaxMode,
Path: "/authorize",
}
http.SetCookie(w, cookie)
q := oauth2server.Query()
q.Set(oauth2.REDIRECT, url.String())
oauth2server.RawQuery = q.Encode()
http.Redirect(w, r, oauth2server.String(), http.StatusSeeOther)
return errors.New("logging in")
}
@@ -63,3 +94,16 @@ func verify(access string, oauth2server *url.URL, w http.ResponseWriter, r *http
}
return nil
}
func setCookie(access string, w http.ResponseWriter) {
cookie := &http.Cookie{
Name: oauth2.COOKIE,
Value: access,
SameSite: http.SameSiteLaxMode,
Path: "/",
}
if access == "" {
cookie.Expires = time.Now().Add(-1 * time.Hour)
}
http.SetCookie(w, cookie)
}