oauth.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package service
  2. import (
  3. "Gwen/global"
  4. "Gwen/model"
  5. "Gwen/utils"
  6. "context"
  7. "encoding/json"
  8. "errors"
  9. "golang.org/x/oauth2"
  10. "golang.org/x/oauth2/github"
  11. "golang.org/x/oauth2/google"
  12. "gorm.io/gorm"
  13. "io"
  14. "net/http"
  15. "net/url"
  16. "strconv"
  17. "sync"
  18. "time"
  19. )
  20. type OauthService struct {
  21. }
  22. type GithubUserdata struct {
  23. AvatarUrl string `json:"avatar_url"`
  24. Bio string `json:"bio"`
  25. Blog string `json:"blog"`
  26. Collaborators int `json:"collaborators"`
  27. Company interface{} `json:"company"`
  28. CreatedAt time.Time `json:"created_at"`
  29. DiskUsage int `json:"disk_usage"`
  30. Email interface{} `json:"email"`
  31. EventsUrl string `json:"events_url"`
  32. Followers int `json:"followers"`
  33. FollowersUrl string `json:"followers_url"`
  34. Following int `json:"following"`
  35. FollowingUrl string `json:"following_url"`
  36. GistsUrl string `json:"gists_url"`
  37. GravatarId string `json:"gravatar_id"`
  38. Hireable interface{} `json:"hireable"`
  39. HtmlUrl string `json:"html_url"`
  40. Id int `json:"id"`
  41. Location interface{} `json:"location"`
  42. Login string `json:"login"`
  43. Name string `json:"name"`
  44. NodeId string `json:"node_id"`
  45. NotificationEmail interface{} `json:"notification_email"`
  46. OrganizationsUrl string `json:"organizations_url"`
  47. OwnedPrivateRepos int `json:"owned_private_repos"`
  48. Plan struct {
  49. Collaborators int `json:"collaborators"`
  50. Name string `json:"name"`
  51. PrivateRepos int `json:"private_repos"`
  52. Space int `json:"space"`
  53. } `json:"plan"`
  54. PrivateGists int `json:"private_gists"`
  55. PublicGists int `json:"public_gists"`
  56. PublicRepos int `json:"public_repos"`
  57. ReceivedEventsUrl string `json:"received_events_url"`
  58. ReposUrl string `json:"repos_url"`
  59. SiteAdmin bool `json:"site_admin"`
  60. StarredUrl string `json:"starred_url"`
  61. SubscriptionsUrl string `json:"subscriptions_url"`
  62. TotalPrivateRepos int `json:"total_private_repos"`
  63. //TwitterUsername interface{} `json:"twitter_username"`
  64. TwoFactorAuthentication bool `json:"two_factor_authentication"`
  65. Type string `json:"type"`
  66. UpdatedAt time.Time `json:"updated_at"`
  67. Url string `json:"url"`
  68. }
  69. type GoogleUserdata struct {
  70. Email string `json:"email"`
  71. FamilyName string `json:"family_name"`
  72. GivenName string `json:"given_name"`
  73. Id string `json:"id"`
  74. Name string `json:"name"`
  75. Picture string `json:"picture"`
  76. VerifiedEmail bool `json:"verified_email"`
  77. }
  78. type OauthCacheItem struct {
  79. UserId uint `json:"user_id"`
  80. Id string `json:"id"` //rustdesk的设备ID
  81. Op string `json:"op"`
  82. Action string `json:"action"`
  83. Uuid string `json:"uuid"`
  84. DeviceName string `json:"device_name"`
  85. DeviceOs string `json:"device_os"`
  86. DeviceType string `json:"device_type"`
  87. ThirdOpenId string `json:"third_open_id"`
  88. ThirdName string `json:"third_name"`
  89. ThirdEmail string `json:"third_email"`
  90. }
  91. var OauthCache = &sync.Map{}
  92. const (
  93. OauthActionTypeLogin = "login"
  94. OauthActionTypeBind = "bind"
  95. )
  96. func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
  97. v, ok := OauthCache.Load(key)
  98. if !ok {
  99. return nil
  100. }
  101. return v.(*OauthCacheItem)
  102. }
  103. func (os *OauthService) SetOauthCache(key string, item *OauthCacheItem, expire uint) {
  104. OauthCache.Store(key, item)
  105. if expire > 0 {
  106. go func() {
  107. time.Sleep(time.Duration(expire) * time.Second)
  108. os.DeleteOauthCache(key)
  109. }()
  110. }
  111. }
  112. func (os *OauthService) DeleteOauthCache(key string) {
  113. OauthCache.Delete(key)
  114. }
  115. func (os *OauthService) BeginAuth(op string) (error error, code, url string) {
  116. code = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  117. if op == model.OauthTypeWebauth {
  118. url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + code
  119. //url = "http://localhost:8888/_admin/#/oauth/" + code
  120. return nil, code, url
  121. }
  122. err, conf := os.GetOauthConfig(op)
  123. if err == nil {
  124. return err, code, conf.AuthCodeURL(code)
  125. }
  126. return err, code, ""
  127. }
  128. // GetOauthConfig 获取配置
  129. func (os *OauthService) GetOauthConfig(op string) (error, *oauth2.Config) {
  130. if op == model.OauthTypeGithub {
  131. g := os.InfoByOp(model.OauthTypeGithub)
  132. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  133. return errors.New("ConfigNotFound"), nil
  134. }
  135. return nil, &oauth2.Config{
  136. ClientID: g.ClientId,
  137. ClientSecret: g.ClientSecret,
  138. RedirectURL: g.RedirectUrl,
  139. Endpoint: github.Endpoint,
  140. Scopes: []string{"read:user", "user:email"},
  141. }
  142. }
  143. if op == model.OauthTypeGoogle {
  144. g := os.InfoByOp(model.OauthTypeGoogle)
  145. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  146. return errors.New("ConfigNotFound"), nil
  147. }
  148. return nil, &oauth2.Config{
  149. ClientID: g.ClientId,
  150. ClientSecret: g.ClientSecret,
  151. RedirectURL: g.RedirectUrl,
  152. Endpoint: google.Endpoint,
  153. Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"},
  154. }
  155. }
  156. return errors.New("ConfigNotFound"), nil
  157. }
  158. func getHTTPClientWithProxy() *http.Client {
  159. if global.Config.Proxy.Enable {
  160. if global.Config.Proxy.Host == "" {
  161. global.Logger.Warn("Proxy is enabled but proxy host is empty.")
  162. return http.DefaultClient
  163. }
  164. proxyURL, err := url.Parse(global.Config.Proxy.Host)
  165. if err != nil {
  166. global.Logger.Warn("Invalid proxy URL: ", err)
  167. return http.DefaultClient
  168. }
  169. transport := &http.Transport{
  170. Proxy: http.ProxyURL(proxyURL),
  171. }
  172. return &http.Client{Transport: transport}
  173. }
  174. return http.DefaultClient
  175. }
  176. func (os *OauthService) GithubCallback(code string) (error error, userData *GithubUserdata) {
  177. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGithub)
  178. if err != nil {
  179. return err, nil
  180. }
  181. // 使用代理配置创建 HTTP 客户端
  182. httpClient := getHTTPClientWithProxy()
  183. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  184. token, err := oauthConfig.Exchange(ctx, code)
  185. if err != nil {
  186. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  187. error = errors.New("GetOauthTokenError")
  188. return
  189. }
  190. // 使用带有代理的 HTTP 客户端获取用户信息
  191. client := oauthConfig.Client(ctx, token)
  192. resp, err := client.Get("https://api.github.com/user")
  193. if err != nil {
  194. global.Logger.Warn("failed getting user info: ", err)
  195. error = errors.New("GetOauthUserInfoError")
  196. return
  197. }
  198. defer func(Body io.ReadCloser) {
  199. err := Body.Close()
  200. if err != nil {
  201. global.Logger.Warn("failed closing response body: ", err)
  202. }
  203. }(resp.Body)
  204. // 解析用户信息
  205. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  206. global.Logger.Warn("failed decoding user info: ", err)
  207. error = errors.New("DecodeOauthUserInfoError")
  208. return
  209. }
  210. return
  211. }
  212. func (os *OauthService) GoogleCallback(code string) (error error, userData *GoogleUserdata) {
  213. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGoogle)
  214. if err != nil {
  215. return err, nil
  216. }
  217. // 使用代理配置创建 HTTP 客户端
  218. httpClient := getHTTPClientWithProxy()
  219. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  220. token, err := oauthConfig.Exchange(ctx, code)
  221. if err != nil {
  222. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  223. error = errors.New("GetOauthTokenError")
  224. return
  225. }
  226. // 使用带有代理的 HTTP 客户端获取用户信息
  227. client := oauthConfig.Client(ctx, token)
  228. resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
  229. if err != nil {
  230. global.Logger.Warn("failed getting user info: ", err)
  231. error = errors.New("GetOauthUserInfoError")
  232. return
  233. }
  234. defer func(Body io.ReadCloser) {
  235. err := Body.Close()
  236. if err != nil {
  237. global.Logger.Warn("failed closing response body: ", err)
  238. }
  239. }(resp.Body)
  240. // 解析用户信息
  241. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  242. global.Logger.Warn("failed decoding user info: ", err)
  243. error = errors.New("DecodeOauthUserInfoError")
  244. return
  245. }
  246. return
  247. }
  248. func (os *OauthService) UserThirdInfo(op, openid string) *model.UserThird {
  249. ut := &model.UserThird{}
  250. global.DB.Where("open_id = ? and third_type = ?", openid, op).First(ut)
  251. return ut
  252. }
  253. func (os *OauthService) BindGithubUser(openid, username string, userId uint) error {
  254. return os.BindOauthUser(model.OauthTypeGithub, openid, username, userId)
  255. }
  256. func (os *OauthService) BindGoogleUser(email, username string, userId uint) error {
  257. return os.BindOauthUser(model.OauthTypeGoogle, email, username, userId)
  258. }
  259. func (os *OauthService) BindOauthUser(thirdType, openid, username string, userId uint) error {
  260. utr := &model.UserThird{
  261. OpenId: openid,
  262. ThirdType: thirdType,
  263. ThirdName: username,
  264. UserId: userId,
  265. }
  266. return global.DB.Create(utr).Error
  267. }
  268. func (os *OauthService) UnBindGithubUser(userid uint) error {
  269. return os.UnBindThird(model.OauthTypeGithub, userid)
  270. }
  271. func (os *OauthService) UnBindGoogleUser(userid uint) error {
  272. return os.UnBindThird(model.OauthTypeGoogle, userid)
  273. }
  274. func (os *OauthService) UnBindThird(thirdType string, userid uint) error {
  275. return global.DB.Where("user_id = ? and third_type = ?", userid, thirdType).Delete(&model.UserThird{}).Error
  276. }
  277. // InfoById 根据id取用户信息
  278. func (os *OauthService) InfoById(id uint) *model.Oauth {
  279. u := &model.Oauth{}
  280. global.DB.Where("id = ?", id).First(u)
  281. return u
  282. }
  283. // InfoByOp 根据op取用户信息
  284. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  285. u := &model.Oauth{}
  286. global.DB.Where("op = ?", op).First(u)
  287. return u
  288. }
  289. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  290. res = &model.OauthList{}
  291. res.Page = int64(page)
  292. res.PageSize = int64(pageSize)
  293. tx := global.DB.Model(&model.Oauth{})
  294. if where != nil {
  295. where(tx)
  296. }
  297. tx.Count(&res.Total)
  298. tx.Scopes(Paginate(page, pageSize))
  299. tx.Find(&res.Oauths)
  300. return
  301. }
  302. // Create 创建
  303. func (os *OauthService) Create(u *model.Oauth) error {
  304. res := global.DB.Create(u).Error
  305. return res
  306. }
  307. func (os *OauthService) Delete(u *model.Oauth) error {
  308. return global.DB.Delete(u).Error
  309. }
  310. // Update 更新
  311. func (os *OauthService) Update(u *model.Oauth) error {
  312. return global.DB.Model(u).Updates(u).Error
  313. }