GoBlog/indieAuth.go

31 lines
883 B
Go
Raw Normal View History

2020-10-06 17:07:48 +00:00
package main
import (
"context"
2020-10-06 17:07:48 +00:00
"net/http"
"strings"
)
2021-02-08 17:51:07 +00:00
const indieAuthScope requestContextKey = "scope"
2020-10-06 17:07:48 +00:00
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 {
2020-12-24 09:09:34 +00:00
serveError(w, r, err.Error(), http.StatusUnauthorized)
2020-10-06 17:07:48 +00:00
return
}
2021-02-08 17:51:07 +00:00
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), indieAuthScope, strings.Join(tokenData.Scopes, " "))))
2020-10-06 17:07:48 +00:00
})
}
func addAllScopes(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
2021-02-08 17:51:07 +00:00
next.ServeHTTP(rw, r.WithContext(context.WithValue(r.Context(), indieAuthScope, "create update delete media")))
})
}