oauth.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. package service
  2. import (
  3. "Gwen/global"
  4. "Gwen/model"
  5. "Gwen/utils"
  6. "context"
  7. "encoding/json"
  8. "errors"
  9. "golang.org/x/oauth2"
  10. "golang.org/x/oauth2/github"
  11. "golang.org/x/oauth2/google"
  12. "gorm.io/gorm"
  13. // "io"
  14. "net/http"
  15. "net/url"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "fmt"
  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. }
  45. func (oci *OauthCacheItem) ToOauthUser() *model.OauthUser {
  46. return &model.OauthUser{
  47. OpenId: oci.OpenId,
  48. Username: oci.Username,
  49. Name: oci.Name,
  50. Email: oci.Email,
  51. }
  52. }
  53. var OauthCache = &sync.Map{}
  54. const (
  55. OauthActionTypeLogin = "login"
  56. OauthActionTypeBind = "bind"
  57. )
  58. func (oa *OauthCacheItem) UpdateFromOauthUser(oauthUser *model.OauthUser) {
  59. oa.OpenId = oauthUser.OpenId
  60. oa.Username = oauthUser.Username
  61. oa.Name = oauthUser.Name
  62. oa.Email = oauthUser.Email
  63. }
  64. // Validate the oauth type
  65. func (os *OauthService) ValidateOauthType(oauthType string) error {
  66. switch oauthType {
  67. case model.OauthTypeGithub, model.OauthTypeGoogle, model.OauthTypeOidc, model.OauthTypeWebauth:
  68. return nil
  69. default:
  70. return errors.New("invalid Oauth type")
  71. }
  72. }
  73. func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
  74. v, ok := OauthCache.Load(key)
  75. if !ok {
  76. return nil
  77. }
  78. return v.(*OauthCacheItem)
  79. }
  80. func (os *OauthService) SetOauthCache(key string, item *OauthCacheItem, expire uint) {
  81. OauthCache.Store(key, item)
  82. if expire > 0 {
  83. go func() {
  84. time.Sleep(time.Duration(expire) * time.Second)
  85. os.DeleteOauthCache(key)
  86. }()
  87. }
  88. }
  89. func (os *OauthService) DeleteOauthCache(key string) {
  90. OauthCache.Delete(key)
  91. }
  92. func (os *OauthService) BeginAuth(op string) (error error, code, url string) {
  93. code = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  94. if op == string(model.OauthTypeWebauth) {
  95. url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + code
  96. //url = "http://localhost:8888/_admin/#/oauth/" + code
  97. return nil, code, url
  98. }
  99. err, _, conf := os.GetOauthConfig(op)
  100. if err == nil {
  101. return err, code, conf.AuthCodeURL(code)
  102. }
  103. return err, code, ""
  104. }
  105. // Method to fetch OIDC configuration dynamically
  106. func (os *OauthService) FetchOidcEndpoint(issuer string) (error, OidcEndpoint) {
  107. configURL := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
  108. // Get the HTTP client (with or without proxy based on configuration)
  109. client := getHTTPClientWithProxy()
  110. resp, err := client.Get(configURL)
  111. if err != nil {
  112. return errors.New("failed to fetch OIDC configuration"), OidcEndpoint{}
  113. }
  114. defer resp.Body.Close()
  115. if resp.StatusCode != http.StatusOK {
  116. return errors.New("OIDC configuration not found, status code: %d"), OidcEndpoint{}
  117. }
  118. var endpoint OidcEndpoint
  119. if err := json.NewDecoder(resp.Body).Decode(&endpoint); err != nil {
  120. return errors.New("failed to parse OIDC configuration"), OidcEndpoint{}
  121. }
  122. return nil, endpoint
  123. }
  124. func (os *OauthService) FetchOidcEndpointByOp(op string) (error, OidcEndpoint) {
  125. oauthInfo := os.InfoByOp(op)
  126. if oauthInfo.Issuer == "" {
  127. return errors.New("issuer is empty"), OidcEndpoint{}
  128. }
  129. return os.FetchOidcEndpoint(oauthInfo.Issuer)
  130. }
  131. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  132. func (os *OauthService) GetOauthConfig(op string) (err error, oauthType string, oauthConfig *oauth2.Config) {
  133. err = os.ValidateOauthProvider(op)
  134. if err != nil {
  135. return err, "", nil
  136. }
  137. err, oauthType, oauthConfig = os.getOauthConfigGeneral(op)
  138. if err != nil {
  139. return err, oauthType, nil
  140. }
  141. // Maybe should validate the oauthConfig here
  142. switch oauthType {
  143. case model.OauthTypeGithub:
  144. oauthConfig.Endpoint = github.Endpoint
  145. oauthConfig.Scopes = []string{"read:user", "user:email"}
  146. case model.OauthTypeGoogle:
  147. oauthConfig.Endpoint = google.Endpoint
  148. oauthConfig.Scopes = []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"}
  149. case model.OauthTypeOidc:
  150. err, endpoint := os.FetchOidcEndpointByOp(op)
  151. if err != nil {
  152. return err,oauthType, nil
  153. }
  154. oauthConfig.Endpoint = oauth2.Endpoint{AuthURL: endpoint.AuthURL,TokenURL: endpoint.TokenURL,}
  155. oauthConfig.Scopes = os.getScopesByOp(op)
  156. default:
  157. return errors.New("unsupported OAuth type"), oauthType, nil
  158. }
  159. return nil, oauthType, oauthConfig
  160. }
  161. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  162. func (os *OauthService) getOauthConfigGeneral(op string) (err error, oauthType string, oauthConfig *oauth2.Config) {
  163. g := os.InfoByOp(op)
  164. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" {
  165. return errors.New("ConfigNotFound"), "", nil
  166. }
  167. // If the redirect URL is empty, use the default redirect URL
  168. if g.RedirectUrl == "" {
  169. g.RedirectUrl = global.Config.Rustdesk.ApiServer + "/api/oidc/callback"
  170. }
  171. return nil, g.OauthType, &oauth2.Config{
  172. ClientID: g.ClientId,
  173. ClientSecret: g.ClientSecret,
  174. RedirectURL: g.RedirectUrl,
  175. }
  176. }
  177. func getHTTPClientWithProxy() *http.Client {
  178. //todo add timeout
  179. if global.Config.Proxy.Enable {
  180. if global.Config.Proxy.Host == "" {
  181. global.Logger.Warn("Proxy is enabled but proxy host is empty.")
  182. return http.DefaultClient
  183. }
  184. proxyURL, err := url.Parse(global.Config.Proxy.Host)
  185. if err != nil {
  186. global.Logger.Warn("Invalid proxy URL: ", err)
  187. return http.DefaultClient
  188. }
  189. transport := &http.Transport{
  190. Proxy: http.ProxyURL(proxyURL),
  191. }
  192. return &http.Client{Transport: transport}
  193. }
  194. return http.DefaultClient
  195. }
  196. func (os *OauthService) callbackBase(op string, code string, userEndpoint string, userData interface{}) error {
  197. err, oauthType, oauthConfig := os.GetOauthConfig(op)
  198. if err != nil {
  199. return err
  200. }
  201. // If the OAuth type is OIDC and the user endpoint is empty
  202. // Fetch the OIDC configuration and get the user endpoint
  203. if oauthType == model.OauthTypeOidc && userEndpoint == "" {
  204. err, endpoint := os.FetchOidcEndpointByOp(op)
  205. if err != nil {
  206. global.Logger.Warn("failed fetching OIDC configuration: ", err)
  207. return errors.New("FetchOidcEndpointError")
  208. }
  209. userEndpoint = endpoint.UserInfo
  210. }
  211. // 设置代理客户端
  212. httpClient := getHTTPClientWithProxy()
  213. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  214. // 使用 code 换取 token
  215. token, err := oauthConfig.Exchange(ctx, code)
  216. if err != nil {
  217. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  218. return errors.New("GetOauthTokenError")
  219. }
  220. // 获取用户信息
  221. client := oauthConfig.Client(ctx, token)
  222. resp, err := client.Get(userEndpoint)
  223. if err != nil {
  224. global.Logger.Warn("failed getting user info: ", err)
  225. return errors.New("GetOauthUserInfoError")
  226. }
  227. defer func() {
  228. if closeErr := resp.Body.Close(); closeErr != nil {
  229. global.Logger.Warn("failed closing response body: ", closeErr)
  230. }
  231. }()
  232. // 解析用户信息
  233. if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
  234. global.Logger.Warn("failed decoding user info: ", err)
  235. return errors.New("DecodeOauthUserInfoError")
  236. }
  237. return nil
  238. }
  239. // githubCallback github回调
  240. func (os *OauthService) githubCallback(code string) (error, *model.OauthUser) {
  241. var user = &model.GithubUser{}
  242. const userEndpoint = "https://api.github.com/user"
  243. if err := os.callbackBase(model.OauthTypeGithub, code, userEndpoint, user); err != nil {
  244. return err, nil
  245. }
  246. return nil, user.ToOauthUser()
  247. }
  248. // googleCallback google回调
  249. func (os *OauthService) googleCallback(code string) (error, *model.OauthUser) {
  250. var user = &model.GoogleUser{}
  251. const userEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo"
  252. if err := os.callbackBase(model.OauthTypeGoogle, code, userEndpoint, user); err != nil {
  253. return err, nil
  254. }
  255. return nil, user.ToOauthUser()
  256. }
  257. // oidcCallback oidc回调, 通过code获取用户信息
  258. func (os *OauthService) oidcCallback(code string, op string) (error, *model.OauthUser,) {
  259. var user = &model.OidcUser{}
  260. if err := os.callbackBase(op, code, "", user); err != nil {
  261. return err, nil
  262. }
  263. return nil, user.ToOauthUser()
  264. }
  265. // Callback: Get user information by code and op(Oauth provider)
  266. func (os *OauthService) Callback(code string, op string) (err error, oauthUser *model.OauthUser) {
  267. oauthType := os.GetTypeByOp(op)
  268. if err = os.ValidateOauthType(oauthType); err != nil {
  269. return err, nil
  270. }
  271. switch oauthType {
  272. case model.OauthTypeGithub:
  273. err, oauthUser = os.githubCallback(code)
  274. case model.OauthTypeGoogle:
  275. err, oauthUser = os.googleCallback(code)
  276. case model.OauthTypeOidc:
  277. err, oauthUser = os.oidcCallback(code, op)
  278. default:
  279. return errors.New("unsupported OAuth type"), nil
  280. }
  281. return err, oauthUser
  282. }
  283. func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
  284. ut := &model.UserThird{}
  285. global.DB.Where("open_id = ? and op = ?", openId, op).First(ut)
  286. return ut
  287. }
  288. // BindOauthUser: Bind third party account
  289. func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, op string) error {
  290. utr := &model.UserThird{}
  291. oauthType := os.GetTypeByOp(op)
  292. utr.FromOauthUser(userId, oauthUser, oauthType, op)
  293. return global.DB.Create(utr).Error
  294. }
  295. // UnBindOauthUser: Unbind third party account
  296. func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
  297. return os.UnBindThird(op, userId)
  298. }
  299. // UnBindThird: Unbind third party account
  300. func (os *OauthService) UnBindThird(op string, userId uint) error {
  301. return global.DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
  302. }
  303. // DeleteUserByUserId: When user is deleted, delete all third party bindings
  304. func (os *OauthService) DeleteUserByUserId(userId uint) error {
  305. return global.DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
  306. }
  307. // InfoById 根据id获取Oauth信息
  308. func (os *OauthService) InfoById(id uint) *model.Oauth {
  309. oauthInfo := &model.Oauth{}
  310. global.DB.Where("id = ?", id).First(oauthInfo)
  311. return oauthInfo
  312. }
  313. // InfoByOp 根据op获取Oauth信息
  314. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  315. oauthInfo := &model.Oauth{}
  316. global.DB.Where("op = ?", op).First(oauthInfo)
  317. return oauthInfo
  318. }
  319. // Helper function to get scopes by operation
  320. func (os *OauthService) getScopesByOp(op string) []string {
  321. scopes := os.InfoByOp(op).Scopes
  322. scopes = strings.TrimSpace(scopes) // 这里使用 `=` 而不是 `:=`,避免重新声明变量
  323. if scopes == "" {
  324. scopes = "openid,profile,email"
  325. }
  326. return strings.Split(scopes, ",")
  327. }
  328. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  329. res = &model.OauthList{}
  330. res.Page = int64(page)
  331. res.PageSize = int64(pageSize)
  332. tx := global.DB.Model(&model.Oauth{})
  333. if where != nil {
  334. where(tx)
  335. }
  336. tx.Count(&res.Total)
  337. tx.Scopes(Paginate(page, pageSize))
  338. tx.Find(&res.Oauths)
  339. return
  340. }
  341. // GetTypeByOp 根据op获取OauthType
  342. func (os *OauthService) GetTypeByOp(op string) string {
  343. oauthInfo := &model.Oauth{}
  344. if global.DB.Where("op = ?", op).First(oauthInfo).Error != nil {
  345. return ""
  346. }
  347. return oauthInfo.OauthType
  348. }
  349. func (os *OauthService) ValidateOauthProvider(op string) error {
  350. oauthInfo := &model.Oauth{}
  351. // 使用 Gorm 的 Take 方法查找符合条件的记录
  352. if err := global.DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
  353. return fmt.Errorf("OAuth provider with op '%s' not found: %w", op, err)
  354. }
  355. return nil
  356. }
  357. // Create 创建
  358. func (os *OauthService) Create(oauthInfo *model.Oauth) error {
  359. res := global.DB.Create(oauthInfo).Error
  360. return res
  361. }
  362. func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
  363. return global.DB.Delete(oauthInfo).Error
  364. }
  365. // Update 更新
  366. func (os *OauthService) Update(oauthInfo *model.Oauth) error {
  367. return global.DB.Model(oauthInfo).Updates(oauthInfo).Error
  368. }
  369. // GetOauthProviders 获取所有的provider
  370. func (os *OauthService) GetOauthProviders() []string {
  371. var res []string
  372. global.DB.Model(&model.Oauth{}).Pluck("op", &res)
  373. return res
  374. }