oauth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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/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. Nonce string `json:"nonce"`
  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, nonce, url string) {
  85. state = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  86. verifier = ""
  87. nonce = ""
  88. if op == model.OauthTypeWebauth {
  89. url = Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
  90. //url = "http://localhost:8888/_admin/#/oauth/" + code
  91. return nil, state, verifier, nonce, url
  92. }
  93. err, oauthInfo, oauthConfig, _ := os.GetOauthConfig(op)
  94. if err == nil {
  95. extras := make([]oauth2.AuthCodeOption, 0, 3)
  96. nonce = utils.RandomString(10)
  97. extras = append(extras, oauth2.SetAuthURLParam("nonce", nonce))
  98. if oauthInfo.PkceEnable != nil && *oauthInfo.PkceEnable {
  99. extras = append(extras, oauth2.AccessTypeOffline)
  100. verifier = oauth2.GenerateVerifier()
  101. switch oauthInfo.PkceMethod {
  102. case model.PKCEMethodS256:
  103. extras = append(extras, oauth2.S256ChallengeOption(verifier))
  104. case model.PKCEMethodPlain:
  105. // oauth2 does not have a plain challenge option, so we add it manually
  106. extras = append(extras, oauth2.SetAuthURLParam("code_challenge_method", "plain"), oauth2.SetAuthURLParam("code_challenge", verifier))
  107. }
  108. }
  109. return err, state, verifier, nonce, oauthConfig.AuthCodeURL(state, extras...)
  110. }
  111. return err, state, verifier, nonce, ""
  112. }
  113. func (os *OauthService) FetchOidcProvider(issuer string) (error, *oidc.Provider) {
  114. // Get the HTTP client (with or without proxy based on configuration)
  115. client := getHTTPClientWithProxy()
  116. ctx := oidc.ClientContext(context.Background(), client)
  117. provider, err := oidc.NewProvider(ctx, issuer)
  118. if err != nil {
  119. return err, nil
  120. }
  121. return nil, provider
  122. }
  123. func (os *OauthService) GithubProvider() *oidc.Provider {
  124. return (&oidc.ProviderConfig{
  125. IssuerURL: "",
  126. AuthURL: github.Endpoint.AuthURL,
  127. TokenURL: github.Endpoint.TokenURL,
  128. DeviceAuthURL: github.Endpoint.DeviceAuthURL,
  129. UserInfoURL: model.UserEndpointGithub,
  130. JWKSURL: "",
  131. Algorithms: nil,
  132. }).NewProvider(context.Background())
  133. }
  134. func (os *OauthService) LinuxdoProvider() *oidc.Provider {
  135. return (&oidc.ProviderConfig{
  136. IssuerURL: "",
  137. AuthURL: "https://connect.linux.do/oauth2/authorize",
  138. TokenURL: "https://connect.linux.do/oauth2/token",
  139. DeviceAuthURL: "",
  140. UserInfoURL: model.UserEndpointLinuxdo,
  141. JWKSURL: "",
  142. Algorithms: nil,
  143. }).NewProvider(context.Background())
  144. }
  145. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  146. func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config, provider *oidc.Provider) {
  147. //err, oauthInfo, oauthConfig = os.getOauthConfigGeneral(op)
  148. oauthInfo = os.InfoByOp(op)
  149. if oauthInfo.Id == 0 || oauthInfo.ClientId == "" || oauthInfo.ClientSecret == "" {
  150. return errors.New("ConfigNotFound"), nil, nil, nil
  151. }
  152. // If the redirect URL is empty, use the default redirect URL
  153. if oauthInfo.RedirectUrl == "" {
  154. oauthInfo.RedirectUrl = Config.Rustdesk.ApiServer + "/api/oidc/callback"
  155. }
  156. oauthConfig = &oauth2.Config{
  157. ClientID: oauthInfo.ClientId,
  158. ClientSecret: oauthInfo.ClientSecret,
  159. RedirectURL: oauthInfo.RedirectUrl,
  160. }
  161. // Maybe should validate the oauthConfig here
  162. oauthType := oauthInfo.OauthType
  163. err = model.ValidateOauthType(oauthType)
  164. if err != nil {
  165. return err, nil, nil, nil
  166. }
  167. switch oauthType {
  168. case model.OauthTypeGithub:
  169. oauthConfig.Endpoint = github.Endpoint
  170. oauthConfig.Scopes = []string{"read:user", "user:email"}
  171. provider = os.GithubProvider()
  172. case model.OauthTypeLinuxdo:
  173. provider = os.LinuxdoProvider()
  174. oauthConfig.Endpoint = provider.Endpoint()
  175. oauthConfig.Scopes = []string{"profile"}
  176. //case model.OauthTypeGoogle: //google单独出来,可以少一次FetchOidcEndpoint请求
  177. // oauthConfig.Endpoint = google.Endpoint
  178. // oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
  179. case model.OauthTypeOidc, model.OauthTypeGoogle:
  180. err, provider = os.FetchOidcProvider(oauthInfo.Issuer)
  181. if err != nil {
  182. return err, nil, nil, nil
  183. }
  184. oauthConfig.Endpoint = provider.Endpoint()
  185. oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
  186. default:
  187. return errors.New("unsupported OAuth type"), nil, nil, nil
  188. }
  189. return nil, oauthInfo, oauthConfig, provider
  190. }
  191. func getHTTPClientWithProxy() *http.Client {
  192. //add timeout 30s
  193. timeout := time.Duration(60) * time.Second
  194. if Config.Proxy.Enable {
  195. if Config.Proxy.Host == "" {
  196. Logger.Warn("Proxy is enabled but proxy host is empty.")
  197. return http.DefaultClient
  198. }
  199. proxyURL, err := url.Parse(Config.Proxy.Host)
  200. if err != nil {
  201. Logger.Warn("Invalid proxy URL: ", err)
  202. return http.DefaultClient
  203. }
  204. transport := &http.Transport{
  205. Proxy: http.ProxyURL(proxyURL),
  206. }
  207. return &http.Client{Transport: transport, Timeout: timeout}
  208. }
  209. return http.DefaultClient
  210. }
  211. func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.Provider, code string, verifier string, nonce string, userData interface{}) (err error, client *http.Client) {
  212. // 设置代理客户端
  213. httpClient := getHTTPClientWithProxy()
  214. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  215. exchangeOpts := make([]oauth2.AuthCodeOption, 0, 1)
  216. if verifier != "" {
  217. exchangeOpts = append(exchangeOpts, oauth2.VerifierOption(verifier))
  218. }
  219. token, err := oauthConfig.Exchange(ctx, code, exchangeOpts...)
  220. if err != nil {
  221. Logger.Warn("oauthConfig.Exchange() failed: ", err)
  222. return errors.New("GetOauthTokenError"), nil
  223. }
  224. // 获取 ID Token, github没有id_token
  225. rawIDToken, ok := token.Extra("id_token").(string)
  226. if ok && rawIDToken != "" {
  227. // 验证 ID Token
  228. v := provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID})
  229. idToken, err2 := v.Verify(ctx, rawIDToken)
  230. if err2 != nil {
  231. Logger.Warn("IdTokenVerifyError: ", err2)
  232. return errors.New("IdTokenVerifyError"), nil
  233. }
  234. if nonce != "" {
  235. // 验证 nonce
  236. var claims struct {
  237. Nonce string `json:"nonce"`
  238. }
  239. if err2 = idToken.Claims(&claims); err2 != nil {
  240. Logger.Warn("Failed to parse ID Token claims: ", err)
  241. return errors.New("IDTokenClaimsError"), nil
  242. }
  243. if claims.Nonce != nonce {
  244. Logger.Warn("Nonce does not match")
  245. return errors.New("NonceDoesNotMatch"), nil
  246. }
  247. }
  248. }
  249. // 获取用户信息
  250. client = oauthConfig.Client(ctx, token)
  251. resp, err := client.Get(provider.UserInfoEndpoint())
  252. if err != nil {
  253. Logger.Warn("failed getting user info: ", err)
  254. return errors.New("GetOauthUserInfoError"), nil
  255. }
  256. defer func() {
  257. if closeErr := resp.Body.Close(); closeErr != nil {
  258. Logger.Warn("failed closing response body: ", closeErr)
  259. }
  260. }()
  261. // 解析用户信息
  262. if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
  263. Logger.Warn("failed decoding user info: ", err)
  264. return errors.New("DecodeOauthUserInfoError"), nil
  265. }
  266. return nil, client
  267. }
  268. // githubCallback github回调
  269. func (os *OauthService) githubCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  270. var user = &model.GithubUser{}
  271. err, client := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user)
  272. if err != nil {
  273. return err, nil
  274. }
  275. err = os.getGithubPrimaryEmail(client, user)
  276. if err != nil {
  277. return err, nil
  278. }
  279. return nil, user.ToOauthUser()
  280. }
  281. // linuxdoCallback linux.do回调
  282. func (os *OauthService) linuxdoCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  283. var user = &model.LinuxdoUser{}
  284. err, _ := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user)
  285. if err != nil {
  286. return err, nil
  287. }
  288. return nil, user.ToOauthUser()
  289. }
  290. // oidcCallback oidc回调, 通过code获取用户信息
  291. func (os *OauthService) oidcCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  292. var user = &model.OidcUser{}
  293. if err, _ := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user); err != nil {
  294. return err, nil
  295. }
  296. return nil, user.ToOauthUser()
  297. }
  298. // Callback: Get user information by code and op(Oauth provider)
  299. func (os *OauthService) Callback(code, verifier, op, nonce string) (err error, oauthUser *model.OauthUser) {
  300. err, oauthInfo, oauthConfig, provider := os.GetOauthConfig(op)
  301. // oauthType is already validated in GetOauthConfig
  302. if err != nil {
  303. return err, nil
  304. }
  305. oauthType := oauthInfo.OauthType
  306. switch oauthType {
  307. case model.OauthTypeGithub:
  308. err, oauthUser = os.githubCallback(oauthConfig, provider, code, verifier, nonce)
  309. case model.OauthTypeLinuxdo:
  310. err, oauthUser = os.linuxdoCallback(oauthConfig, provider, code, verifier, nonce)
  311. case model.OauthTypeOidc, model.OauthTypeGoogle:
  312. err, oauthUser = os.oidcCallback(oauthConfig, provider, code, verifier, nonce)
  313. default:
  314. return errors.New("unsupported OAuth type"), nil
  315. }
  316. return err, oauthUser
  317. }
  318. func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
  319. ut := &model.UserThird{}
  320. DB.Where("open_id = ? and op = ?", openId, op).First(ut)
  321. return ut
  322. }
  323. // BindOauthUser: Bind third party account
  324. func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, op string) error {
  325. utr := &model.UserThird{}
  326. err, oauthType := os.GetTypeByOp(op)
  327. if err != nil {
  328. return err
  329. }
  330. utr.FromOauthUser(userId, oauthUser, oauthType, op)
  331. return DB.Create(utr).Error
  332. }
  333. // UnBindOauthUser: Unbind third party account
  334. func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
  335. return os.UnBindThird(op, userId)
  336. }
  337. // UnBindThird: Unbind third party account
  338. func (os *OauthService) UnBindThird(op string, userId uint) error {
  339. return DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
  340. }
  341. // DeleteUserByUserId: When user is deleted, delete all third party bindings
  342. func (os *OauthService) DeleteUserByUserId(userId uint) error {
  343. return DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
  344. }
  345. // InfoById 根据id获取Oauth信息
  346. func (os *OauthService) InfoById(id uint) *model.Oauth {
  347. oauthInfo := &model.Oauth{}
  348. DB.Where("id = ?", id).First(oauthInfo)
  349. return oauthInfo
  350. }
  351. // InfoByOp 根据op获取Oauth信息
  352. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  353. oauthInfo := &model.Oauth{}
  354. DB.Where("op = ?", op).First(oauthInfo)
  355. return oauthInfo
  356. }
  357. // Helper function to get scopes by operation
  358. func (os *OauthService) getScopesByOp(op string) []string {
  359. scopes := os.InfoByOp(op).Scopes
  360. return os.constructScopes(scopes)
  361. }
  362. // Helper function to construct scopes
  363. func (os *OauthService) constructScopes(scopes string) []string {
  364. scopes = strings.TrimSpace(scopes)
  365. if scopes == "" {
  366. scopes = model.OIDC_DEFAULT_SCOPES
  367. }
  368. return strings.Split(scopes, ",")
  369. }
  370. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  371. res = &model.OauthList{}
  372. res.Page = int64(page)
  373. res.PageSize = int64(pageSize)
  374. tx := DB.Model(&model.Oauth{})
  375. if where != nil {
  376. where(tx)
  377. }
  378. tx.Count(&res.Total)
  379. tx.Scopes(Paginate(page, pageSize))
  380. tx.Find(&res.Oauths)
  381. return
  382. }
  383. // GetTypeByOp 根据op获取OauthType
  384. func (os *OauthService) GetTypeByOp(op string) (error, string) {
  385. oauthInfo := &model.Oauth{}
  386. if DB.Where("op = ?", op).First(oauthInfo).Error != nil {
  387. return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
  388. }
  389. return nil, oauthInfo.OauthType
  390. }
  391. // ValidateOauthProvider 验证Oauth提供者是否正确
  392. func (os *OauthService) ValidateOauthProvider(op string) error {
  393. if !os.IsOauthProviderExist(op) {
  394. return fmt.Errorf("OAuth provider with op '%s' not found", op)
  395. }
  396. return nil
  397. }
  398. // IsOauthProviderExist 验证Oauth提供者是否存在
  399. func (os *OauthService) IsOauthProviderExist(op string) bool {
  400. oauthInfo := &model.Oauth{}
  401. // 使用 Gorm 的 Take 方法查找符合条件的记录
  402. if err := DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
  403. return false
  404. }
  405. return true
  406. }
  407. // Create 创建
  408. func (os *OauthService) Create(oauthInfo *model.Oauth) error {
  409. err := oauthInfo.FormatOauthInfo()
  410. if err != nil {
  411. return err
  412. }
  413. res := DB.Create(oauthInfo).Error
  414. return res
  415. }
  416. func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
  417. return DB.Delete(oauthInfo).Error
  418. }
  419. // Update 更新
  420. func (os *OauthService) Update(oauthInfo *model.Oauth) error {
  421. err := oauthInfo.FormatOauthInfo()
  422. if err != nil {
  423. return err
  424. }
  425. return DB.Model(oauthInfo).Updates(oauthInfo).Error
  426. }
  427. // GetOauthProviders 获取所有的provider
  428. func (os *OauthService) GetOauthProviders() []string {
  429. var res []string
  430. DB.Model(&model.Oauth{}).Pluck("op", &res)
  431. return res
  432. }
  433. // getGithubPrimaryEmail: Get the primary email of the user from Github
  434. func (os *OauthService) getGithubPrimaryEmail(client *http.Client, githubUser *model.GithubUser) error {
  435. // the client is already set with the token
  436. resp, err := client.Get("https://api.github.com/user/emails")
  437. if err != nil {
  438. return fmt.Errorf("failed to fetch emails: %w", err)
  439. }
  440. defer resp.Body.Close()
  441. // check the response status code
  442. if resp.StatusCode != http.StatusOK {
  443. return fmt.Errorf("failed to fetch emails: %s", resp.Status)
  444. }
  445. // decode the response
  446. var emails []struct {
  447. Email string `json:"email"`
  448. Primary bool `json:"primary"`
  449. Verified bool `json:"verified"`
  450. }
  451. if err := json.NewDecoder(resp.Body).Decode(&emails); err != nil {
  452. return fmt.Errorf("failed to decode response: %w", err)
  453. }
  454. // find the primary verified email
  455. for _, e := range emails {
  456. if e.Primary && e.Verified {
  457. githubUser.Email = e.Email
  458. githubUser.VerifiedEmail = e.Verified
  459. return nil
  460. }
  461. }
  462. return fmt.Errorf("no primary verified email found")
  463. }