oauth.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package service
  2. import (
  3. "Gwen/global"
  4. "Gwen/model"
  5. "Gwen/utils"
  6. "context"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "golang.org/x/oauth2"
  11. "golang.org/x/oauth2/github"
  12. "golang.org/x/oauth2/google"
  13. "gorm.io/gorm"
  14. "io"
  15. "strconv"
  16. "sync"
  17. "time"
  18. )
  19. type OauthService struct {
  20. }
  21. type GithubUserdata struct {
  22. AvatarUrl string `json:"avatar_url"`
  23. Bio string `json:"bio"`
  24. Blog string `json:"blog"`
  25. Collaborators int `json:"collaborators"`
  26. Company interface{} `json:"company"`
  27. CreatedAt time.Time `json:"created_at"`
  28. DiskUsage int `json:"disk_usage"`
  29. Email interface{} `json:"email"`
  30. EventsUrl string `json:"events_url"`
  31. Followers int `json:"followers"`
  32. FollowersUrl string `json:"followers_url"`
  33. Following int `json:"following"`
  34. FollowingUrl string `json:"following_url"`
  35. GistsUrl string `json:"gists_url"`
  36. GravatarId string `json:"gravatar_id"`
  37. Hireable interface{} `json:"hireable"`
  38. HtmlUrl string `json:"html_url"`
  39. Id int `json:"id"`
  40. Location interface{} `json:"location"`
  41. Login string `json:"login"`
  42. Name string `json:"name"`
  43. NodeId string `json:"node_id"`
  44. NotificationEmail interface{} `json:"notification_email"`
  45. OrganizationsUrl string `json:"organizations_url"`
  46. OwnedPrivateRepos int `json:"owned_private_repos"`
  47. Plan struct {
  48. Collaborators int `json:"collaborators"`
  49. Name string `json:"name"`
  50. PrivateRepos int `json:"private_repos"`
  51. Space int `json:"space"`
  52. } `json:"plan"`
  53. PrivateGists int `json:"private_gists"`
  54. PublicGists int `json:"public_gists"`
  55. PublicRepos int `json:"public_repos"`
  56. ReceivedEventsUrl string `json:"received_events_url"`
  57. ReposUrl string `json:"repos_url"`
  58. SiteAdmin bool `json:"site_admin"`
  59. StarredUrl string `json:"starred_url"`
  60. SubscriptionsUrl string `json:"subscriptions_url"`
  61. TotalPrivateRepos int `json:"total_private_repos"`
  62. //TwitterUsername interface{} `json:"twitter_username"`
  63. TwoFactorAuthentication bool `json:"two_factor_authentication"`
  64. Type string `json:"type"`
  65. UpdatedAt time.Time `json:"updated_at"`
  66. Url string `json:"url"`
  67. }
  68. type OauthCacheItem struct {
  69. UserId uint `json:"user_id"`
  70. Id string `json:"id"` //rustdesk的设备ID
  71. Op string `json:"op"`
  72. Action string `json:"action"`
  73. Uuid string `json:"uuid"`
  74. DeviceName string `json:"device_name"`
  75. DeviceOs string `json:"device_os"`
  76. DeviceType string `json:"device_type"`
  77. ThirdOpenId string `json:"third_open_id"`
  78. ThirdName string `json:"third_name"`
  79. ThirdEmail string `json:"third_email"`
  80. }
  81. var OauthCache = &sync.Map{}
  82. const (
  83. OauthActionTypeLogin = "login"
  84. OauthActionTypeBind = "bind"
  85. )
  86. func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
  87. v, ok := OauthCache.Load(key)
  88. if !ok {
  89. return nil
  90. }
  91. return v.(*OauthCacheItem)
  92. }
  93. func (os *OauthService) SetOauthCache(key string, item *OauthCacheItem, expire uint) {
  94. OauthCache.Store(key, item)
  95. if expire > 0 {
  96. go func() {
  97. time.Sleep(time.Duration(expire) * time.Second)
  98. os.DeleteOauthCache(key)
  99. }()
  100. }
  101. }
  102. func (os *OauthService) DeleteOauthCache(key string) {
  103. OauthCache.Delete(key)
  104. }
  105. func (os *OauthService) BeginAuth(op string) (error error, code, url string) {
  106. code = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  107. if op == model.OauthTypeWebauth {
  108. url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + code
  109. //url = "http://localhost:8888/_admin/#/oauth/" + code
  110. return nil, code, url
  111. }
  112. err, conf := os.GetOauthConfig(op)
  113. if err == nil {
  114. return err, code, conf.AuthCodeURL(code)
  115. }
  116. return errors.New("op错误"), code, ""
  117. }
  118. // GetOauthConfig 获取配置
  119. func (os *OauthService) GetOauthConfig(op string) (error, *oauth2.Config) {
  120. if op == model.OauthTypeGithub {
  121. g := os.InfoByOp(model.OauthTypeGithub)
  122. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  123. return errors.New("配置不存在"), nil
  124. }
  125. return nil, &oauth2.Config{
  126. ClientID: g.ClientId,
  127. ClientSecret: g.ClientSecret,
  128. RedirectURL: g.RedirectUrl,
  129. Endpoint: github.Endpoint,
  130. Scopes: []string{"read:user", "user:email"},
  131. }
  132. }
  133. if op == model.OauthTypeGoogle {
  134. g := os.InfoByOp(model.OauthTypeGoogle)
  135. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  136. return errors.New("配置不存在"), nil
  137. }
  138. return nil, &oauth2.Config{
  139. ClientID: g.ClientId,
  140. ClientSecret: g.ClientSecret,
  141. RedirectURL: g.RedirectUrl,
  142. Endpoint: google.Endpoint,
  143. Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"},
  144. }
  145. }
  146. return errors.New("op错误"), nil
  147. }
  148. func (os *OauthService) GithubCallback(code string) (error error, userData *GithubUserdata) {
  149. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGithub)
  150. if err != nil {
  151. return err, nil
  152. }
  153. token, err := oauthConfig.Exchange(context.Background(), code)
  154. if err != nil {
  155. global.Logger.Warn(fmt.Printf("oauthConfig.Exchange() failed: %s\n", err))
  156. error = errors.New("获取token失败")
  157. return
  158. }
  159. // 创建一个 HTTP 客户端,并将 access_token 添加到 Authorization 头中
  160. client := oauthConfig.Client(context.Background(), token)
  161. resp, err := client.Get("https://api.github.com/user")
  162. if err != nil {
  163. global.Logger.Warn("failed getting user info: %s\n", err)
  164. error = errors.New("获取user info失败")
  165. return
  166. }
  167. defer func(Body io.ReadCloser) {
  168. err := Body.Close()
  169. if err != nil {
  170. global.Logger.Warn("failed closing response body: %s\n", err)
  171. }
  172. }(resp.Body)
  173. // 在这里处理 GitHub 用户信息
  174. if err := json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  175. global.Logger.Warn("failed decoding user info: %s\n", err)
  176. error = errors.New("解析user info失败")
  177. return
  178. }
  179. return
  180. }
  181. func (os *OauthService) UserThirdInfo(op, openid string) *model.UserThird {
  182. ut := &model.UserThird{}
  183. global.DB.Where("open_id = ? and third_type = ?", openid, op).First(ut)
  184. return ut
  185. }
  186. func (os *OauthService) BindGithubUser(openid, username string, userId uint) error {
  187. utr := &model.UserThird{
  188. OpenId: openid,
  189. ThirdType: model.OauthTypeGithub,
  190. ThirdName: username,
  191. UserId: userId,
  192. }
  193. return global.DB.Create(utr).Error
  194. }
  195. func (os *OauthService) UnBindGithubUser(userid uint) error {
  196. return global.DB.Where("user_id = ? and third_type = ?", userid, model.OauthTypeGithub).Delete(&model.UserThird{}).Error
  197. }
  198. // InfoById 根据id取用户信息
  199. func (os *OauthService) InfoById(id uint) *model.Oauth {
  200. u := &model.Oauth{}
  201. global.DB.Where("id = ?", id).First(u)
  202. return u
  203. }
  204. // InfoByOp 根据op取用户信息
  205. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  206. u := &model.Oauth{}
  207. global.DB.Where("op = ?", op).First(u)
  208. return u
  209. }
  210. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  211. res = &model.OauthList{}
  212. res.Page = int64(page)
  213. res.PageSize = int64(pageSize)
  214. tx := global.DB.Model(&model.Oauth{})
  215. if where != nil {
  216. where(tx)
  217. }
  218. tx.Count(&res.Total)
  219. tx.Scopes(Paginate(page, pageSize))
  220. tx.Find(&res.Oauths)
  221. return
  222. }
  223. // Create 创建
  224. func (os *OauthService) Create(u *model.Oauth) error {
  225. res := global.DB.Create(u).Error
  226. return res
  227. }
  228. func (os *OauthService) Delete(u *model.Oauth) error {
  229. return global.DB.Delete(u).Error
  230. }
  231. // Update 更新
  232. func (os *OauthService) Update(u *model.Oauth) error {
  233. return global.DB.Model(u).Updates(u).Error
  234. }