oauth.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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, oauthType, oauthConfig = os.getOauthConfigGeneral(op)
  134. if err != nil {
  135. return err, oauthType, nil
  136. }
  137. // Maybe should validate the oauthConfig here
  138. switch oauthType {
  139. case model.OauthTypeGithub:
  140. oauthConfig.Endpoint = github.Endpoint
  141. oauthConfig.Scopes = []string{"read:user", "user:email"}
  142. case model.OauthTypeGoogle:
  143. oauthConfig.Endpoint = google.Endpoint
  144. oauthConfig.Scopes = []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"}
  145. case model.OauthTypeOidc:
  146. err, endpoint := os.FetchOidcEndpointByOp(op)
  147. if err != nil {
  148. return err,oauthType, nil
  149. }
  150. oauthConfig.Endpoint = oauth2.Endpoint{AuthURL: endpoint.AuthURL,TokenURL: endpoint.TokenURL,}
  151. oauthConfig.Scopes = os.getScopesByOp(op)
  152. default:
  153. return errors.New("unsupported OAuth type"), oauthType, nil
  154. }
  155. return nil, oauthType, oauthConfig
  156. }
  157. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  158. func (os *OauthService) getOauthConfigGeneral(op string) (err error, oauthType string, oauthConfig *oauth2.Config) {
  159. g := os.InfoByOp(op)
  160. if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" {
  161. return errors.New("ConfigNotFound"), "", nil
  162. }
  163. // If the redirect URL is empty, use the default redirect URL
  164. if g.RedirectUrl == "" {
  165. g.RedirectUrl = global.Config.Rustdesk.ApiServer + "/api/oidc/callback"
  166. }
  167. return nil, g.OauthType, &oauth2.Config{
  168. ClientID: g.ClientId,
  169. ClientSecret: g.ClientSecret,
  170. RedirectURL: g.RedirectUrl,
  171. }
  172. }
  173. func getHTTPClientWithProxy() *http.Client {
  174. //todo add timeout
  175. if global.Config.Proxy.Enable {
  176. if global.Config.Proxy.Host == "" {
  177. global.Logger.Warn("Proxy is enabled but proxy host is empty.")
  178. return http.DefaultClient
  179. }
  180. proxyURL, err := url.Parse(global.Config.Proxy.Host)
  181. if err != nil {
  182. global.Logger.Warn("Invalid proxy URL: ", err)
  183. return http.DefaultClient
  184. }
  185. transport := &http.Transport{
  186. Proxy: http.ProxyURL(proxyURL),
  187. }
  188. return &http.Client{Transport: transport}
  189. }
  190. return http.DefaultClient
  191. }
  192. func (os *OauthService) callbackBase(op string, code string, userEndpoint string, userData interface{}) error {
  193. err, oauthType, oauthConfig := os.GetOauthConfig(op)
  194. if err != nil {
  195. return err
  196. }
  197. // If the OAuth type is OIDC and the user endpoint is empty
  198. // Fetch the OIDC configuration and get the user endpoint
  199. if oauthType == model.OauthTypeOidc && userEndpoint == "" {
  200. err, endpoint := os.FetchOidcEndpointByOp(op)
  201. if err != nil {
  202. global.Logger.Warn("failed fetching OIDC configuration: ", err)
  203. return errors.New("FetchOidcEndpointError")
  204. }
  205. userEndpoint = endpoint.UserInfo
  206. }
  207. // 设置代理客户端
  208. httpClient := getHTTPClientWithProxy()
  209. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  210. // 使用 code 换取 token
  211. token, err := oauthConfig.Exchange(ctx, code)
  212. if err != nil {
  213. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  214. return errors.New("GetOauthTokenError")
  215. }
  216. // 获取用户信息
  217. client := oauthConfig.Client(ctx, token)
  218. resp, err := client.Get(userEndpoint)
  219. if err != nil {
  220. global.Logger.Warn("failed getting user info: ", err)
  221. return errors.New("GetOauthUserInfoError")
  222. }
  223. defer func() {
  224. if closeErr := resp.Body.Close(); closeErr != nil {
  225. global.Logger.Warn("failed closing response body: ", closeErr)
  226. }
  227. }()
  228. // 解析用户信息
  229. if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
  230. global.Logger.Warn("failed decoding user info: ", err)
  231. return errors.New("DecodeOauthUserInfoError")
  232. }
  233. return nil
  234. }
  235. // githubCallback github回调
  236. func (os *OauthService) githubCallback(code string) (error, *model.OauthUser) {
  237. var user = &model.GithubUser{}
  238. const userEndpoint = "https://api.github.com/user"
  239. if err := os.callbackBase(model.OauthTypeGithub, code, userEndpoint, user); err != nil {
  240. return err, nil
  241. }
  242. return nil, user.ToOauthUser()
  243. }
  244. // googleCallback google回调
  245. func (os *OauthService) googleCallback(code string) (error, *model.OauthUser) {
  246. var user = &model.GoogleUser{}
  247. const userEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo"
  248. if err := os.callbackBase(model.OauthTypeGoogle, code, userEndpoint, user); err != nil {
  249. return err, nil
  250. }
  251. return nil, user.ToOauthUser()
  252. }
  253. // oidcCallback oidc回调, 通过code获取用户信息
  254. func (os *OauthService) oidcCallback(code string, op string) (error, *model.OauthUser,) {
  255. var user = &model.OidcUser{}
  256. if err := os.callbackBase(op, code, "", user); err != nil {
  257. return err, nil
  258. }
  259. return nil, user.ToOauthUser()
  260. }
  261. // Callback: Get user information by code and op(Oauth provider)
  262. func (os *OauthService) Callback(code string, op string) (err error, oauthUser *model.OauthUser) {
  263. oauthType := os.GetTypeByOp(op)
  264. if err = os.ValidateOauthType(oauthType); err != nil {
  265. return err, nil
  266. }
  267. switch oauthType {
  268. case model.OauthTypeGithub:
  269. err, oauthUser = os.githubCallback(code)
  270. case model.OauthTypeGoogle:
  271. err, oauthUser = os.googleCallback(code)
  272. case model.OauthTypeOidc:
  273. err, oauthUser = os.oidcCallback(code, op)
  274. default:
  275. return errors.New("unsupported OAuth type"), nil
  276. }
  277. return err, oauthUser
  278. }
  279. func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
  280. ut := &model.UserThird{}
  281. global.DB.Where("open_id = ? and op = ?", openId, op).First(ut)
  282. return ut
  283. }
  284. // BindOauthUser: Bind third party account
  285. func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, op string) error {
  286. utr := &model.UserThird{}
  287. oauthType := os.GetTypeByOp(op)
  288. utr.FromOauthUser(userId, oauthUser, oauthType, op)
  289. return global.DB.Create(utr).Error
  290. }
  291. // UnBindOauthUser: Unbind third party account
  292. func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
  293. return os.UnBindThird(op, userId)
  294. }
  295. // UnBindThird: Unbind third party account
  296. func (os *OauthService) UnBindThird(op string, userId uint) error {
  297. return global.DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
  298. }
  299. // DeleteUserByUserId: When user is deleted, delete all third party bindings
  300. func (os *OauthService) DeleteUserByUserId(userId uint) error {
  301. return global.DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
  302. }
  303. // InfoById 根据id获取Oauth信息
  304. func (os *OauthService) InfoById(id uint) *model.Oauth {
  305. oauthInfo := &model.Oauth{}
  306. global.DB.Where("id = ?", id).First(oauthInfo)
  307. return oauthInfo
  308. }
  309. // InfoByOp 根据op获取Oauth信息
  310. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  311. oauthInfo := &model.Oauth{}
  312. global.DB.Where("op = ?", op).First(oauthInfo)
  313. return oauthInfo
  314. }
  315. // Helper function to get scopes by operation
  316. func (os *OauthService) getScopesByOp(op string) []string {
  317. scopes := os.InfoByOp(op).Scopes
  318. scopes = strings.TrimSpace(scopes) // 这里使用 `=` 而不是 `:=`,避免重新声明变量
  319. if scopes == "" {
  320. scopes = "openid,profile,email"
  321. }
  322. return strings.Split(scopes, ",")
  323. }
  324. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  325. res = &model.OauthList{}
  326. res.Page = int64(page)
  327. res.PageSize = int64(pageSize)
  328. tx := global.DB.Model(&model.Oauth{})
  329. if where != nil {
  330. where(tx)
  331. }
  332. tx.Count(&res.Total)
  333. tx.Scopes(Paginate(page, pageSize))
  334. tx.Find(&res.Oauths)
  335. return
  336. }
  337. // GetTypeByOp 根据op获取OauthType
  338. func (os *OauthService) GetTypeByOp(op string) string {
  339. oauthInfo := &model.Oauth{}
  340. if global.DB.Where("op = ?", op).First(oauthInfo).Error != nil {
  341. return ""
  342. }
  343. return oauthInfo.OauthType
  344. }
  345. func (os *OauthService) ValidateOauthProvider(op string) error {
  346. oauthInfo := &model.Oauth{}
  347. // 使用 Gorm 的 Take 方法查找符合条件的记录
  348. if err := global.DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
  349. return fmt.Errorf("OAuth provider with op '%s' not found: %w", op, err)
  350. }
  351. return nil
  352. }
  353. // Create 创建
  354. func (os *OauthService) Create(oauthInfo *model.Oauth) error {
  355. res := global.DB.Create(oauthInfo).Error
  356. return res
  357. }
  358. func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
  359. return global.DB.Delete(oauthInfo).Error
  360. }
  361. // Update 更新
  362. func (os *OauthService) Update(oauthInfo *model.Oauth) error {
  363. return global.DB.Model(oauthInfo).Updates(oauthInfo).Error
  364. }
  365. // GetOauthProviders 获取所有的provider
  366. func (os *OauthService) GetOauthProviders() []string {
  367. var res []string
  368. global.DB.Model(&model.Oauth{}).Pluck("op", &res)
  369. return res
  370. }