oauth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. "strings"
  20. )
  21. // Define a struct to parse the .well-known/openid-configuration response
  22. type OidcEndpoint struct {
  23. Issuer string `json:"issuer"`
  24. AuthURL string `json:"authorization_endpoint"`
  25. TokenURL string `json:"token_endpoint"`
  26. UserInfo string `json:"userinfo_endpoint"`
  27. }
  28. type OauthService struct {
  29. OidcEndpoint *OidcEndpoint
  30. }
  31. type GithubUserdata struct {
  32. AvatarUrl string `json:"avatar_url"`
  33. Bio string `json:"bio"`
  34. Blog string `json:"blog"`
  35. Collaborators int `json:"collaborators"`
  36. Company interface{} `json:"company"`
  37. CreatedAt time.Time `json:"created_at"`
  38. DiskUsage int `json:"disk_usage"`
  39. Email interface{} `json:"email"`
  40. EventsUrl string `json:"events_url"`
  41. Followers int `json:"followers"`
  42. FollowersUrl string `json:"followers_url"`
  43. Following int `json:"following"`
  44. FollowingUrl string `json:"following_url"`
  45. GistsUrl string `json:"gists_url"`
  46. GravatarId string `json:"gravatar_id"`
  47. Hireable interface{} `json:"hireable"`
  48. HtmlUrl string `json:"html_url"`
  49. Id int `json:"id"`
  50. Location interface{} `json:"location"`
  51. Login string `json:"login"`
  52. Name string `json:"name"`
  53. NodeId string `json:"node_id"`
  54. NotificationEmail interface{} `json:"notification_email"`
  55. OrganizationsUrl string `json:"organizations_url"`
  56. OwnedPrivateRepos int `json:"owned_private_repos"`
  57. Plan struct {
  58. Collaborators int `json:"collaborators"`
  59. Name string `json:"name"`
  60. PrivateRepos int `json:"private_repos"`
  61. Space int `json:"space"`
  62. } `json:"plan"`
  63. PrivateGists int `json:"private_gists"`
  64. PublicGists int `json:"public_gists"`
  65. PublicRepos int `json:"public_repos"`
  66. ReceivedEventsUrl string `json:"received_events_url"`
  67. ReposUrl string `json:"repos_url"`
  68. SiteAdmin bool `json:"site_admin"`
  69. StarredUrl string `json:"starred_url"`
  70. SubscriptionsUrl string `json:"subscriptions_url"`
  71. TotalPrivateRepos int `json:"total_private_repos"`
  72. //TwitterUsername interface{} `json:"twitter_username"`
  73. TwoFactorAuthentication bool `json:"two_factor_authentication"`
  74. Type string `json:"type"`
  75. UpdatedAt time.Time `json:"updated_at"`
  76. Url string `json:"url"`
  77. }
  78. type GoogleUserdata struct {
  79. Email string `json:"email"`
  80. FamilyName string `json:"family_name"`
  81. GivenName string `json:"given_name"`
  82. Id string `json:"id"`
  83. Name string `json:"name"`
  84. Picture string `json:"picture"`
  85. VerifiedEmail bool `json:"verified_email"`
  86. }
  87. type OidcUserdata struct {
  88. Sub string `json:"sub"`
  89. Email string `json:"email"`
  90. VerifiedEmail bool `json:"email_verified"`
  91. Name string `json:"name"`
  92. Picture string `json:"picture"`
  93. PrefferedUsername string `json:"preffered_username"`
  94. }
  95. type OauthCacheItem struct {
  96. UserId uint `json:"user_id"`
  97. Id string `json:"id"` //rustdesk的设备ID
  98. Op string `json:"op"`
  99. Action string `json:"action"`
  100. Uuid string `json:"uuid"`
  101. DeviceName string `json:"device_name"`
  102. DeviceOs string `json:"device_os"`
  103. DeviceType string `json:"device_type"`
  104. ThirdOpenId string `json:"third_open_id"`
  105. ThirdName string `json:"third_name"`
  106. ThirdEmail string `json:"third_email"`
  107. }
  108. var OauthCache = &sync.Map{}
  109. const (
  110. OauthActionTypeLogin = "login"
  111. OauthActionTypeBind = "bind"
  112. )
  113. func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
  114. v, ok := OauthCache.Load(key)
  115. if !ok {
  116. return nil
  117. }
  118. return v.(*OauthCacheItem)
  119. }
  120. func (os *OauthService) SetOauthCache(key string, item *OauthCacheItem, expire uint) {
  121. OauthCache.Store(key, item)
  122. if expire > 0 {
  123. go func() {
  124. time.Sleep(time.Duration(expire) * time.Second)
  125. os.DeleteOauthCache(key)
  126. }()
  127. }
  128. }
  129. func (os *OauthService) DeleteOauthCache(key string) {
  130. OauthCache.Delete(key)
  131. }
  132. func (os *OauthService) BeginAuth(op string) (error error, code, url string) {
  133. code = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  134. if op == model.OauthTypeWebauth {
  135. url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + code
  136. //url = "http://localhost:8888/_admin/#/oauth/" + code
  137. return nil, code, url
  138. }
  139. err, conf := os.GetOauthConfig(op)
  140. if err == nil {
  141. return err, code, conf.AuthCodeURL(code)
  142. }
  143. return err, code, ""
  144. }
  145. // Method to fetch OIDC configuration dynamically
  146. func (os *OauthService) FetchOIDCConfig(issuer string) error {
  147. configURL := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
  148. // Get the HTTP client (with or without proxy based on configuration)
  149. client := getHTTPClientWithProxy()
  150. resp, err := client.Get(configURL)
  151. if err != nil {
  152. return errors.New("failed to fetch OIDC configuration")
  153. }
  154. defer resp.Body.Close()
  155. if resp.StatusCode != http.StatusOK {
  156. return errors.New("OIDC configuration not found")
  157. }
  158. var endpoint OidcEndpoint
  159. if err := json.NewDecoder(resp.Body).Decode(&endpoint); err != nil {
  160. return errors.New("failed to parse OIDC configuration")
  161. }
  162. os.OidcEndpoint = &endpoint
  163. return nil
  164. }
  165. // GetOauthConfig retrieves the OAuth2 configuration based on the provider type
  166. func (os *OauthService) GetOauthConfig(op string) (error, *oauth2.Config) {
  167. switch op {
  168. case model.OauthTypeGithub:
  169. return os.getGithubConfig()
  170. case model.OauthTypeGoogle:
  171. return os.getGoogleConfig()
  172. case model.OauthTypeOidc:
  173. return os.getOidcConfig()
  174. default:
  175. return errors.New("unsupported OAuth type"), nil
  176. }
  177. }
  178. // Helper function to get GitHub OAuth2 configuration
  179. func (os *OauthService) getGithubConfig() (error, *oauth2.Config) {
  180. g := os.InfoByOp(model.OauthTypeGithub)
  181. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  182. return errors.New("ConfigNotFound"), nil
  183. }
  184. return nil, &oauth2.Config{
  185. ClientID: g.ClientId,
  186. ClientSecret: g.ClientSecret,
  187. RedirectURL: g.RedirectUrl,
  188. Endpoint: github.Endpoint,
  189. Scopes: []string{"read:user", "user:email"},
  190. }
  191. }
  192. // Helper function to get Google OAuth2 configuration
  193. func (os *OauthService) getGoogleConfig() (error, *oauth2.Config) {
  194. g := os.InfoByOp(model.OauthTypeGoogle)
  195. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
  196. return errors.New("ConfigNotFound"), nil
  197. }
  198. return nil, &oauth2.Config{
  199. ClientID: g.ClientId,
  200. ClientSecret: g.ClientSecret,
  201. RedirectURL: g.RedirectUrl,
  202. Endpoint: google.Endpoint,
  203. Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"},
  204. }
  205. }
  206. // Helper function to get OIDC OAuth2 configuration
  207. func (os *OauthService) getOidcConfig() (error, *oauth2.Config) {
  208. g := os.InfoByOp(model.OauthTypeOidc)
  209. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" || g.Issuer == "" {
  210. return errors.New("ConfigNotFound"), nil
  211. }
  212. // Set scopes
  213. scopes := g.Scopes
  214. if scopes == "" {
  215. scopes = "openid,profile,email"
  216. }
  217. scopeList := strings.Split(scopes, ",")
  218. // Fetch OIDC configuration
  219. if err := os.FetchOIDCConfig(g.Issuer); err != nil {
  220. return err, nil
  221. }
  222. return nil, &oauth2.Config{
  223. ClientID: g.ClientId,
  224. ClientSecret: g.ClientSecret,
  225. RedirectURL: g.RedirectUrl,
  226. Endpoint: oauth2.Endpoint{
  227. AuthURL: os.OidcEndpoint.AuthURL,
  228. TokenURL: os.OidcEndpoint.TokenURL,
  229. },
  230. Scopes: scopeList,
  231. }
  232. }
  233. func getHTTPClientWithProxy() *http.Client {
  234. if global.Config.Proxy.Enable {
  235. if global.Config.Proxy.Host == "" {
  236. global.Logger.Warn("Proxy is enabled but proxy host is empty.")
  237. return http.DefaultClient
  238. }
  239. proxyURL, err := url.Parse(global.Config.Proxy.Host)
  240. if err != nil {
  241. global.Logger.Warn("Invalid proxy URL: ", err)
  242. return http.DefaultClient
  243. }
  244. transport := &http.Transport{
  245. Proxy: http.ProxyURL(proxyURL),
  246. }
  247. return &http.Client{Transport: transport}
  248. }
  249. return http.DefaultClient
  250. }
  251. func (os *OauthService) GithubCallback(code string) (error error, userData *GithubUserdata) {
  252. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGithub)
  253. if err != nil {
  254. return err, nil
  255. }
  256. // 使用代理配置创建 HTTP 客户端
  257. httpClient := getHTTPClientWithProxy()
  258. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  259. token, err := oauthConfig.Exchange(ctx, code)
  260. if err != nil {
  261. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  262. error = errors.New("GetOauthTokenError")
  263. return
  264. }
  265. // 使用带有代理的 HTTP 客户端获取用户信息
  266. client := oauthConfig.Client(ctx, token)
  267. resp, err := client.Get("https://api.github.com/user")
  268. if err != nil {
  269. global.Logger.Warn("failed getting user info: ", err)
  270. error = errors.New("GetOauthUserInfoError")
  271. return
  272. }
  273. defer func(Body io.ReadCloser) {
  274. err := Body.Close()
  275. if err != nil {
  276. global.Logger.Warn("failed closing response body: ", err)
  277. }
  278. }(resp.Body)
  279. // 解析用户信息
  280. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  281. global.Logger.Warn("failed decoding user info: ", err)
  282. error = errors.New("DecodeOauthUserInfoError")
  283. return
  284. }
  285. return
  286. }
  287. func (os *OauthService) GoogleCallback(code string) (error error, userData *GoogleUserdata) {
  288. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGoogle)
  289. if err != nil {
  290. return err, nil
  291. }
  292. // 使用代理配置创建 HTTP 客户端
  293. httpClient := getHTTPClientWithProxy()
  294. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  295. token, err := oauthConfig.Exchange(ctx, code)
  296. if err != nil {
  297. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  298. error = errors.New("GetOauthTokenError")
  299. return
  300. }
  301. // 使用带有代理的 HTTP 客户端获取用户信息
  302. client := oauthConfig.Client(ctx, token)
  303. resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
  304. if err != nil {
  305. global.Logger.Warn("failed getting user info: ", err)
  306. error = errors.New("GetOauthUserInfoError")
  307. return
  308. }
  309. defer func(Body io.ReadCloser) {
  310. err := Body.Close()
  311. if err != nil {
  312. global.Logger.Warn("failed closing response body: ", err)
  313. }
  314. }(resp.Body)
  315. // 解析用户信息
  316. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  317. global.Logger.Warn("failed decoding user info: ", err)
  318. error = errors.New("DecodeOauthUserInfoError")
  319. return
  320. }
  321. return
  322. }
  323. func (os *OauthService) OidcCallback(code string) (error error, userData *OidcUserdata) {
  324. err, oauthConfig := os.GetOauthConfig(model.OauthTypeOidc)
  325. if err != nil {
  326. return err, nil
  327. }
  328. // 使用代理配置创建 HTTP 客户端
  329. httpClient := getHTTPClientWithProxy()
  330. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  331. token, err := oauthConfig.Exchange(ctx, code)
  332. if err != nil {
  333. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  334. error = errors.New("GetOauthTokenError")
  335. return
  336. }
  337. // 使用带有代理的 HTTP 客户端获取用户信息
  338. client := oauthConfig.Client(ctx, token)
  339. resp, err := client.Get(os.OidcEndpoint.UserInfo)
  340. if err != nil {
  341. global.Logger.Warn("failed getting user info: ", err)
  342. error = errors.New("GetOauthUserInfoError")
  343. return
  344. }
  345. defer func(Body io.ReadCloser) {
  346. err := Body.Close()
  347. if err != nil {
  348. global.Logger.Warn("failed closing response body: ", err)
  349. }
  350. }(resp.Body)
  351. // 解析用户信息
  352. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  353. global.Logger.Warn("failed decoding user info: ", err)
  354. error = errors.New("DecodeOauthUserInfoError")
  355. return
  356. }
  357. return
  358. }
  359. func (os *OauthService) UserThirdInfo(op, openid string) *model.UserThird {
  360. ut := &model.UserThird{}
  361. global.DB.Where("open_id = ? and third_type = ?", openid, op).First(ut)
  362. return ut
  363. }
  364. func (os *OauthService) BindGithubUser(openid, username string, userId uint) error {
  365. return os.BindOauthUser(model.OauthTypeGithub, openid, username, userId)
  366. }
  367. func (os *OauthService) BindGoogleUser(email, username string, userId uint) error {
  368. return os.BindOauthUser(model.OauthTypeGoogle, email, username, userId)
  369. }
  370. func (os *OauthService) BindOidcUser(openid, username string, userId uint) error {
  371. return os.BindOauthUser(model.OauthTypeOidc, openid, username, userId)
  372. }
  373. func (os *OauthService) BindOauthUser(thirdType, openid, username string, userId uint) error {
  374. utr := &model.UserThird{
  375. OpenId: openid,
  376. ThirdType: thirdType,
  377. ThirdName: username,
  378. UserId: userId,
  379. }
  380. return global.DB.Create(utr).Error
  381. }
  382. func (os *OauthService) UnBindGithubUser(userid uint) error {
  383. return os.UnBindThird(model.OauthTypeGithub, userid)
  384. }
  385. func (os *OauthService) UnBindGoogleUser(userid uint) error {
  386. return os.UnBindThird(model.OauthTypeGoogle, userid)
  387. }
  388. func (os *OauthService) UnBindOidcUser(userid uint) error {
  389. return os.UnBindThird(model.OauthTypeOidc, userid)
  390. }
  391. func (os *OauthService) UnBindThird(thirdType string, userid uint) error {
  392. return global.DB.Where("user_id = ? and third_type = ?", userid, thirdType).Delete(&model.UserThird{}).Error
  393. }
  394. // InfoById 根据id取用户信息
  395. func (os *OauthService) InfoById(id uint) *model.Oauth {
  396. u := &model.Oauth{}
  397. global.DB.Where("id = ?", id).First(u)
  398. return u
  399. }
  400. // InfoByOp 根据op取用户信息
  401. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  402. u := &model.Oauth{}
  403. global.DB.Where("op = ?", op).First(u)
  404. return u
  405. }
  406. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  407. res = &model.OauthList{}
  408. res.Page = int64(page)
  409. res.PageSize = int64(pageSize)
  410. tx := global.DB.Model(&model.Oauth{})
  411. if where != nil {
  412. where(tx)
  413. }
  414. tx.Count(&res.Total)
  415. tx.Scopes(Paginate(page, pageSize))
  416. tx.Find(&res.Oauths)
  417. return
  418. }
  419. // Create 创建
  420. func (os *OauthService) Create(u *model.Oauth) error {
  421. res := global.DB.Create(u).Error
  422. return res
  423. }
  424. func (os *OauthService) Delete(u *model.Oauth) error {
  425. return global.DB.Delete(u).Error
  426. }
  427. // Update 更新
  428. func (os *OauthService) Update(u *model.Oauth) error {
  429. return global.DB.Model(u).Updates(u).Error
  430. }