oauth.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 GoogleUserdata struct {
  69. Email string `json:"email"`
  70. FamilyName string `json:"family_name"`
  71. GivenName string `json:"given_name"`
  72. Id string `json:"id"`
  73. Name string `json:"name"`
  74. Picture string `json:"picture"`
  75. VerifiedEmail bool `json:"verified_email"`
  76. }
  77. type OauthCacheItem struct {
  78. UserId uint `json:"user_id"`
  79. Id string `json:"id"` //rustdesk的设备ID
  80. Op string `json:"op"`
  81. Action string `json:"action"`
  82. Uuid string `json:"uuid"`
  83. DeviceName string `json:"device_name"`
  84. DeviceOs string `json:"device_os"`
  85. DeviceType string `json:"device_type"`
  86. ThirdOpenId string `json:"third_open_id"`
  87. ThirdName string `json:"third_name"`
  88. ThirdEmail string `json:"third_email"`
  89. }
  90. var OauthCache = &sync.Map{}
  91. const (
  92. OauthActionTypeLogin = "login"
  93. OauthActionTypeBind = "bind"
  94. )
  95. func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
  96. v, ok := OauthCache.Load(key)
  97. if !ok {
  98. return nil
  99. }
  100. return v.(*OauthCacheItem)
  101. }
  102. func (os *OauthService) SetOauthCache(key string, item *OauthCacheItem, expire uint) {
  103. OauthCache.Store(key, item)
  104. if expire > 0 {
  105. go func() {
  106. time.Sleep(time.Duration(expire) * time.Second)
  107. os.DeleteOauthCache(key)
  108. }()
  109. }
  110. }
  111. func (os *OauthService) DeleteOauthCache(key string) {
  112. OauthCache.Delete(key)
  113. }
  114. func (os *OauthService) BeginAuth(op string) (error error, code, url string) {
  115. code = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  116. if op == model.OauthTypeWebauth {
  117. url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + code
  118. //url = "http://localhost:8888/_admin/#/oauth/" + code
  119. return nil, code, url
  120. }
  121. err, conf := os.GetOauthConfig(op)
  122. if err == nil {
  123. return err, code, conf.AuthCodeURL(code)
  124. }
  125. return err, code, ""
  126. }
  127. // GetOauthConfig 获取配置
  128. func (os *OauthService) GetOauthConfig(op string) (error, *oauth2.Config) {
  129. if op == model.OauthTypeGithub {
  130. g := os.InfoByOp(model.OauthTypeGithub)
  131. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  132. return errors.New("ConfigNotFound"), nil
  133. }
  134. return nil, &oauth2.Config{
  135. ClientID: g.ClientId,
  136. ClientSecret: g.ClientSecret,
  137. RedirectURL: g.RedirectUrl,
  138. Endpoint: github.Endpoint,
  139. Scopes: []string{"read:user", "user:email"},
  140. }
  141. }
  142. if op == model.OauthTypeGoogle {
  143. g := os.InfoByOp(model.OauthTypeGoogle)
  144. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  145. return errors.New("ConfigNotFound"), nil
  146. }
  147. return nil, &oauth2.Config{
  148. ClientID: g.ClientId,
  149. ClientSecret: g.ClientSecret,
  150. RedirectURL: g.RedirectUrl,
  151. Endpoint: google.Endpoint,
  152. Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"},
  153. }
  154. }
  155. return errors.New("ConfigNotFound"), nil
  156. }
  157. func (os *OauthService) GithubCallback(code string) (error error, userData *GithubUserdata) {
  158. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGithub)
  159. if err != nil {
  160. return err, nil
  161. }
  162. token, err := oauthConfig.Exchange(context.Background(), code)
  163. if err != nil {
  164. global.Logger.Warn(fmt.Printf("oauthConfig.Exchange() failed: %s\n", err))
  165. error = errors.New("GetOauthTokenError")
  166. return
  167. }
  168. // 创建一个 HTTP 客户端,并将 access_token 添加到 Authorization 头中
  169. client := oauthConfig.Client(context.Background(), token)
  170. resp, err := client.Get("https://api.github.com/user")
  171. if err != nil {
  172. global.Logger.Warn("failed getting user info: %s\n", err)
  173. error = errors.New("GetOauthUserInfoError")
  174. return
  175. }
  176. defer func(Body io.ReadCloser) {
  177. err := Body.Close()
  178. if err != nil {
  179. global.Logger.Warn("failed closing response body: %s\n", err)
  180. }
  181. }(resp.Body)
  182. // 在这里处理 GitHub 用户信息
  183. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  184. global.Logger.Warn("failed decoding user info: %s\n", err)
  185. error = errors.New("DecodeOauthUserInfoError")
  186. return
  187. }
  188. return
  189. }
  190. func (os *OauthService) GoogleCallback(code string) (error error, userData *GoogleUserdata) {
  191. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGoogle)
  192. token, err := oauthConfig.Exchange(context.Background(), code)
  193. if err != nil {
  194. global.Logger.Warn(fmt.Printf("oauthConfig.Exchange() failed: %s\n", err))
  195. error = errors.New("GetOauthTokenError")
  196. return
  197. }
  198. // 创建 HTTP 客户端,并将 access_token 添加到 Authorization 头中
  199. client := oauthConfig.Client(context.Background(), token)
  200. resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
  201. if err != nil {
  202. global.Logger.Warn("failed getting user info: %s\n", err)
  203. error = errors.New("GetOauthUserInfoError")
  204. return
  205. }
  206. defer func(Body io.ReadCloser) {
  207. err := Body.Close()
  208. if err != nil {
  209. global.Logger.Warn("failed closing response body: %s\n", err)
  210. }
  211. }(resp.Body)
  212. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  213. global.Logger.Warn("failed decoding user info: %s\n", err)
  214. error = errors.New("DecodeOauthUserInfoError")
  215. return
  216. }
  217. return
  218. }
  219. func (os *OauthService) UserThirdInfo(op, openid string) *model.UserThird {
  220. ut := &model.UserThird{}
  221. global.DB.Where("open_id = ? and third_type = ?", openid, op).First(ut)
  222. return ut
  223. }
  224. func (os *OauthService) BindGithubUser(openid, username string, userId uint) error {
  225. return os.BindOauthUser(model.OauthTypeGithub, openid, username, userId)
  226. }
  227. func (os *OauthService) BindGoogleUser(email, username string, userId uint) error {
  228. return os.BindOauthUser(model.OauthTypeGoogle, email, username, userId)
  229. }
  230. func (os *OauthService) BindOauthUser(thirdType, openid, username string, userId uint) error {
  231. utr := &model.UserThird{
  232. OpenId: openid,
  233. ThirdType: thirdType,
  234. ThirdName: username,
  235. UserId: userId,
  236. }
  237. return global.DB.Create(utr).Error
  238. }
  239. func (os *OauthService) UnBindGithubUser(userid uint) error {
  240. return os.UnBindThird(model.OauthTypeGithub, userid)
  241. }
  242. func (os *OauthService) UnBindGoogleUser(userid uint) error {
  243. return os.UnBindThird(model.OauthTypeGoogle, userid)
  244. }
  245. func (os *OauthService) UnBindThird(thirdType string, userid uint) error {
  246. return global.DB.Where("user_id = ? and third_type = ?", userid, thirdType).Delete(&model.UserThird{}).Error
  247. }
  248. // InfoById 根据id取用户信息
  249. func (os *OauthService) InfoById(id uint) *model.Oauth {
  250. u := &model.Oauth{}
  251. global.DB.Where("id = ?", id).First(u)
  252. return u
  253. }
  254. // InfoByOp 根据op取用户信息
  255. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  256. u := &model.Oauth{}
  257. global.DB.Where("op = ?", op).First(u)
  258. return u
  259. }
  260. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  261. res = &model.OauthList{}
  262. res.Page = int64(page)
  263. res.PageSize = int64(pageSize)
  264. tx := global.DB.Model(&model.Oauth{})
  265. if where != nil {
  266. where(tx)
  267. }
  268. tx.Count(&res.Total)
  269. tx.Scopes(Paginate(page, pageSize))
  270. tx.Find(&res.Oauths)
  271. return
  272. }
  273. // Create 创建
  274. func (os *OauthService) Create(u *model.Oauth) error {
  275. res := global.DB.Create(u).Error
  276. return res
  277. }
  278. func (os *OauthService) Delete(u *model.Oauth) error {
  279. return global.DB.Delete(u).Error
  280. }
  281. // Update 更新
  282. func (os *OauthService) Update(u *model.Oauth) error {
  283. return global.DB.Model(u).Updates(u).Error
  284. }