oauth.go 16 KB

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