oauth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. "fmt"
  21. )
  22. type OauthService struct {
  23. }
  24. // Define a struct to parse the .well-known/openid-configuration response
  25. type OidcEndpoint struct {
  26. Issuer string `json:"issuer"`
  27. AuthURL string `json:"authorization_endpoint"`
  28. TokenURL string `json:"token_endpoint"`
  29. UserInfo string `json:"userinfo_endpoint"`
  30. }
  31. type OauthCacheItem struct {
  32. UserId uint `json:"user_id"`
  33. Id string `json:"id"` //rustdesk的设备ID
  34. Op string `json:"op"`
  35. Action string `json:"action"`
  36. Uuid string `json:"uuid"`
  37. DeviceName string `json:"device_name"`
  38. DeviceOs string `json:"device_os"`
  39. DeviceType string `json:"device_type"`
  40. OpenId string `json:"open_id"`
  41. Username string `json:"username"`
  42. Name string `json:"name"`
  43. Email string `json:"email"`
  44. }
  45. func (oci *OauthCacheItem) ToOauthUser() *model.OauthUser {
  46. return &model.OauthUser{
  47. OpenId: oci.OpenId,
  48. Username: oci.Username,
  49. Name: oci.Name,
  50. Email: oci.Email,
  51. }
  52. }
  53. var OauthCache = &sync.Map{}
  54. const (
  55. OauthActionTypeLogin = "login"
  56. OauthActionTypeBind = "bind"
  57. )
  58. func (oa *OauthCacheItem) UpdateFromOauthUser(oauthUser *model.OauthUser) {
  59. oa.OpenId = oauthUser.OpenId
  60. oa.Username = oauthUser.Username
  61. oa.Name = oauthUser.Name
  62. oa.Email = oauthUser.Email
  63. }
  64. // Validate the oauth type
  65. func (os *OauthService) ValidateOauthType(oauthType string) error {
  66. switch oauthType {
  67. case model.OauthTypeGithub, model.OauthTypeGoogle, model.OauthTypeOidc, model.OauthTypeWebauth:
  68. return nil
  69. default:
  70. return errors.New("invalid Oauth type")
  71. }
  72. }
  73. func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
  74. v, ok := OauthCache.Load(key)
  75. if !ok {
  76. return nil
  77. }
  78. return v.(*OauthCacheItem)
  79. }
  80. func (os *OauthService) SetOauthCache(key string, item *OauthCacheItem, expire uint) {
  81. OauthCache.Store(key, item)
  82. if expire > 0 {
  83. go func() {
  84. time.Sleep(time.Duration(expire) * time.Second)
  85. os.DeleteOauthCache(key)
  86. }()
  87. }
  88. }
  89. func (os *OauthService) DeleteOauthCache(key string) {
  90. OauthCache.Delete(key)
  91. }
  92. func (os *OauthService) BeginAuth(op string) (error error, code, url string) {
  93. code = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  94. if op == string(model.OauthTypeWebauth) {
  95. url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + code
  96. //url = "http://localhost:8888/_admin/#/oauth/" + code
  97. return nil, code, url
  98. }
  99. err, _, oauthConfig := os.GetOauthConfig(op)
  100. if err == nil {
  101. return err, code, oauthConfig.AuthCodeURL(code)
  102. }
  103. return err, code, ""
  104. }
  105. // Method to fetch OIDC configuration dynamically
  106. func (os *OauthService) FetchOidcEndpoint(issuer string) (error, OidcEndpoint) {
  107. configURL := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
  108. // Get the HTTP client (with or without proxy based on configuration)
  109. client := getHTTPClientWithProxy()
  110. resp, err := client.Get(configURL)
  111. if err != nil {
  112. return errors.New("failed to fetch OIDC configuration"), OidcEndpoint{}
  113. }
  114. defer resp.Body.Close()
  115. if resp.StatusCode != http.StatusOK {
  116. return errors.New("OIDC configuration not found, status code: %d"), OidcEndpoint{}
  117. }
  118. var endpoint OidcEndpoint
  119. if err := json.NewDecoder(resp.Body).Decode(&endpoint); err != nil {
  120. return errors.New("failed to parse OIDC configuration"), OidcEndpoint{}
  121. }
  122. return nil, endpoint
  123. }
  124. func (os *OauthService) FetchOidcEndpointByOp(op string) (error, OidcEndpoint) {
  125. oauthInfo := os.InfoByOp(op)
  126. if oauthInfo.Issuer == "" {
  127. return errors.New("issuer is empty"), OidcEndpoint{}
  128. }
  129. return os.FetchOidcEndpoint(oauthInfo.Issuer)
  130. }
  131. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  132. func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config) {
  133. err, oauthInfo, oauthConfig = os.getOauthConfigGeneral(op)
  134. if err != nil {
  135. return err, nil, nil
  136. }
  137. // Maybe should validate the oauthConfig here
  138. oauthType := oauthInfo.OauthType
  139. err = os.ValidateOauthType(oauthType)
  140. if err != nil {
  141. return err, nil, nil
  142. }
  143. switch oauthType {
  144. case model.OauthTypeGithub:
  145. oauthConfig.Endpoint = github.Endpoint
  146. oauthConfig.Scopes = []string{"read:user", "user:email"}
  147. case model.OauthTypeGoogle:
  148. oauthConfig.Endpoint = google.Endpoint
  149. oauthConfig.Scopes = os.constructScopes(model.OIDC_DEFAULT_SCOPES)
  150. case model.OauthTypeOidc:
  151. var endpoint OidcEndpoint
  152. err, endpoint = os.FetchOidcEndpoint(oauthInfo.Issuer)
  153. if err != nil {
  154. return err, nil, nil
  155. }
  156. oauthConfig.Endpoint = oauth2.Endpoint{AuthURL: endpoint.AuthURL,TokenURL: endpoint.TokenURL,}
  157. oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
  158. default:
  159. return errors.New("unsupported OAuth type"), nil, nil
  160. }
  161. return nil, oauthInfo, oauthConfig
  162. }
  163. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  164. func (os *OauthService) getOauthConfigGeneral(op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config) {
  165. oauthInfo = os.InfoByOp(op)
  166. if oauthInfo.Id == 0 || oauthInfo.ClientId == "" || oauthInfo.ClientSecret == "" {
  167. return errors.New("ConfigNotFound"), nil, nil
  168. }
  169. // If the redirect URL is empty, use the default redirect URL
  170. if oauthInfo.RedirectUrl == "" {
  171. oauthInfo.RedirectUrl = global.Config.Rustdesk.ApiServer + "/api/oidc/callback"
  172. }
  173. return nil, oauthInfo, &oauth2.Config{
  174. ClientID: oauthInfo.ClientId,
  175. ClientSecret: oauthInfo.ClientSecret,
  176. RedirectURL: oauthInfo.RedirectUrl,
  177. }
  178. }
  179. func getHTTPClientWithProxy() *http.Client {
  180. //todo add timeout
  181. if global.Config.Proxy.Enable {
  182. if global.Config.Proxy.Host == "" {
  183. global.Logger.Warn("Proxy is enabled but proxy host is empty.")
  184. return http.DefaultClient
  185. }
  186. proxyURL, err := url.Parse(global.Config.Proxy.Host)
  187. if err != nil {
  188. global.Logger.Warn("Invalid proxy URL: ", err)
  189. return http.DefaultClient
  190. }
  191. transport := &http.Transport{
  192. Proxy: http.ProxyURL(proxyURL),
  193. }
  194. return &http.Client{Transport: transport}
  195. }
  196. return http.DefaultClient
  197. }
  198. func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, code string, userEndpoint string, userData interface{}) (err error, client *http.Client) {
  199. // 设置代理客户端
  200. httpClient := getHTTPClientWithProxy()
  201. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  202. // 使用 code 换取 token
  203. var token *oauth2.Token
  204. token, err = oauthConfig.Exchange(ctx, code)
  205. if err != nil {
  206. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  207. return errors.New("GetOauthTokenError"), nil
  208. }
  209. // 获取用户信息
  210. client = oauthConfig.Client(ctx, token)
  211. resp, err := client.Get(userEndpoint)
  212. if err != nil {
  213. global.Logger.Warn("failed getting user info: ", err)
  214. return errors.New("GetOauthUserInfoError"), nil
  215. }
  216. defer func() {
  217. if closeErr := resp.Body.Close(); closeErr != nil {
  218. global.Logger.Warn("failed closing response body: ", closeErr)
  219. }
  220. }()
  221. // 解析用户信息
  222. if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
  223. global.Logger.Warn("failed decoding user info: ", err)
  224. return errors.New("DecodeOauthUserInfoError"), nil
  225. }
  226. return nil, client
  227. }
  228. // githubCallback github回调
  229. func (os *OauthService) githubCallback(oauthConfig *oauth2.Config, code string) (error, *model.OauthUser) {
  230. var user = &model.GithubUser{}
  231. err, client := os.callbackBase(oauthConfig, code, model.UserEndpointGithub, user)
  232. if err != nil {
  233. return err, nil
  234. }
  235. err = os.getGithubPrimaryEmail(client, user)
  236. if err != nil {
  237. return err, nil
  238. }
  239. return nil, user.ToOauthUser()
  240. }
  241. // googleCallback google回调
  242. func (os *OauthService) googleCallback(oauthConfig *oauth2.Config, code string) (error, *model.OauthUser) {
  243. var user = &model.GoogleUser{}
  244. if err, _ := os.callbackBase(oauthConfig, code, model.UserEndpointGoogle, user); err != nil {
  245. return err, nil
  246. }
  247. return nil, user.ToOauthUser()
  248. }
  249. // oidcCallback oidc回调, 通过code获取用户信息
  250. func (os *OauthService) oidcCallback(oauthConfig *oauth2.Config, code string, userInfoEndpoint string) (error, *model.OauthUser,) {
  251. var user = &model.OidcUser{}
  252. if err, _ := os.callbackBase(oauthConfig, code, userInfoEndpoint, user); err != nil {
  253. return err, nil
  254. }
  255. return nil, user.ToOauthUser()
  256. }
  257. // Callback: Get user information by code and op(Oauth provider)
  258. func (os *OauthService) Callback(code string, op string) (err error, oauthUser *model.OauthUser) {
  259. var oauthInfo *model.Oauth
  260. var oauthConfig *oauth2.Config
  261. err, oauthInfo, oauthConfig = os.GetOauthConfig(op)
  262. // oauthType is already validated in GetOauthConfig
  263. if err != nil {
  264. return err, nil
  265. }
  266. oauthType := oauthInfo.OauthType
  267. switch oauthType {
  268. case model.OauthTypeGithub:
  269. err, oauthUser = os.githubCallback(oauthConfig, code)
  270. case model.OauthTypeGoogle:
  271. err, oauthUser = os.googleCallback(oauthConfig, code)
  272. case model.OauthTypeOidc:
  273. err, endpoint := os.FetchOidcEndpoint(oauthInfo.Issuer)
  274. if err != nil {
  275. return err, nil
  276. }
  277. err, oauthUser = os.oidcCallback(oauthConfig, code, endpoint.UserInfo)
  278. default:
  279. return errors.New("unsupported OAuth type"), nil
  280. }
  281. return err, oauthUser
  282. }
  283. func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
  284. ut := &model.UserThird{}
  285. global.DB.Where("open_id = ? and op = ?", openId, op).First(ut)
  286. return ut
  287. }
  288. // BindOauthUser: Bind third party account
  289. func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, op string) error {
  290. utr := &model.UserThird{}
  291. err, oauthType := os.GetTypeByOp(op)
  292. if err != nil {
  293. return err
  294. }
  295. utr.FromOauthUser(userId, oauthUser, oauthType, op)
  296. return global.DB.Create(utr).Error
  297. }
  298. // UnBindOauthUser: Unbind third party account
  299. func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
  300. return os.UnBindThird(op, userId)
  301. }
  302. // UnBindThird: Unbind third party account
  303. func (os *OauthService) UnBindThird(op string, userId uint) error {
  304. return global.DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
  305. }
  306. // DeleteUserByUserId: When user is deleted, delete all third party bindings
  307. func (os *OauthService) DeleteUserByUserId(userId uint) error {
  308. return global.DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
  309. }
  310. // InfoById 根据id获取Oauth信息
  311. func (os *OauthService) InfoById(id uint) *model.Oauth {
  312. oauthInfo := &model.Oauth{}
  313. global.DB.Where("id = ?", id).First(oauthInfo)
  314. return oauthInfo
  315. }
  316. // InfoByOp 根据op获取Oauth信息
  317. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  318. oauthInfo := &model.Oauth{}
  319. global.DB.Where("op = ?", op).First(oauthInfo)
  320. return oauthInfo
  321. }
  322. // Helper function to get scopes by operation
  323. func (os *OauthService) getScopesByOp(op string) []string {
  324. scopes := os.InfoByOp(op).Scopes
  325. return os.constructScopes(scopes)
  326. }
  327. // Helper function to construct scopes
  328. func (os *OauthService) constructScopes(scopes string) []string {
  329. scopes = strings.TrimSpace(scopes)
  330. if scopes == "" {
  331. scopes = model.OIDC_DEFAULT_SCOPES
  332. }
  333. return strings.Split(scopes, ",")
  334. }
  335. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  336. res = &model.OauthList{}
  337. res.Page = int64(page)
  338. res.PageSize = int64(pageSize)
  339. tx := global.DB.Model(&model.Oauth{})
  340. if where != nil {
  341. where(tx)
  342. }
  343. tx.Count(&res.Total)
  344. tx.Scopes(Paginate(page, pageSize))
  345. tx.Find(&res.Oauths)
  346. return
  347. }
  348. // GetTypeByOp 根据op获取OauthType
  349. func (os *OauthService) GetTypeByOp(op string) (error, string) {
  350. oauthInfo := &model.Oauth{}
  351. if global.DB.Where("op = ?", op).First(oauthInfo).Error != nil {
  352. return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
  353. }
  354. return nil, oauthInfo.OauthType
  355. }
  356. // ValidateOauthProvider 验证Oauth提供者是否正确
  357. func (os *OauthService) ValidateOauthProvider(op string) error {
  358. if !os.IsOauthProviderExist(op) {
  359. return fmt.Errorf("OAuth provider with op '%s' not found", op)
  360. }
  361. return nil
  362. }
  363. // IsOauthProviderExist 验证Oauth提供者是否存在
  364. func (os *OauthService) IsOauthProviderExist(op string) bool {
  365. oauthInfo := &model.Oauth{}
  366. // 使用 Gorm 的 Take 方法查找符合条件的记录
  367. if err := global.DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
  368. return false
  369. }
  370. return true
  371. }
  372. // Create 创建
  373. func (os *OauthService) Create(oauthInfo *model.Oauth) error {
  374. res := global.DB.Create(oauthInfo).Error
  375. return res
  376. }
  377. func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
  378. return global.DB.Delete(oauthInfo).Error
  379. }
  380. // Update 更新
  381. func (os *OauthService) Update(oauthInfo *model.Oauth) error {
  382. return global.DB.Model(oauthInfo).Updates(oauthInfo).Error
  383. }
  384. // GetOauthProviders 获取所有的provider
  385. func (os *OauthService) GetOauthProviders() []string {
  386. var res []string
  387. global.DB.Model(&model.Oauth{}).Pluck("op", &res)
  388. return res
  389. }
  390. // getGithubPrimaryEmail: Get the primary email of the user from Github
  391. func (os *OauthService) getGithubPrimaryEmail(client *http.Client, githubUser *model.GithubUser) error {
  392. // the client is already set with the token
  393. resp, err := client.Get("https://api.github.com/user/emails")
  394. if err != nil {
  395. return fmt.Errorf("failed to fetch emails: %w", err)
  396. }
  397. defer resp.Body.Close()
  398. // check the response status code
  399. if resp.StatusCode != http.StatusOK {
  400. return fmt.Errorf("failed to fetch emails: %s", resp.Status)
  401. }
  402. // decode the response
  403. var emails []struct {
  404. Email string `json:"email"`
  405. Primary bool `json:"primary"`
  406. Verified bool `json:"verified"`
  407. }
  408. if err := json.NewDecoder(resp.Body).Decode(&emails); err != nil {
  409. return fmt.Errorf("failed to decode response: %w", err)
  410. }
  411. // find the primary verified email
  412. for _, e := range emails {
  413. if e.Primary && e.Verified {
  414. githubUser.Email = e.Email
  415. githubUser.VerifiedEmail = e.Verified
  416. return nil
  417. }
  418. }
  419. return fmt.Errorf("no primary verified email found")
  420. }