oauth.go 13 KB

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