oauth.go 9.5 KB

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