GoBlog/indieAuth.go

31 lines
895 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"
)
const indieAuthScope contextKey = "scope"
2021-02-08 17:51:07 +00:00
func (a *goBlog) checkIndieAuth(next http.Handler) http.Handler {
2020-10-06 17:07:48 +00:00
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
}
tokenData, err := a.db.verifyIndieAuthToken(bearerToken)
2020-10-06 17:07:48 +00:00
if err != nil {
a.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")))
})
}