-
Notifications
You must be signed in to change notification settings - Fork 12
/
signer.go
executable file
·56 lines (51 loc) · 1.32 KB
/
signer.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
package oauth
import (
"bytes"
"crypto/rsa"
"errors"
"io"
"net/http"
)
// Signer represents the http request signer that holds the
// consumer key and the signing key.
type Signer struct {
ConsumerKey string
SigningKey *rsa.PrivateKey
}
// Sign signs the http request. It generates the authorization header and sets
// on the header of provided http request.
func (signer *Signer) Sign(req *http.Request) error {
if signer.ConsumerKey == "" {
return errors.New("signer: provide valid consumer key")
}
if signer.SigningKey == nil {
return errors.New("signer: provide valid signing key")
}
if req == nil {
return errors.New("signer: Nil http.Request provided")
}
body, err := getRequestBody(req)
if err != nil {
return err
}
authHeader, err := GetAuthorizationHeader(req.URL, req.Method, body, signer.ConsumerKey, signer.SigningKey)
if err != nil {
return err
}
req.Header.Set(AuthorizationHeaderName, authHeader)
return nil
}
// The getRequestBody extracts the body content from the given
// http request and returns in []byte format.
func getRequestBody(req *http.Request) ([]byte, error) {
if req.Body == nil {
return nil, nil
}
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
defer req.Body.Close()
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
return bodyBytes, nil
}