Skip to content

Instantly share code, notes, and snippets.

@reo7sp
Last active January 29, 2020 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reo7sp/c62f71d58a7ee9d833b8847b9304e854 to your computer and use it in GitHub Desktop.
Save reo7sp/c62f71d58a7ee9d833b8847b9304e854 to your computer and use it in GitHub Desktop.
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"net/url"
"strings"
"github.com/pkg/errors"
)
func DoQueryAuthAndReturnUserId(launchQuery string, vkSecret string) (*string, error) {
// parse
var vkUserId string
var vkSign []byte
query, err := url.ParseQuery(launchQuery)
if err != nil {
return nil, errors.Wrap(err, "cannot parse launch query string")
}
for key, vals := range query {
val := vals[0]
switch key {
case "vk_user_id":
vkUserId = val
case "sign":
vkSign = []byte(val)
}
if !strings.HasPrefix(key, "vk_") {
delete(query, key)
}
}
// hash
mac := hmac.New(sha256.New, []byte(vkSecret))
mac.Write([]byte(query.Encode()))
rawOurSignHmac := mac.Sum(nil)
encoding := base64.RawURLEncoding
rawOurSignBase64 := make([]byte, encoding.EncodedLen(len(rawOurSignHmac)))
encoding.Encode(rawOurSignBase64, rawOurSignHmac[:])
ourSign := rawOurSignBase64
// check
ok := bytes.Equal(ourSign, vkSign)
if ok {
return &vkUserId, nil
} else {
return nil, nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment