/
client.go
101 lines (89 loc) · 2.6 KB
/
client.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
package authservice
import (
"context"
"fmt"
aurestbreaker "github.com/StephanHCB/go-autumn-restclient-circuitbreaker/implementation/breaker"
aurestclientapi "github.com/StephanHCB/go-autumn-restclient/api"
auresthttpclient "github.com/StephanHCB/go-autumn-restclient/implementation/httpclient"
aurestlogging "github.com/StephanHCB/go-autumn-restclient/implementation/requestlogging"
"github.com/eurofurence/reg-attendee-service/internal/repository/config"
"github.com/eurofurence/reg-attendee-service/internal/web/util/ctxvalues"
"github.com/go-http-utils/headers"
"net/http"
"time"
)
type Impl struct {
client aurestclientapi.Client
baseUrl string
}
func requestManipulator(ctx context.Context, r *http.Request) {
r.Header.Add(TraceIdHeader, ctxvalues.RequestId(ctx))
if ctxvalues.IdToken(ctx) == "" && ctxvalues.AccessToken(ctx) != "" {
r.Header.Add(headers.Authorization, "Bearer "+ctxvalues.AccessToken(ctx))
} else {
r.AddCookie(&http.Cookie{
Name: config.OidcIdTokenCookieName(),
Value: ctxvalues.IdToken(ctx),
Domain: "localhost",
Expires: time.Now().Add(10 * time.Minute),
Path: "/",
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
r.AddCookie(&http.Cookie{
Name: config.OidcAccessTokenCookieName(),
Value: ctxvalues.AccessToken(ctx),
Domain: "localhost",
Expires: time.Now().Add(10 * time.Minute),
Path: "/",
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
}
}
func newClient() (AuthService, error) {
httpClient, err := auresthttpclient.New(0, nil, requestManipulator)
if err != nil {
return nil, err
}
requestLoggingClient := aurestlogging.New(httpClient)
circuitBreakerClient := aurestbreaker.New(requestLoggingClient,
"auth-service-breaker",
10,
2*time.Minute,
30*time.Second,
15*time.Second,
)
return &Impl{
client: circuitBreakerClient,
baseUrl: config.AuthServiceBaseUrl(),
}, nil
}
func errByStatus(err error, status int) error {
if err != nil {
return err
}
if status == http.StatusUnauthorized {
return UnauthorizedError
}
if status >= 300 {
return DownstreamError
}
return nil
}
func (i Impl) IsEnabled() bool {
return true
}
func (i Impl) UserInfo(ctx context.Context) (UserInfoResponse, error) {
url := fmt.Sprintf("%s/v1/userinfo", i.baseUrl)
bodyDto := UserInfoResponse{}
response := aurestclientapi.ParsedResponse{
Body: &bodyDto,
}
err := i.client.Perform(ctx, http.MethodGet, url, nil, &response)
// TODO blank audience until properly available
bodyDto.Audiences = []string{}
return bodyDto, errByStatus(err, response.Status)
}