oauth.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. "strings"
  18. "sync"
  19. "time"
  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. //todo add timeout
  232. if global.Config.Proxy.Enable {
  233. if global.Config.Proxy.Host == "" {
  234. global.Logger.Warn("Proxy is enabled but proxy host is empty.")
  235. return http.DefaultClient
  236. }
  237. proxyURL, err := url.Parse(global.Config.Proxy.Host)
  238. if err != nil {
  239. global.Logger.Warn("Invalid proxy URL: ", err)
  240. return http.DefaultClient
  241. }
  242. transport := &http.Transport{
  243. Proxy: http.ProxyURL(proxyURL),
  244. }
  245. return &http.Client{Transport: transport}
  246. }
  247. return http.DefaultClient
  248. }
  249. func (os *OauthService) GithubCallback(code string) (error error, userData *GithubUserdata) {
  250. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGithub)
  251. if err != nil {
  252. return err, nil
  253. }
  254. // 使用代理配置创建 HTTP 客户端
  255. httpClient := getHTTPClientWithProxy()
  256. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  257. token, err := oauthConfig.Exchange(ctx, code)
  258. if err != nil {
  259. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  260. error = errors.New("GetOauthTokenError")
  261. return
  262. }
  263. // 使用带有代理的 HTTP 客户端获取用户信息
  264. client := oauthConfig.Client(ctx, token)
  265. resp, err := client.Get("https://api.github.com/user")
  266. if err != nil {
  267. global.Logger.Warn("failed getting user info: ", err)
  268. error = errors.New("GetOauthUserInfoError")
  269. return
  270. }
  271. defer func(Body io.ReadCloser) {
  272. err := Body.Close()
  273. if err != nil {
  274. global.Logger.Warn("failed closing response body: ", err)
  275. }
  276. }(resp.Body)
  277. // 解析用户信息
  278. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  279. global.Logger.Warn("failed decoding user info: ", err)
  280. error = errors.New("DecodeOauthUserInfoError")
  281. return
  282. }
  283. return
  284. }
  285. func (os *OauthService) GoogleCallback(code string) (error error, userData *GoogleUserdata) {
  286. err, oauthConfig := os.GetOauthConfig(model.OauthTypeGoogle)
  287. if err != nil {
  288. return err, nil
  289. }
  290. // 使用代理配置创建 HTTP 客户端
  291. httpClient := getHTTPClientWithProxy()
  292. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  293. token, err := oauthConfig.Exchange(ctx, code)
  294. if err != nil {
  295. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  296. error = errors.New("GetOauthTokenError")
  297. return
  298. }
  299. // 使用带有代理的 HTTP 客户端获取用户信息
  300. client := oauthConfig.Client(ctx, token)
  301. resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
  302. if err != nil {
  303. global.Logger.Warn("failed getting user info: ", err)
  304. error = errors.New("GetOauthUserInfoError")
  305. return
  306. }
  307. defer func(Body io.ReadCloser) {
  308. err := Body.Close()
  309. if err != nil {
  310. global.Logger.Warn("failed closing response body: ", err)
  311. }
  312. }(resp.Body)
  313. // 解析用户信息
  314. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  315. global.Logger.Warn("failed decoding user info: ", err)
  316. error = errors.New("DecodeOauthUserInfoError")
  317. return
  318. }
  319. return
  320. }
  321. func (os *OauthService) OidcCallback(code string) (error error, userData *OidcUserdata) {
  322. err, oauthConfig := os.GetOauthConfig(model.OauthTypeOidc)
  323. if err != nil {
  324. return err, nil
  325. }
  326. // 使用代理配置创建 HTTP 客户端
  327. httpClient := getHTTPClientWithProxy()
  328. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  329. token, err := oauthConfig.Exchange(ctx, code)
  330. if err != nil {
  331. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  332. error = errors.New("GetOauthTokenError")
  333. return
  334. }
  335. // 使用带有代理的 HTTP 客户端获取用户信息
  336. client := oauthConfig.Client(ctx, token)
  337. g := os.InfoByOp(model.OauthTypeOidc)
  338. err, endpoint := FetchOidcConfig(g.Issuer)
  339. if err != nil {
  340. global.Logger.Warn("failed fetching OIDC configuration: ", err)
  341. error = errors.New("FetchOidcConfigError")
  342. return
  343. }
  344. resp, err := client.Get(endpoint.UserInfo)
  345. if err != nil {
  346. global.Logger.Warn("failed getting user info: ", err)
  347. error = errors.New("GetOauthUserInfoError")
  348. return
  349. }
  350. defer func(Body io.ReadCloser) {
  351. err := Body.Close()
  352. if err != nil {
  353. global.Logger.Warn("failed closing response body: ", err)
  354. }
  355. }(resp.Body)
  356. // 解析用户信息
  357. if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
  358. global.Logger.Warn("failed decoding user info: ", err)
  359. error = errors.New("DecodeOauthUserInfoError")
  360. return
  361. }
  362. return
  363. }
  364. func (os *OauthService) UserThirdInfo(op, openid string) *model.UserThird {
  365. ut := &model.UserThird{}
  366. global.DB.Where("open_id = ? and third_type = ?", openid, op).First(ut)
  367. return ut
  368. }
  369. func (os *OauthService) BindGithubUser(openid, username string, userId uint) error {
  370. return os.BindOauthUser(model.OauthTypeGithub, openid, username, userId)
  371. }
  372. func (os *OauthService) BindGoogleUser(email, username string, userId uint) error {
  373. return os.BindOauthUser(model.OauthTypeGoogle, email, username, userId)
  374. }
  375. func (os *OauthService) BindOidcUser(sub, username string, userId uint) error {
  376. return os.BindOauthUser(model.OauthTypeOidc, sub, username, userId)
  377. }
  378. func (os *OauthService) BindOauthUser(thirdType, openid, username string, userId uint) error {
  379. utr := &model.UserThird{
  380. OpenId: openid,
  381. ThirdType: thirdType,
  382. ThirdName: username,
  383. UserId: userId,
  384. }
  385. return global.DB.Create(utr).Error
  386. }
  387. func (os *OauthService) UnBindGithubUser(userid uint) error {
  388. return os.UnBindThird(model.OauthTypeGithub, userid)
  389. }
  390. func (os *OauthService) UnBindGoogleUser(userid uint) error {
  391. return os.UnBindThird(model.OauthTypeGoogle, userid)
  392. }
  393. func (os *OauthService) UnBindOidcUser(userid uint) error {
  394. return os.UnBindThird(model.OauthTypeOidc, userid)
  395. }
  396. func (os *OauthService) UnBindThird(thirdType string, userid uint) error {
  397. return global.DB.Where("user_id = ? and third_type = ?", userid, thirdType).Delete(&model.UserThird{}).Error
  398. }
  399. // DeleteUserByUserId: When user is deleted, delete all third party bindings
  400. func (os *OauthService) DeleteUserByUserId(userid uint) error {
  401. return global.DB.Where("user_id = ?", userid).Delete(&model.UserThird{}).Error
  402. }
  403. // InfoById 根据id取用户信息
  404. func (os *OauthService) InfoById(id uint) *model.Oauth {
  405. u := &model.Oauth{}
  406. global.DB.Where("id = ?", id).First(u)
  407. return u
  408. }
  409. // InfoByOp 根据op取用户信息
  410. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  411. u := &model.Oauth{}
  412. global.DB.Where("op = ?", op).First(u)
  413. return u
  414. }
  415. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  416. res = &model.OauthList{}
  417. res.Page = int64(page)
  418. res.PageSize = int64(pageSize)
  419. tx := global.DB.Model(&model.Oauth{})
  420. if where != nil {
  421. where(tx)
  422. }
  423. tx.Count(&res.Total)
  424. tx.Scopes(Paginate(page, pageSize))
  425. tx.Find(&res.Oauths)
  426. return
  427. }
  428. // Create 创建
  429. func (os *OauthService) Create(u *model.Oauth) error {
  430. res := global.DB.Create(u).Error
  431. return res
  432. }
  433. func (os *OauthService) Delete(u *model.Oauth) error {
  434. return global.DB.Delete(u).Error
  435. }
  436. // Update 更新
  437. func (os *OauthService) Update(u *model.Oauth) error {
  438. return global.DB.Model(u).Updates(u).Error
  439. }