oauth.go 15 KB

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