dingtalk.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package dingtalk
  15. import (
  16. "context"
  17. "crypto/hmac"
  18. "crypto/sha256"
  19. "encoding/base64"
  20. "fmt"
  21. "strconv"
  22. "time"
  23. "yunion.io/x/jsonutils"
  24. "yunion.io/x/pkg/errors"
  25. "yunion.io/x/pkg/util/httputils"
  26. "yunion.io/x/onecloud/pkg/keystone/driver/oauth2"
  27. )
  28. type SDingtalkOAuth2Driver struct {
  29. oauth2.SOAuth2BaseDriver
  30. }
  31. func NewDingtalkOAuth2Driver(appId string, secret string) oauth2.IOAuth2Driver {
  32. drv := &SDingtalkOAuth2Driver{
  33. SOAuth2BaseDriver: oauth2.SOAuth2BaseDriver{
  34. AppId: appId,
  35. Secret: secret,
  36. },
  37. }
  38. return drv
  39. }
  40. const (
  41. AuthUrl = "https://oapi.dingtalk.com/connect/qrconnect"
  42. )
  43. func (drv *SDingtalkOAuth2Driver) GetSsoRedirectUri(ctx context.Context, callbackUrl, state string) (string, error) {
  44. req := map[string]string{
  45. "appid": drv.AppId,
  46. "response_type": "code",
  47. "scope": "snsapi_login",
  48. "state": state,
  49. "redirect_uri": callbackUrl,
  50. }
  51. urlStr := fmt.Sprintf("%s?%s", AuthUrl, jsonutils.Marshal(req).QueryString())
  52. return urlStr, nil
  53. }
  54. const (
  55. UserInfoUrl = "https://oapi.dingtalk.com/sns/getuserinfo_bycode"
  56. AccessTokenUrl = "https://oapi.dingtalk.com/gettoken"
  57. )
  58. func (drv *SDingtalkOAuth2Driver) signUrl(timestamp string) string {
  59. mac := hmac.New(sha256.New, []byte(drv.Secret))
  60. mac.Write([]byte(timestamp))
  61. sigBytes := mac.Sum(nil)
  62. return base64.StdEncoding.EncodeToString(sigBytes)
  63. }
  64. type sFetchUserInfoQuery struct {
  65. AccessKey string `json:"accessKey"`
  66. Timestamp string `json:"timestamp"`
  67. Signature string `json:"signature"`
  68. }
  69. type sFetchUserInfoBody struct {
  70. TmpAuthCode string `json:"tmp_auth_code"`
  71. }
  72. type sFetchUserInfoData struct {
  73. Nick string `json:"nick"`
  74. Openid string `json:"openid"`
  75. Unionid string `json:"unionid"`
  76. }
  77. func (drv *SDingtalkOAuth2Driver) fetchUserInfo(ctx context.Context, code string) (*sFetchUserInfoData, error) {
  78. httpclient := httputils.GetDefaultClient()
  79. timestamp := strconv.FormatInt(time.Now().UnixNano()/1000000, 10) // microseconds
  80. qs := sFetchUserInfoQuery{
  81. AccessKey: drv.AppId,
  82. Timestamp: timestamp,
  83. Signature: drv.signUrl(timestamp),
  84. }
  85. body := sFetchUserInfoBody{
  86. TmpAuthCode: code,
  87. }
  88. urlstr := fmt.Sprintf("%s?%s", UserInfoUrl, jsonutils.Marshal(qs).QueryString())
  89. _, resp, err := httputils.JSONRequest(httpclient, ctx, httputils.POST, urlstr, nil, jsonutils.Marshal(body), true)
  90. if err != nil {
  91. return nil, errors.Wrap(err, "request access token")
  92. }
  93. data := sFetchUserInfoData{}
  94. err = resp.Unmarshal(&data, "user_info")
  95. if err != nil {
  96. return nil, errors.Wrap(err, "Unmarshal")
  97. }
  98. return &data, nil
  99. }
  100. func (drv *SDingtalkOAuth2Driver) Authenticate(ctx context.Context, code string) (map[string][]string, error) {
  101. data, err := drv.fetchUserInfo(ctx, code)
  102. if err != nil {
  103. return nil, errors.Wrap(err, "fetchUserInfo")
  104. }
  105. ret := make(map[string][]string)
  106. ret["name"] = []string{data.Nick}
  107. ret["user_id"] = []string{data.Unionid}
  108. return ret, nil
  109. }