~netlandish/links

ref: 5851060eb47d9310b58d2b700fedd3779385ef24 links/client.go -rw-r--r-- 2.0 KiB
5851060ePeter Sanchez Add helper to stop bots from tag crawling. Now requests to public profiles, recent, and popular bookmarks pages will require login if they want to filter by more than 2 tags. 5 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package links

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"git.sr.ht/~emersion/gqlclient"
	oauth2 "netlandish.com/x/gobwebs-oauth2"
	"netlandish.com/x/gobwebs/auth"
	"netlandish.com/x/gobwebs/server"
)

// HTTPTransport custom http transport
type HTTPTransport struct {
	headers map[string]string
}

// AddHeader add headers for request
func (h *HTTPTransport) AddHeader(k, v string) {
	if h.headers == nil {
		h.headers = make(map[string]string)
	}
	h.headers[k] = v
}

// RoundTrip apply headers for request
func (h *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	for k, v := range h.headers {
		req.Header.Set(k, v)
	}
	return http.DefaultTransport.RoundTrip(req)
}

// Execute ...
func Execute(ctx context.Context, op *gqlclient.Operation, result interface{}) error {
	var (
		client     *gqlclient.Client
		httpClient *http.Client
		origin     string
	)

	srv := server.ForContext(ctx)
	user := auth.ForContext(ctx)

	if ostr, ok := srv.Config.File.Get("links", "api-origin"); ok {
		origin = ostr
	} else {
		origin = "http://127.0.0.1:8080/query"
	}

	trans := &HTTPTransport{}
	issued := time.Now().UTC()
	expires := issued.Add(30 * time.Second)
	grant := oauth2.BearerToken{
		Version:  oauth2.TokenVersion,
		Issued:   oauth2.ToTimestamp(issued),
		Expires:  oauth2.ToTimestamp(expires),
		Grants:   "",
		ClientID: "",
	}

	if user != nil && user.IsAuthenticated() {
		grant.Type = TypeWebAuth
		grant.UserID = int(user.GetID())
	} else {
		grant.Type = TypeInternal
		// Add Lang Header
		lang := LangForContext(ctx)
		trans.AddHeader("Accept-Language", lang)
	}

	token := grant.Encode(ctx)
	trans.AddHeader("Authorization", fmt.Sprintf("Internal %s", token))
	httpClient = &http.Client{
		Transport: trans,
		Timeout:   30 * time.Second,
	}

	client = gqlclient.New(origin, httpClient)
	err := client.Execute(ctx, op, &result)
	if graphErrors, ok := err.(interface{ Unwrap() []error }); ok {
		errs := graphErrors.Unwrap()
		err = errs[0]
	}
	return err
}
Do not follow this link