2020-10-06 17:07:48 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-10-14 16:23:56 +00:00
|
|
|
"context"
|
2020-10-06 17:07:48 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
func checkIndieAuth(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
bearerToken := r.Header.Get("Authorization")
|
|
|
|
if len(bearerToken) == 0 {
|
2020-10-13 19:35:39 +00:00
|
|
|
bearerToken = r.URL.Query().Get("access_token")
|
2020-10-06 17:07:48 +00:00
|
|
|
}
|
2020-10-13 19:35:39 +00:00
|
|
|
tokenData, err := verifyIndieAuthToken(bearerToken)
|
2020-10-06 17:07:48 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
2020-10-14 16:23:56 +00:00
|
|
|
if err := compareHostnames(tokenData.Me, appConfig.Server.Domain); err != nil {
|
2020-10-06 17:07:48 +00:00
|
|
|
http.Error(w, "Forbidden", http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
2020-10-14 16:23:56 +00:00
|
|
|
ctx := context.WithValue(r.Context(), "scope", strings.Join(tokenData.Scopes, " "))
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
2020-10-06 17:07:48 +00:00
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func compareHostnames(a string, allowed string) error {
|
|
|
|
h1, err := url.Parse(a)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if strings.ToLower(h1.Hostname()) != strings.ToLower(allowed) {
|
|
|
|
return fmt.Errorf("hostnames do not match, %s is not %s", h1, allowed)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|