github.com/vmpartner/bitmex@v1.1.0/swagger/auth_util.go (about)

     1  package swagger
     2  
     3  import (
     4  	"crypto/hmac"
     5  	"crypto/sha256"
     6  	"encoding/hex"
     7  	"fmt"
     8  	"net/http"
     9  	"net/http/httputil"
    10  	"net/url"
    11  	"strconv"
    12  	"strings"
    13  	"time"
    14  	"regexp"
    15  )
    16  
    17  func SetAuthHeader(request *http.Request, apiKey APIKey, c *Configuration, httpMethod, path, postBody string,
    18  	queryParams url.Values) {
    19  	var expires = strconv.FormatInt(time.Now().Unix()+c.ExpireTime, 10)
    20  	request.Header.Add("api-key", apiKey.Key)
    21  	request.Header.Add("api-expires", expires)
    22  	p := regexp.MustCompile("/api.*").FindString(path)
    23  	request.Header.Add("api-signature", Signature(apiKey.Secret, httpMethod, p, queryParams.Encode(),
    24  		expires, postBody))
    25  }
    26  
    27  /**
    28   *  nonce: nonce or expires
    29   */
    30  func Signature(apiSecret, method, path, query, nonce, bodyStr string) string {
    31  	str := ""
    32  	if "" == query {
    33  		str = strings.ToUpper(method) + path + nonce + bodyStr
    34  	} else {
    35  		str = strings.ToUpper(method) + path + "?" + query + nonce + bodyStr
    36  	}
    37  	return CalSignature(apiSecret, str)
    38  }
    39  
    40  func CalSignature(apiSecret, payload string) string {
    41  	sig := hmac.New(sha256.New, []byte(apiSecret))
    42  	sig.Write([]byte(payload))
    43  	return hex.EncodeToString(sig.Sum(nil))
    44  }
    45  
    46  // Save a copy of this request for debugging.
    47  func DebugHttpRequest(r *http.Request) {
    48  	requestDump, err := httputil.DumpRequest(r, true)
    49  	if err != nil {
    50  		fmt.Println(err)
    51  	}
    52  	fmt.Println(string(requestDump))
    53  }