auth.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package oppo
  2. import (
  3. "crypto/sha256"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "time"
  10. )
  11. // Auth oppo auth token.
  12. type Auth struct {
  13. Token string
  14. Expire int64
  15. }
  16. type authResponse struct {
  17. Code int `json:"code"`
  18. Message string `json:"message"`
  19. Data struct {
  20. Token string `json:"auth_token"`
  21. CreateTime int64 `json:"create_time"` // auth token的授权时间,单位为毫秒
  22. } `json:"data"`
  23. }
  24. // NewAuth get auth token.
  25. func NewAuth(key, secret string) (a *Auth, err error) {
  26. tm := strconv.FormatInt(time.Now().UnixNano()/1000000, 10) // 用毫秒
  27. params := url.Values{}
  28. params.Add("app_key", key)
  29. params.Add("timestamp", tm)
  30. params.Add("sign", sign(key, secret, tm))
  31. res, err := http.PostForm(_apiAuth, params)
  32. if err != nil {
  33. return
  34. }
  35. defer res.Body.Close()
  36. dc := json.NewDecoder(res.Body)
  37. resp := new(authResponse)
  38. if err = dc.Decode(resp); err != nil {
  39. return
  40. }
  41. if resp.Code == ResponseCodeSuccess {
  42. a = &Auth{
  43. Token: resp.Data.Token,
  44. Expire: resp.Data.CreateTime/1000 + _authExpire,
  45. }
  46. return
  47. }
  48. err = fmt.Errorf("new access error, code(%d) description(%s)", resp.Code, resp.Message)
  49. return
  50. }
  51. func sign(key, secret, timestamp string) string {
  52. return fmt.Sprintf("%x", sha256.Sum256([]byte(key+timestamp+secret)))
  53. }
  54. // IsExpired judge that whether privilige expired.
  55. func (a *Auth) IsExpired() bool {
  56. return a.Expire <= time.Now().Add(4*time.Hour).Unix() // 提前4小时过期,for renew auth
  57. }