auth.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package gn
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "eta_gn/eta_bridge/global"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. )
  13. type AccessTokenResp struct {
  14. ErrResp `description:"报错响应"`
  15. AccessToken string `json:"access_token"`
  16. ExpiresIn int `json:"expires_in"`
  17. RefreshExpiresIn int `json:"refresh_expires_in"`
  18. RefreshToken string `json:"refresh_token"`
  19. TokenType string `json:"token_type"`
  20. NotBeforePolicy int `json:"not-before-policy"`
  21. SessionState string `json:"session_state"`
  22. //Error string `json:"error" description:"错误代码"`
  23. //ErrorDescription string `json:"error_description" description:"错误描述"`
  24. }
  25. type UserBaseInfoResp struct {
  26. ErrResp `description:"报错响应"`
  27. Sub string `json:"sub"`
  28. Name string `json:"name"`
  29. PreferredUsername string `json:"preferred_username"`
  30. GivenName string `json:"given_name"`
  31. FamilyName string `json:"family_name"`
  32. }
  33. // ErrResp
  34. // @Description: 错误信息返回
  35. type ErrResp struct {
  36. Error string `json:"error" description:"错误代码"`
  37. ErrorDescription string `json:"error_description" description:"错误描述"`
  38. }
  39. // GetToken
  40. // @Description: 获取token信息
  41. // @author: Roc
  42. // @datetime 2024-01-23 15:40:56
  43. // @param code string
  44. // @return resp *AccessTokenResp
  45. // @return err error
  46. func GetToken(code string) (resp *AccessTokenResp, err error) {
  47. code = strings.TrimSpace(code)
  48. if code == "" {
  49. err = fmt.Errorf("code不可为空")
  50. return
  51. }
  52. //baseUrl := `%s?client_id=%s&client_secret=%s&redirect_uri=%s&code=%s&grant_type=authorization_code`
  53. baseUrl := global.CONFIG.Gn.AuthTokenApiUrl
  54. params := url.Values{}
  55. params.Add("client_id", global.CONFIG.Gn.AuthClientId)
  56. params.Add("client_secret", global.CONFIG.Gn.AuthClientSecret)
  57. params.Add("redirect_uri", global.CONFIG.Gn.AuthSSOCallbackUrl)
  58. params.Add("code", code)
  59. params.Add("grant_type", "authorization_code")
  60. //callbackUrl := url.QueryEscape(global.CONFIG.Gn.AuthSSOCallbackUrl)
  61. //fmt.Println("CallbackUrl: ", callbackUrl)
  62. //urlPath := fmt.Sprintf(baseUrl, global.CONFIG.Gn.AuthTokenApiUrl, global.CONFIG.Gn.AuthClientId, global.CONFIG.Gn.AuthClientSecret, callbackUrl, code)
  63. //fmt.Println("RequestUrl: ", urlPath)
  64. result, e := HttpPostAuth(baseUrl, params, "")
  65. //urlPath := fmt.Sprintf(`/idp/oauth2/getToken?client_id=%s&grant_type=authorization_code&code=%s&client_secret=%s`, global.CONFIG.Xiangyu.SystemCode, code, global.CONFIG.Xiangyu.UserKey)
  66. //result, e := HttpPostAuth(urlPath, ``, "")
  67. if e != nil {
  68. err = fmt.Errorf("统一认证请求失败, %v", e)
  69. return
  70. }
  71. fmt.Printf("Token RequestResult: %s\n", string(result))
  72. // 解析响应结果
  73. if e := json.Unmarshal(result, &resp); e != nil {
  74. err = fmt.Errorf("解析响应失败, %v", e)
  75. return
  76. }
  77. if resp.Error != "" {
  78. err = fmt.Errorf("Token请求失败, Err: %s, ErrMsg: %s ", resp.Error, resp.ErrorDescription)
  79. //err = errors.New(fmt.Sprintf("响应代码:%s,错误信息:%s", resp.ErrCode, resp.Msg))
  80. return
  81. }
  82. return
  83. }
  84. // GetUserInfo
  85. // @Description: 获取用户信息
  86. // @author: Roc
  87. // @datetime 2024-01-23 15:49:38
  88. // @param token string
  89. // @return resp *UserBaseInfoResp
  90. // @return err error
  91. func GetUserInfo(code, token string) (resp *UserBaseInfoResp, err error) {
  92. code = strings.TrimSpace(code)
  93. token = strings.TrimSpace(token)
  94. if code == "" || token == "" {
  95. err = fmt.Errorf("Code和Token不可为空, Code: %s, Token: %s", code, token)
  96. return
  97. }
  98. baseUrl := global.CONFIG.Gn.AuthUserApiUrl
  99. params := url.Values{}
  100. params.Add("code", code)
  101. params.Add("access_token", token)
  102. //callbackUrl := url.QueryEscape(global.CONFIG.Gn.AuthSSOCallbackUrl)
  103. //fmt.Println("CallbackUrl: ", callbackUrl)
  104. //urlPath := fmt.Sprintf(baseUrl, global.CONFIG.Gn.AuthTokenApiUrl, global.CONFIG.Gn.AuthClientId, global.CONFIG.Gn.AuthClientSecret, callbackUrl, code)
  105. //fmt.Println("RequestUrl: ", urlPath)
  106. result, err := HttpPostAuth(baseUrl, params, "")
  107. //urlPath := fmt.Sprintf(`/idp/oauth2/getUserInfo?client_id=%s&access_token=%s`, global.CONFIG.Xiangyu.SystemCode, token)
  108. //result, err := HttpGetAuth(urlPath)
  109. if err != nil {
  110. return
  111. }
  112. fmt.Printf("UserInfoResult: %s\n", string(result))
  113. // 解析响应结果
  114. err = json.Unmarshal(result, &resp)
  115. if err != nil {
  116. return
  117. }
  118. if resp.Error != "" {
  119. err = fmt.Errorf("UserInfo请求失败, Err: %s, ErrMsg: %s ", resp.Error, resp.ErrorDescription)
  120. return
  121. }
  122. return
  123. }
  124. func HttpPostAuth(postUrl string, params url.Values, contentTypes ...string) ([]byte, error) {
  125. //if global.CONFIG.Xiangyu.UserAuthHost == `` {
  126. // return nil, errors.New("统一用户同步接口地址为空")
  127. //}
  128. // 请求地址
  129. //postUrl := global.CONFIG.Xiangyu.UserAuthHost + urlPath
  130. //postUrl := urlPath
  131. //body := io.NopCloser(strings.NewReader(postData))
  132. client := &http.Client{}
  133. req, err := http.NewRequest("POST", postUrl, bytes.NewBufferString(params.Encode()))
  134. //req, err := http.NewRequest("POST", postUrl, body)
  135. if err != nil {
  136. return nil, err
  137. }
  138. contentType := "application/x-www-form-urlencoded;charset=utf-8"
  139. if len(contentTypes) > 0 && contentTypes[0] != "" {
  140. contentType = contentTypes[0]
  141. }
  142. req.Header.Set("content-Type", contentType)
  143. resp, err := client.Do(req)
  144. if err != nil {
  145. return nil, err
  146. }
  147. defer func() {
  148. _ = resp.Body.Close()
  149. }()
  150. result, err := io.ReadAll(resp.Body)
  151. if err != nil {
  152. return nil, err
  153. }
  154. // 日志记录
  155. postData := fmt.Sprintf("%v", params)
  156. global.FILE_LOG.Debug("统一认证:地址:" + postUrl + ";\n请求参数:" + postData + ";\n返回参数:" + string(result))
  157. // 解析返回参数,判断是否是json
  158. if !json.Valid(result) {
  159. err = errors.New("返回参数不是json格式")
  160. }
  161. return result, err
  162. }
  163. // GetUserInfo
  164. // @Description: 获取用户信息
  165. // @author: Roc
  166. // @datetime 2024-01-23 15:49:38
  167. // @param token string
  168. // @return resp *UserBaseInfoResp
  169. // @return err error
  170. func GetUserInfoBySci(token string) (resp *UserBaseInfoResp, err error) {
  171. token = strings.TrimSpace(token)
  172. if token == "" {
  173. err = fmt.Errorf("Token不可为空,Token: %s", token)
  174. return
  175. }
  176. urlPath := fmt.Sprintf(`%s?token=%s`, `getuserinfo`, token)
  177. result, err := HttpGetAuth(urlPath)
  178. if err != nil {
  179. return
  180. }
  181. // 解析响应结果
  182. err = json.Unmarshal(result, &resp)
  183. if err != nil {
  184. return
  185. }
  186. if resp.Error != "" {
  187. err = fmt.Errorf("UserInfo请求失败, Err: %s, ErrMsg: %s ", resp.Error, resp.ErrorDescription)
  188. return
  189. }
  190. return
  191. }
  192. func HttpGetAuth(urlPath string) ([]byte, error) {
  193. if global.CONFIG.Gn.AuthUserApiUrl == `` {
  194. return nil, errors.New("授权平台同步接口地址为空")
  195. }
  196. // 请求地址
  197. getUrl := global.CONFIG.Gn.AuthUserApiUrl + urlPath
  198. client := &http.Client{}
  199. req, err := http.NewRequest("GET", getUrl, nil)
  200. if err != nil {
  201. return nil, err
  202. }
  203. resp, err := client.Do(req)
  204. if err != nil {
  205. return nil, err
  206. }
  207. defer resp.Body.Close()
  208. result, err := io.ReadAll(resp.Body)
  209. if err != nil {
  210. return nil, err
  211. }
  212. // 日志记录
  213. global.FILE_LOG.Debug("授权平台:地址:" + getUrl + ";\n返回参数:" + string(result))
  214. // 解析返回参数,判断是否是json
  215. if !json.Valid(result) {
  216. err = errors.New("返回参数不是json格式")
  217. }
  218. return result, err
  219. }