oauth.go 14 KB

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