oauth.go 15 KB

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