♻️ Used HTTP utils for user repository
This commit is contained in:
parent
ba1be08915
commit
d71039d6eb
|
@ -1,82 +1,19 @@
|
||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/tomnomnom/linkheader"
|
|
||||||
http "github.com/valyala/fasthttp"
|
http "github.com/valyala/fasthttp"
|
||||||
"willnorris.com/go/microformats"
|
|
||||||
|
|
||||||
"source.toby3d.me/website/indieauth/internal/domain"
|
"source.toby3d.me/website/indieauth/internal/domain"
|
||||||
"source.toby3d.me/website/indieauth/internal/user"
|
"source.toby3d.me/website/indieauth/internal/user"
|
||||||
|
"source.toby3d.me/website/indieauth/internal/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
type (
|
type httpUserRepository struct {
|
||||||
//nolint: tagliatelle
|
client *http.Client
|
||||||
Response struct {
|
}
|
||||||
// The server's issuer identifier. The issuer identifier is a
|
|
||||||
// URL that uses the "https" scheme and has no query or fragment
|
|
||||||
// components. The identifier MUST be a prefix of the
|
|
||||||
// indieauth-metadata URL. e.g. for an indieauth-metadata
|
|
||||||
// endpoint
|
|
||||||
// https://example.com/.well-known/oauth-authorization-server,
|
|
||||||
// the issuer URL could be https://example.com/, or for a
|
|
||||||
// metadata URL of
|
|
||||||
// https://example.com/wp-json/indieauth/1.0/metadata, the
|
|
||||||
// issuer URL could be https://example.com/wp-json/indieauth/1.0
|
|
||||||
Issuer *domain.URL `json:"issuer"`
|
|
||||||
|
|
||||||
// The Authorization Endpoint.
|
|
||||||
AuthorizationEndpoint *domain.URL `json:"authorization_endpoint"`
|
|
||||||
|
|
||||||
// The Token Endpoint.
|
|
||||||
TokenEndpoint *domain.URL `json:"token_endpoint"`
|
|
||||||
|
|
||||||
// JSON array containing scope values supported by the
|
|
||||||
// IndieAuth server. Servers MAY choose not to advertise some
|
|
||||||
// supported scope values even when this parameter is used.
|
|
||||||
ScopesSupported domain.Scopes `json:"scopes_supported,omitempty"`
|
|
||||||
|
|
||||||
// JSON array containing the response_type values supported.
|
|
||||||
// This differs from RFC8414 in that this parameter is OPTIONAL
|
|
||||||
// and that, if omitted, the default is code.
|
|
||||||
ResponseTypesSupported []domain.ResponseType `json:"response_types_supported,omitempty"`
|
|
||||||
|
|
||||||
// JSON array containing grant type values supported. If
|
|
||||||
// omitted, the default value differs from RFC8414 and is
|
|
||||||
// authorization_code.
|
|
||||||
GrantTypesSupported []domain.GrantType `json:"grant_types_supported,omitempty"`
|
|
||||||
|
|
||||||
// URL of a page containing human-readable information that
|
|
||||||
// developers might need to know when using the server. This
|
|
||||||
// might be a link to the IndieAuth spec or something more
|
|
||||||
// personal to your implementation.
|
|
||||||
ServiceDocumentation *domain.URL `json:"service_documentation,omitempty"`
|
|
||||||
|
|
||||||
// JSON array containing the methods supported for PKCE. This
|
|
||||||
// parameter differs from RFC8414 in that it is not optional as
|
|
||||||
// PKCE is REQUIRED.
|
|
||||||
CodeChallengeMethodsSupported []domain.CodeChallengeMethod `json:"code_challenge_methods_supported"`
|
|
||||||
|
|
||||||
// Boolean parameter indicating whether the authorization server
|
|
||||||
// provides the iss parameter. If omitted, the default value is
|
|
||||||
// false. As the iss parameter is REQUIRED, this is provided for
|
|
||||||
// compatibility with OAuth 2.0 servers implementing the
|
|
||||||
// parameter.
|
|
||||||
//
|
|
||||||
//nolint: lll
|
|
||||||
AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
httpUserRepository struct {
|
|
||||||
client *http.Client
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const DefaultMaxRedirectsCount int = 10
|
const DefaultMaxRedirectsCount int = 10
|
||||||
|
|
||||||
|
@ -105,8 +42,8 @@ func NewHTTPUserRepository(client *http.Client) user.Repository {
|
||||||
func (repo *httpUserRepository) Get(ctx context.Context, me *domain.Me) (*domain.User, error) {
|
func (repo *httpUserRepository) Get(ctx context.Context, me *domain.Me) (*domain.User, error) {
|
||||||
req := http.AcquireRequest()
|
req := http.AcquireRequest()
|
||||||
defer http.ReleaseRequest(req)
|
defer http.ReleaseRequest(req)
|
||||||
req.SetRequestURI(me.String())
|
|
||||||
req.Header.SetMethod(http.MethodGet)
|
req.Header.SetMethod(http.MethodGet)
|
||||||
|
req.SetRequestURI(me.String())
|
||||||
|
|
||||||
resp := http.AcquireResponse()
|
resp := http.AcquireResponse()
|
||||||
defer http.ReleaseResponse(resp)
|
defer http.ReleaseResponse(resp)
|
||||||
|
@ -115,147 +52,120 @@ func (repo *httpUserRepository) Get(ctx context.Context, me *domain.Me) (*domain
|
||||||
return nil, fmt.Errorf("cannot fetch user by me: %w", err)
|
return nil, fmt.Errorf("cannot fetch user by me: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
profile := domain.NewProfile()
|
|
||||||
profile.Name = extractValues(resp, propertyName)
|
|
||||||
|
|
||||||
for _, val := range extractValues(resp, propertyEmail) {
|
|
||||||
profile.Email = append(profile.Email, domain.Email(strings.TrimPrefix(val, "mailto:")))
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, val := range extractValues(resp, propertyPhoto) {
|
|
||||||
u, err := domain.NewURL(val)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
profile.Photo = append(profile.Photo, u)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, val := range extractValues(resp, propertyURL) {
|
|
||||||
u, err := domain.NewURL(val)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
profile.URL = append(profile.URL, u)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO(toby3d): handle error here?
|
// TODO(toby3d): handle error here?
|
||||||
resolvedMe, _ := domain.NewMe(string(resp.Header.Peek(http.HeaderLocation)))
|
resolvedMe, _ := domain.NewMe(string(resp.Header.Peek(http.HeaderLocation)))
|
||||||
|
|
||||||
u := &domain.User{
|
u := &domain.User{
|
||||||
Profile: profile,
|
Me: resolvedMe,
|
||||||
Me: resolvedMe,
|
Profile: &domain.Profile{
|
||||||
AuthorizationEndpoint: extractEndpoint(resp, relAuthorizationEndpoint),
|
Name: make([]string, 0),
|
||||||
IndieAuthMetadata: extractEndpoint(resp, relIndieAuthMetadata),
|
URL: make([]*domain.URL, 0),
|
||||||
Micropub: extractEndpoint(resp, relMicropub),
|
Photo: make([]*domain.URL, 0),
|
||||||
Microsub: extractEndpoint(resp, relMicrosub),
|
Email: make([]*domain.Email, 0),
|
||||||
TicketEndpoint: extractEndpoint(resp, relTicketEndpoint),
|
},
|
||||||
TokenEndpoint: extractEndpoint(resp, relTokenEndpoint),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if u.IndieAuthMetadata == nil {
|
metadata, err := util.ExtractMetadata(resp, repo.client)
|
||||||
return u, nil
|
if err == nil && metadata != nil {
|
||||||
|
u.AuthorizationEndpoint = metadata.AuthorizationEndpoint
|
||||||
|
u.Micropub = metadata.Micropub
|
||||||
|
u.Microsub = metadata.Microsub
|
||||||
|
u.TicketEndpoint = metadata.TicketEndpoint
|
||||||
|
u.TokenEndpoint = metadata.TokenEndpoint
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO(toby3d): handle error here?
|
extractUser(u, resp)
|
||||||
_ = extractFromMetadata(repo.client, u.IndieAuthMetadata, u)
|
extractProfile(u.Profile, resp)
|
||||||
|
|
||||||
return u, nil
|
return u, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func extractEndpoint(resp *http.Response, name string) *domain.URL {
|
func extractUser(dst *domain.User, src *http.Response) {
|
||||||
u, err := extractEndpointFromHeader(resp, name)
|
if dst.IndieAuthMetadata != nil {
|
||||||
if err == nil && u != nil {
|
if endpoints := util.ExtractEndpoints(src, relIndieAuthMetadata); len(endpoints) > 0 {
|
||||||
return u
|
dst.IndieAuthMetadata = endpoints[len(endpoints)-1]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if u, err = extractEndpointFromBody(resp, name); err == nil && u != nil {
|
if dst.AuthorizationEndpoint == nil {
|
||||||
return u
|
if endpoints := util.ExtractEndpoints(src, relAuthorizationEndpoint); len(endpoints) > 0 {
|
||||||
|
dst.AuthorizationEndpoint = endpoints[len(endpoints)-1]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
if dst.Micropub == nil {
|
||||||
|
if endpoints := util.ExtractEndpoints(src, relMicropub); len(endpoints) > 0 {
|
||||||
|
dst.Micropub = endpoints[len(endpoints)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if dst.Microsub == nil {
|
||||||
|
if endpoints := util.ExtractEndpoints(src, relMicrosub); len(endpoints) > 0 {
|
||||||
|
dst.Microsub = endpoints[len(endpoints)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if dst.TicketEndpoint == nil {
|
||||||
|
if endpoints := util.ExtractEndpoints(src, relTicketEndpoint); len(endpoints) > 0 {
|
||||||
|
dst.TicketEndpoint = endpoints[len(endpoints)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if dst.TokenEndpoint == nil {
|
||||||
|
if endpoints := util.ExtractEndpoints(src, relTokenEndpoint); len(endpoints) > 0 {
|
||||||
|
dst.TokenEndpoint = endpoints[len(endpoints)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func extractValues(resp *http.Response, key string) []string {
|
func extractProfile(dst *domain.Profile, src *http.Response) {
|
||||||
results := make([]string, 0)
|
for _, name := range util.ExtractProperty(src, hCard, propertyName) {
|
||||||
|
n, ok := name.(string)
|
||||||
for _, item := range microformats.Parse(bytes.NewReader(resp.Body()), nil).Items {
|
if !ok {
|
||||||
if len(item.Type) == 0 || item.Type[0] != hCard {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
properties, ok := item.Properties[key]
|
dst.Name = append(dst.Name, n)
|
||||||
if !ok || len(properties) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for j := range properties {
|
|
||||||
switch p := properties[j].(type) {
|
|
||||||
case string:
|
|
||||||
results = append(results, p)
|
|
||||||
case map[string][]interface{}:
|
|
||||||
for _, val := range p["value"] {
|
|
||||||
v, ok := val.(string)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
results = append(results, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return results
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
for _, rawEmail := range util.ExtractProperty(src, hCard, propertyEmail) {
|
||||||
}
|
email, ok := rawEmail.(string)
|
||||||
|
if !ok {
|
||||||
func extractEndpointFromHeader(resp *http.Response, name string) (*domain.URL, error) {
|
|
||||||
for _, link := range linkheader.Parse(string(resp.Header.Peek(http.HeaderLink))) {
|
|
||||||
if !strings.EqualFold(link.Rel, name) {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
u := http.AcquireURI()
|
e, err := domain.NewEmail(email)
|
||||||
if err := u.Parse(resp.Header.Peek(http.HeaderHost), []byte(link.URL)); err != nil {
|
if err != nil {
|
||||||
return nil, err
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
return &domain.URL{URI: u}, nil
|
dst.Email = append(dst.Email, e)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, nil
|
for _, rawUrl := range util.ExtractProperty(src, hCard, propertyURL) {
|
||||||
}
|
url, ok := rawUrl.(string)
|
||||||
|
if !ok {
|
||||||
func extractEndpointFromBody(resp *http.Response, name string) (*domain.URL, error) {
|
continue
|
||||||
host, err := url.Parse(string(resp.Header.Peek(http.HeaderHost)))
|
}
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot parse host header: %w", err)
|
u, err := domain.NewURL(url)
|
||||||
}
|
if err != nil {
|
||||||
|
continue
|
||||||
endpoints, ok := microformats.Parse(bytes.NewReader(resp.Body()), host).Rels[name]
|
}
|
||||||
if !ok || len(endpoints) == 0 {
|
|
||||||
return nil, nil
|
dst.URL = append(dst.URL, u)
|
||||||
}
|
}
|
||||||
|
|
||||||
return domain.NewURL(endpoints[len(endpoints)-1])
|
for _, rawPhoto := range util.ExtractProperty(src, hCard, propertyPhoto) {
|
||||||
}
|
photo, ok := rawPhoto.(string)
|
||||||
|
if !ok {
|
||||||
func extractFromMetadata(client *http.Client, endpoint *domain.URL, dst *domain.User) error {
|
continue
|
||||||
_, body, err := client.Get(nil, endpoint.String())
|
}
|
||||||
if err != nil {
|
|
||||||
return err
|
p, err := domain.NewURL(photo)
|
||||||
}
|
if err != nil {
|
||||||
|
continue
|
||||||
resp := new(Response)
|
}
|
||||||
if err = json.Unmarshal(body, resp); err != nil {
|
|
||||||
return err
|
dst.Photo = append(dst.Photo, p)
|
||||||
}
|
}
|
||||||
|
|
||||||
dst.AuthorizationEndpoint = resp.AuthorizationEndpoint
|
|
||||||
dst.TokenEndpoint = resp.TokenEndpoint
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,6 @@ package http_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
@ -85,12 +84,11 @@ func testHandler(tb testing.TB, user *domain.User) http.RequestHandler {
|
||||||
))
|
))
|
||||||
})
|
})
|
||||||
r.GET(string(user.IndieAuthMetadata.Path()), func(ctx *http.RequestCtx) {
|
r.GET(string(user.IndieAuthMetadata.Path()), func(ctx *http.RequestCtx) {
|
||||||
ctx.SetContentType(common.MIMEApplicationJSONCharsetUTF8)
|
ctx.SuccessString(common.MIMEApplicationJSONCharsetUTF8, `{
|
||||||
json.NewEncoder(ctx).Encode(repository.Response{
|
"issuer": "`+user.Me.String()+`",
|
||||||
Issuer: &domain.URL{URI: user.Me.URI()},
|
"authorization_endpoint": "`+user.AuthorizationEndpoint.String()+`",
|
||||||
AuthorizationEndpoint: user.AuthorizationEndpoint,
|
"token_endpoint": "`+user.TokenEndpoint.String()+`"
|
||||||
TokenEndpoint: user.TokenEndpoint,
|
}`)
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return r.Handler
|
return r.Handler
|
||||||
|
|
Loading…
Reference in New Issue