oauth.go 14 KB

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