GoBlog/indieAuth.go

37 lines
995 B
Go
Raw Permalink 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-11-23 14:23:01 +00:00
2023-11-11 18:00:04 +00:00
"go.hacdias.com/indielib/indieauth"
2020-10-06 17:07:48 +00:00
)
const indieAuthScope contextKey = "scope"
2021-02-08 17:51:07 +00:00
2021-11-23 14:23:01 +00:00
func (a *goBlog) initIndieAuth() {
a.ias = indieauth.NewServer(
false,
2022-02-16 18:12:54 +00:00
a.httpClient,
2021-11-23 14:23:01 +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) {
2022-02-25 15:29:42 +00:00
bearerToken := defaultIfEmpty(r.Header.Get("Authorization"), r.URL.Query().Get("access_token"))
2021-11-23 14:23:01 +00:00
data, err := a.db.indieAuthVerifyToken(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-11-23 14:23:01 +00:00
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), indieAuthScope, strings.Join(data.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) {
next.ServeHTTP(rw, r.WithContext(context.WithValue(r.Context(), indieAuthScope, "create update delete undelete media")))
})
}