Created
April 22, 2022 16:25
-
-
Save salrashid123/4000bb8a9fd25a7b7046ab02ef35b1e6 to your computer and use it in GitHub Desktop.
hmac sha256 with bq remote function (no goroutine) (https://github.com/salrashid123/bq_cloud_function_golang)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package remote | |
import ( | |
"crypto/hmac" | |
"crypto/sha256" | |
"encoding/base64" | |
"encoding/json" | |
"fmt" | |
"io" | |
"net/http" | |
) | |
type bqRequest struct { | |
RequestId string `json:"requestId"` | |
Caller string `json:"caller"` | |
SessionUser string `json:"sessionUser"` | |
UserDefinedContext map[string]string `json:"userDefinedContext"` | |
Calls [][]interface{} `json:"calls"` | |
} | |
type bqResponse struct { | |
Replies []string `json:"replies,omitempty"` | |
ErrorMessage string `json:"errorMessage,omitempty"` | |
} | |
const () | |
var () | |
func init() {} | |
func HMAC_SHA256(w http.ResponseWriter, r *http.Request) { | |
bqReq := &bqRequest{} | |
bqResp := &bqResponse{} | |
if err := json.NewDecoder(r.Body).Decode(&bqReq); err != nil { | |
bqResp.ErrorMessage = fmt.Sprintf("External Function error: can't read POST body %v", err) | |
} else { | |
fmt.Printf("caller %s\n", bqReq.Caller) | |
fmt.Printf("sessionUser %s\n", bqReq.SessionUser) | |
fmt.Printf("userDefinedContext %v\n", bqReq.UserDefinedContext) | |
objs := make([]string, len(bqReq.Calls)) | |
for i, r := range bqReq.Calls { | |
if len(r) != 2 { | |
bqResp.ErrorMessage = fmt.Sprintf("Invalid number of input fields provided. expected 2, got %d", len(r)) | |
} | |
raw, ok := r[0].(string) | |
if !ok { | |
bqResp.ErrorMessage = "Invalid plaintext type. expected string" | |
} | |
key, ok := r[1].(string) | |
if !ok { | |
bqResp.ErrorMessage = "Invalid key type. expected string" | |
} | |
if bqResp.ErrorMessage != "" { | |
bqResp.Replies = nil | |
break | |
} | |
h := hmac.New(sha256.New, []byte(key)) | |
_, err = io.WriteString(h, raw) | |
if err != nil { | |
bqResp.ErrorMessage = fmt.Sprintf("Error writing hmac for row %d", i) | |
bqResp.Replies = nil | |
break | |
} | |
objs[i] = base64.StdEncoding.EncodeToString(h.Sum(nil)) | |
} | |
if bqResp.ErrorMessage != "" { | |
bqResp.Replies = nil | |
} else { | |
bqResp.Replies = objs | |
} | |
} | |
b, err := json.Marshal(bqResp) | |
if err != nil { | |
http.Error(w, fmt.Sprintf("can't convert response to JSON %v", err), http.StatusInternalServerError) | |
return | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.Write(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment