github.com/retailcrm/mg-bot-helper@v0.0.0-20201229112329-a17255681a84/src/utils.go (about) 1 package main 2 3 import ( 4 "crypto/sha256" 5 "errors" 6 "fmt" 7 "net/http" 8 "strings" 9 "sync/atomic" 10 "time" 11 12 "github.com/nicksnyder/go-i18n/v2/i18n" 13 "github.com/retailcrm/api-client-go/v5" 14 ) 15 16 // GenerateToken function 17 func GenerateToken() string { 18 c := atomic.AddUint32(&tokenCounter, 1) 19 20 return fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%d%d", time.Now().UnixNano(), c)))) 21 } 22 23 func getAPIClient(url, key string) (*v5.Client, error, int) { 24 client := v5.New(url, key) 25 26 cr, _, e := client.APICredentials() 27 if e.RuntimeErr != nil { 28 return nil, e.RuntimeErr, http.StatusInternalServerError 29 } 30 31 if !cr.Success { 32 return nil, errors.New(getLocalizedMessage("incorrect_url_key")), http.StatusBadRequest 33 } 34 35 if res := checkCredentials(cr.Credentials); len(res) != 0 { 36 return nil, 37 errors.New(localizer.MustLocalize(&i18n.LocalizeConfig{ 38 MessageID: "missing_credentials", 39 TemplateData: map[string]interface{}{ 40 "Credentials": strings.Join(res, ", "), 41 }, 42 })), 43 http.StatusBadRequest 44 } 45 46 return client, nil, 0 47 } 48 49 func checkCredentials(credential []string) []string { 50 rc := make([]string, len(botCredentials)) 51 copy(rc, botCredentials) 52 53 for _, vc := range credential { 54 for kn, vn := range rc { 55 if vn == vc { 56 if len(rc) == 1 { 57 rc = rc[:0] 58 break 59 } 60 rc = append(rc[:kn], rc[kn+1:]...) 61 } 62 } 63 } 64 65 return rc 66 }