|
|
@@ -9,17 +9,22 @@ import (
|
|
9
|
9
|
"errors"
|
|
10
|
10
|
"golang.org/x/oauth2"
|
|
11
|
11
|
"golang.org/x/oauth2/github"
|
|
12
|
|
- "golang.org/x/oauth2/google"
|
|
|
12
|
+ // "golang.org/x/oauth2/google"
|
|
13
|
13
|
"gorm.io/gorm"
|
|
14
|
|
- "io"
|
|
|
14
|
+ // "io"
|
|
15
|
15
|
"net/http"
|
|
16
|
16
|
"net/url"
|
|
17
|
17
|
"strconv"
|
|
18
|
18
|
"strings"
|
|
19
|
19
|
"sync"
|
|
20
|
20
|
"time"
|
|
|
21
|
+ "fmt"
|
|
21
|
22
|
)
|
|
22
|
23
|
|
|
|
24
|
+
|
|
|
25
|
+type OauthService struct {
|
|
|
26
|
+}
|
|
|
27
|
+
|
|
23
|
28
|
// Define a struct to parse the .well-known/openid-configuration response
|
|
24
|
29
|
type OidcEndpoint struct {
|
|
25
|
30
|
Issuer string `json:"issuer"`
|
|
|
@@ -28,73 +33,6 @@ type OidcEndpoint struct {
|
|
28
|
33
|
UserInfo string `json:"userinfo_endpoint"`
|
|
29
|
34
|
}
|
|
30
|
35
|
|
|
31
|
|
-type OauthService struct {
|
|
32
|
|
-}
|
|
33
|
|
-
|
|
34
|
|
-type GithubUserdata struct {
|
|
35
|
|
- AvatarUrl string `json:"avatar_url"`
|
|
36
|
|
- Bio string `json:"bio"`
|
|
37
|
|
- Blog string `json:"blog"`
|
|
38
|
|
- Collaborators int `json:"collaborators"`
|
|
39
|
|
- Company interface{} `json:"company"`
|
|
40
|
|
- CreatedAt time.Time `json:"created_at"`
|
|
41
|
|
- DiskUsage int `json:"disk_usage"`
|
|
42
|
|
- Email interface{} `json:"email"`
|
|
43
|
|
- EventsUrl string `json:"events_url"`
|
|
44
|
|
- Followers int `json:"followers"`
|
|
45
|
|
- FollowersUrl string `json:"followers_url"`
|
|
46
|
|
- Following int `json:"following"`
|
|
47
|
|
- FollowingUrl string `json:"following_url"`
|
|
48
|
|
- GistsUrl string `json:"gists_url"`
|
|
49
|
|
- GravatarId string `json:"gravatar_id"`
|
|
50
|
|
- Hireable interface{} `json:"hireable"`
|
|
51
|
|
- HtmlUrl string `json:"html_url"`
|
|
52
|
|
- Id int `json:"id"`
|
|
53
|
|
- Location interface{} `json:"location"`
|
|
54
|
|
- Login string `json:"login"`
|
|
55
|
|
- Name string `json:"name"`
|
|
56
|
|
- NodeId string `json:"node_id"`
|
|
57
|
|
- NotificationEmail interface{} `json:"notification_email"`
|
|
58
|
|
- OrganizationsUrl string `json:"organizations_url"`
|
|
59
|
|
- OwnedPrivateRepos int `json:"owned_private_repos"`
|
|
60
|
|
- Plan struct {
|
|
61
|
|
- Collaborators int `json:"collaborators"`
|
|
62
|
|
- Name string `json:"name"`
|
|
63
|
|
- PrivateRepos int `json:"private_repos"`
|
|
64
|
|
- Space int `json:"space"`
|
|
65
|
|
- } `json:"plan"`
|
|
66
|
|
- PrivateGists int `json:"private_gists"`
|
|
67
|
|
- PublicGists int `json:"public_gists"`
|
|
68
|
|
- PublicRepos int `json:"public_repos"`
|
|
69
|
|
- ReceivedEventsUrl string `json:"received_events_url"`
|
|
70
|
|
- ReposUrl string `json:"repos_url"`
|
|
71
|
|
- SiteAdmin bool `json:"site_admin"`
|
|
72
|
|
- StarredUrl string `json:"starred_url"`
|
|
73
|
|
- SubscriptionsUrl string `json:"subscriptions_url"`
|
|
74
|
|
- TotalPrivateRepos int `json:"total_private_repos"`
|
|
75
|
|
- //TwitterUsername interface{} `json:"twitter_username"`
|
|
76
|
|
- TwoFactorAuthentication bool `json:"two_factor_authentication"`
|
|
77
|
|
- Type string `json:"type"`
|
|
78
|
|
- UpdatedAt time.Time `json:"updated_at"`
|
|
79
|
|
- Url string `json:"url"`
|
|
80
|
|
-}
|
|
81
|
|
-type GoogleUserdata struct {
|
|
82
|
|
- Email string `json:"email"`
|
|
83
|
|
- FamilyName string `json:"family_name"`
|
|
84
|
|
- GivenName string `json:"given_name"`
|
|
85
|
|
- Id string `json:"id"`
|
|
86
|
|
- Name string `json:"name"`
|
|
87
|
|
- Picture string `json:"picture"`
|
|
88
|
|
- VerifiedEmail bool `json:"verified_email"`
|
|
89
|
|
-}
|
|
90
|
|
-type OidcUserdata struct {
|
|
91
|
|
- Sub string `json:"sub"`
|
|
92
|
|
- Email string `json:"email"`
|
|
93
|
|
- VerifiedEmail bool `json:"email_verified"`
|
|
94
|
|
- Name string `json:"name"`
|
|
95
|
|
- PreferredUsername string `json:"preferred_username"`
|
|
96
|
|
-}
|
|
97
|
|
-
|
|
98
|
36
|
type OauthCacheItem struct {
|
|
99
|
37
|
UserId uint `json:"user_id"`
|
|
100
|
38
|
Id string `json:"id"` //rustdesk的设备ID
|
|
|
@@ -104,9 +42,19 @@ type OauthCacheItem struct {
|
|
104
|
42
|
DeviceName string `json:"device_name"`
|
|
105
|
43
|
DeviceOs string `json:"device_os"`
|
|
106
|
44
|
DeviceType string `json:"device_type"`
|
|
107
|
|
- ThirdOpenId string `json:"third_open_id"`
|
|
108
|
|
- ThirdName string `json:"third_name"`
|
|
109
|
|
- ThirdEmail string `json:"third_email"`
|
|
|
45
|
+ OpenId string `json:"open_id"`
|
|
|
46
|
+ Username string `json:"username"`
|
|
|
47
|
+ Name string `json:"name"`
|
|
|
48
|
+ Email string `json:"email"`
|
|
|
49
|
+}
|
|
|
50
|
+
|
|
|
51
|
+func (oci *OauthCacheItem) ToOauthUser() *model.OauthUser {
|
|
|
52
|
+ return &model.OauthUser{
|
|
|
53
|
+ OpenId: oci.OpenId,
|
|
|
54
|
+ Username: oci.Username,
|
|
|
55
|
+ Name: oci.Name,
|
|
|
56
|
+ Email: oci.Email,
|
|
|
57
|
+ }
|
|
110
|
58
|
}
|
|
111
|
59
|
|
|
112
|
60
|
var OauthCache = &sync.Map{}
|
|
|
@@ -116,6 +64,14 @@ const (
|
|
116
|
64
|
OauthActionTypeBind = "bind"
|
|
117
|
65
|
)
|
|
118
|
66
|
|
|
|
67
|
+func (oa *OauthCacheItem) UpdateFromOauthUser(oauthUser *model.OauthUser) {
|
|
|
68
|
+ oa.OpenId = oauthUser.OpenId
|
|
|
69
|
+ oa.Username = oauthUser.Username
|
|
|
70
|
+ oa.Name = oauthUser.Name
|
|
|
71
|
+ oa.Email = oauthUser.Email
|
|
|
72
|
+}
|
|
|
73
|
+
|
|
|
74
|
+
|
|
119
|
75
|
func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
|
|
120
|
76
|
v, ok := OauthCache.Load(key)
|
|
121
|
77
|
if !ok {
|
|
|
@@ -140,22 +96,21 @@ func (os *OauthService) DeleteOauthCache(key string) {
|
|
140
|
96
|
|
|
141
|
97
|
func (os *OauthService) BeginAuth(op string) (error error, code, url string) {
|
|
142
|
98
|
code = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
|
|
143
|
|
-
|
|
144
|
|
- if op == model.OauthTypeWebauth {
|
|
|
99
|
+ if op == string(model.OauthTypeWebauth) {
|
|
145
|
100
|
url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + code
|
|
146
|
101
|
//url = "http://localhost:8888/_admin/#/oauth/" + code
|
|
147
|
102
|
return nil, code, url
|
|
148
|
103
|
}
|
|
149
|
|
- err, conf := os.GetOauthConfig(op)
|
|
|
104
|
+ err, _, oauthConfig := os.GetOauthConfig(op)
|
|
150
|
105
|
if err == nil {
|
|
151
|
|
- return err, code, conf.AuthCodeURL(code)
|
|
|
106
|
+ return err, code, oauthConfig.AuthCodeURL(code)
|
|
152
|
107
|
}
|
|
153
|
108
|
|
|
154
|
109
|
return err, code, ""
|
|
155
|
110
|
}
|
|
156
|
111
|
|
|
157
|
112
|
// Method to fetch OIDC configuration dynamically
|
|
158
|
|
-func FetchOidcConfig(issuer string) (error, OidcEndpoint) {
|
|
|
113
|
+func (os *OauthService) FetchOidcEndpoint(issuer string) (error, OidcEndpoint) {
|
|
159
|
114
|
configURL := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
|
|
160
|
115
|
|
|
161
|
116
|
// Get the HTTP client (with or without proxy based on configuration)
|
|
|
@@ -179,76 +134,58 @@ func FetchOidcConfig(issuer string) (error, OidcEndpoint) {
|
|
179
|
134
|
return nil, endpoint
|
|
180
|
135
|
}
|
|
181
|
136
|
|
|
182
|
|
-// GetOauthConfig retrieves the OAuth2 configuration based on the provider type
|
|
183
|
|
-func (os *OauthService) GetOauthConfig(op string) (error, *oauth2.Config) {
|
|
184
|
|
- switch op {
|
|
185
|
|
- case model.OauthTypeGithub:
|
|
186
|
|
- return os.getGithubConfig()
|
|
187
|
|
- case model.OauthTypeGoogle:
|
|
188
|
|
- return os.getGoogleConfig()
|
|
189
|
|
- case model.OauthTypeOidc:
|
|
190
|
|
- return os.getOidcConfig()
|
|
191
|
|
- default:
|
|
192
|
|
- return errors.New("unsupported OAuth type"), nil
|
|
|
137
|
+func (os *OauthService) FetchOidcEndpointByOp(op string) (error, OidcEndpoint) {
|
|
|
138
|
+ oauthInfo := os.InfoByOp(op)
|
|
|
139
|
+ if oauthInfo.Issuer == "" {
|
|
|
140
|
+ return errors.New("issuer is empty"), OidcEndpoint{}
|
|
193
|
141
|
}
|
|
|
142
|
+ return os.FetchOidcEndpoint(oauthInfo.Issuer)
|
|
194
|
143
|
}
|
|
195
|
144
|
|
|
196
|
|
-// Helper function to get GitHub OAuth2 configuration
|
|
197
|
|
-func (os *OauthService) getGithubConfig() (error, *oauth2.Config) {
|
|
198
|
|
- g := os.InfoByOp(model.OauthTypeGithub)
|
|
199
|
|
- if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
|
|
200
|
|
- return errors.New("ConfigNotFound"), nil
|
|
201
|
|
- }
|
|
202
|
|
- return nil, &oauth2.Config{
|
|
203
|
|
- ClientID: g.ClientId,
|
|
204
|
|
- ClientSecret: g.ClientSecret,
|
|
205
|
|
- RedirectURL: g.RedirectUrl,
|
|
206
|
|
- Endpoint: github.Endpoint,
|
|
207
|
|
- Scopes: []string{"read:user", "user:email"},
|
|
|
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) {
|
|
|
147
|
+ err, oauthInfo, oauthConfig = os.getOauthConfigGeneral(op)
|
|
|
148
|
+ if err != nil {
|
|
|
149
|
+ return err, nil, nil
|
|
208
|
150
|
}
|
|
209
|
|
-}
|
|
210
|
|
-
|
|
211
|
|
-// Helper function to get Google OAuth2 configuration
|
|
212
|
|
-func (os *OauthService) getGoogleConfig() (error, *oauth2.Config) {
|
|
213
|
|
- g := os.InfoByOp(model.OauthTypeGoogle)
|
|
214
|
|
- if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" {
|
|
215
|
|
- return errors.New("ConfigNotFound"), nil
|
|
|
151
|
+ // Maybe should validate the oauthConfig here
|
|
|
152
|
+ oauthType := oauthInfo.OauthType
|
|
|
153
|
+ err = model.ValidateOauthType(oauthType)
|
|
|
154
|
+ if err != nil {
|
|
|
155
|
+ return err, nil, nil
|
|
216
|
156
|
}
|
|
217
|
|
- return nil, &oauth2.Config{
|
|
218
|
|
- ClientID: g.ClientId,
|
|
219
|
|
- ClientSecret: g.ClientSecret,
|
|
220
|
|
- RedirectURL: g.RedirectUrl,
|
|
221
|
|
- Endpoint: google.Endpoint,
|
|
222
|
|
- Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"},
|
|
|
157
|
+ switch oauthType {
|
|
|
158
|
+ case model.OauthTypeGithub:
|
|
|
159
|
+ oauthConfig.Endpoint = github.Endpoint
|
|
|
160
|
+ oauthConfig.Scopes = []string{"read:user", "user:email"}
|
|
|
161
|
+ case model.OauthTypeOidc, model.OauthTypeGoogle:
|
|
|
162
|
+ var endpoint OidcEndpoint
|
|
|
163
|
+ err, endpoint = os.FetchOidcEndpoint(oauthInfo.Issuer)
|
|
|
164
|
+ if err != nil {
|
|
|
165
|
+ return err, nil, nil
|
|
|
166
|
+ }
|
|
|
167
|
+ oauthConfig.Endpoint = oauth2.Endpoint{AuthURL: endpoint.AuthURL,TokenURL: endpoint.TokenURL,}
|
|
|
168
|
+ oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
|
|
|
169
|
+ default:
|
|
|
170
|
+ return errors.New("unsupported OAuth type"), nil, nil
|
|
223
|
171
|
}
|
|
|
172
|
+ return nil, oauthInfo, oauthConfig
|
|
224
|
173
|
}
|
|
225
|
174
|
|
|
226
|
|
-// Helper function to get OIDC OAuth2 configuration
|
|
227
|
|
-func (os *OauthService) getOidcConfig() (error, *oauth2.Config) {
|
|
228
|
|
- g := os.InfoByOp(model.OauthTypeOidc)
|
|
229
|
|
- if g.Id == 0 || g.ClientId == "" || g.ClientSecret == "" || g.RedirectUrl == "" || g.Issuer == "" {
|
|
230
|
|
- return errors.New("ConfigNotFound"), nil
|
|
|
175
|
+// GetOauthConfig retrieves the OAuth2 configuration based on the provider name
|
|
|
176
|
+func (os *OauthService) getOauthConfigGeneral(op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config) {
|
|
|
177
|
+ oauthInfo = os.InfoByOp(op)
|
|
|
178
|
+ if oauthInfo.Id == 0 || oauthInfo.ClientId == "" || oauthInfo.ClientSecret == "" {
|
|
|
179
|
+ return errors.New("ConfigNotFound"), nil, nil
|
|
231
|
180
|
}
|
|
232
|
|
-
|
|
233
|
|
- // Set scopes
|
|
234
|
|
- scopes := strings.TrimSpace(g.Scopes)
|
|
235
|
|
- if scopes == "" {
|
|
236
|
|
- scopes = "openid,profile,email"
|
|
|
181
|
+ // If the redirect URL is empty, use the default redirect URL
|
|
|
182
|
+ if oauthInfo.RedirectUrl == "" {
|
|
|
183
|
+ oauthInfo.RedirectUrl = global.Config.Rustdesk.ApiServer + "/api/oidc/callback"
|
|
237
|
184
|
}
|
|
238
|
|
- scopeList := strings.Split(scopes, ",")
|
|
239
|
|
- err, endpoint := FetchOidcConfig(g.Issuer)
|
|
240
|
|
- if err != nil {
|
|
241
|
|
- return err, nil
|
|
242
|
|
- }
|
|
243
|
|
- return nil, &oauth2.Config{
|
|
244
|
|
- ClientID: g.ClientId,
|
|
245
|
|
- ClientSecret: g.ClientSecret,
|
|
246
|
|
- RedirectURL: g.RedirectUrl,
|
|
247
|
|
- Endpoint: oauth2.Endpoint{
|
|
248
|
|
- AuthURL: endpoint.AuthURL,
|
|
249
|
|
- TokenURL: endpoint.TokenURL,
|
|
250
|
|
- },
|
|
251
|
|
- Scopes: scopeList,
|
|
|
185
|
+ return nil, oauthInfo, &oauth2.Config{
|
|
|
186
|
+ ClientID: oauthInfo.ClientId,
|
|
|
187
|
+ ClientSecret: oauthInfo.ClientSecret,
|
|
|
188
|
+ RedirectURL: oauthInfo.RedirectUrl,
|
|
252
|
189
|
}
|
|
253
|
190
|
}
|
|
254
|
191
|
|
|
|
@@ -272,194 +209,153 @@ func getHTTPClientWithProxy() *http.Client {
|
|
272
|
209
|
return http.DefaultClient
|
|
273
|
210
|
}
|
|
274
|
211
|
|
|
275
|
|
-func (os *OauthService) GithubCallback(code string) (error error, userData *GithubUserdata) {
|
|
276
|
|
- err, oauthConfig := os.GetOauthConfig(model.OauthTypeGithub)
|
|
277
|
|
- if err != nil {
|
|
278
|
|
- return err, nil
|
|
279
|
|
- }
|
|
|
212
|
+func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, code string, userEndpoint string, userData interface{}) (err error, client *http.Client) {
|
|
280
|
213
|
|
|
281
|
|
- // 使用代理配置创建 HTTP 客户端
|
|
|
214
|
+ // 设置代理客户端
|
|
282
|
215
|
httpClient := getHTTPClientWithProxy()
|
|
283
|
216
|
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
|
|
284
|
217
|
|
|
285
|
|
- token, err := oauthConfig.Exchange(ctx, code)
|
|
|
218
|
+ // 使用 code 换取 token
|
|
|
219
|
+ var token *oauth2.Token
|
|
|
220
|
+ token, err = oauthConfig.Exchange(ctx, code)
|
|
286
|
221
|
if err != nil {
|
|
287
|
222
|
global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
|
|
288
|
|
- error = errors.New("GetOauthTokenError")
|
|
289
|
|
- return
|
|
|
223
|
+ return errors.New("GetOauthTokenError"), nil
|
|
290
|
224
|
}
|
|
291
|
225
|
|
|
292
|
|
- // 使用带有代理的 HTTP 客户端获取用户信息
|
|
293
|
|
- client := oauthConfig.Client(ctx, token)
|
|
294
|
|
- resp, err := client.Get("https://api.github.com/user")
|
|
|
226
|
+ // 获取用户信息
|
|
|
227
|
+ client = oauthConfig.Client(ctx, token)
|
|
|
228
|
+ resp, err := client.Get(userEndpoint)
|
|
295
|
229
|
if err != nil {
|
|
296
|
230
|
global.Logger.Warn("failed getting user info: ", err)
|
|
297
|
|
- error = errors.New("GetOauthUserInfoError")
|
|
298
|
|
- return
|
|
|
231
|
+ return errors.New("GetOauthUserInfoError"), nil
|
|
299
|
232
|
}
|
|
300
|
|
- defer func(Body io.ReadCloser) {
|
|
301
|
|
- err := Body.Close()
|
|
302
|
|
- if err != nil {
|
|
303
|
|
- global.Logger.Warn("failed closing response body: ", err)
|
|
|
233
|
+ defer func() {
|
|
|
234
|
+ if closeErr := resp.Body.Close(); closeErr != nil {
|
|
|
235
|
+ global.Logger.Warn("failed closing response body: ", closeErr)
|
|
304
|
236
|
}
|
|
305
|
|
- }(resp.Body)
|
|
|
237
|
+ }()
|
|
306
|
238
|
|
|
307
|
239
|
// 解析用户信息
|
|
308
|
|
- if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
|
|
|
240
|
+ if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
|
|
309
|
241
|
global.Logger.Warn("failed decoding user info: ", err)
|
|
310
|
|
- error = errors.New("DecodeOauthUserInfoError")
|
|
311
|
|
- return
|
|
|
242
|
+ return errors.New("DecodeOauthUserInfoError"), nil
|
|
312
|
243
|
}
|
|
313
|
|
- return
|
|
|
244
|
+
|
|
|
245
|
+ return nil, client
|
|
314
|
246
|
}
|
|
315
|
247
|
|
|
316
|
|
-func (os *OauthService) GoogleCallback(code string) (error error, userData *GoogleUserdata) {
|
|
317
|
|
- err, oauthConfig := os.GetOauthConfig(model.OauthTypeGoogle)
|
|
|
248
|
+// githubCallback github回调
|
|
|
249
|
+func (os *OauthService) githubCallback(oauthConfig *oauth2.Config, code string) (error, *model.OauthUser) {
|
|
|
250
|
+ var user = &model.GithubUser{}
|
|
|
251
|
+ err, client := os.callbackBase(oauthConfig, code, model.UserEndpointGithub, user)
|
|
318
|
252
|
if err != nil {
|
|
319
|
253
|
return err, nil
|
|
320
|
254
|
}
|
|
321
|
|
-
|
|
322
|
|
- // 使用代理配置创建 HTTP 客户端
|
|
323
|
|
- httpClient := getHTTPClientWithProxy()
|
|
324
|
|
- ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
|
|
325
|
|
-
|
|
326
|
|
- token, err := oauthConfig.Exchange(ctx, code)
|
|
|
255
|
+ err = os.getGithubPrimaryEmail(client, user)
|
|
327
|
256
|
if err != nil {
|
|
328
|
|
- global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
|
|
329
|
|
- error = errors.New("GetOauthTokenError")
|
|
330
|
|
- return
|
|
|
257
|
+ return err, nil
|
|
331
|
258
|
}
|
|
|
259
|
+ return nil, user.ToOauthUser()
|
|
|
260
|
+}
|
|
332
|
261
|
|
|
333
|
|
- // 使用带有代理的 HTTP 客户端获取用户信息
|
|
334
|
|
- client := oauthConfig.Client(ctx, token)
|
|
335
|
|
- resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
|
|
336
|
|
- if err != nil {
|
|
337
|
|
- global.Logger.Warn("failed getting user info: ", err)
|
|
338
|
|
- error = errors.New("GetOauthUserInfoError")
|
|
339
|
|
- return
|
|
340
|
|
- }
|
|
341
|
|
- defer func(Body io.ReadCloser) {
|
|
342
|
|
- err := Body.Close()
|
|
343
|
|
- if err != nil {
|
|
344
|
|
- global.Logger.Warn("failed closing response body: ", err)
|
|
345
|
|
- }
|
|
346
|
|
- }(resp.Body)
|
|
347
|
262
|
|
|
348
|
|
- // 解析用户信息
|
|
349
|
|
- if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
|
|
350
|
|
- global.Logger.Warn("failed decoding user info: ", err)
|
|
351
|
|
- error = errors.New("DecodeOauthUserInfoError")
|
|
352
|
|
- return
|
|
|
263
|
+// oidcCallback oidc回调, 通过code获取用户信息
|
|
|
264
|
+func (os *OauthService) oidcCallback(oauthConfig *oauth2.Config, code string, userInfoEndpoint string) (error, *model.OauthUser,) {
|
|
|
265
|
+ var user = &model.OidcUser{}
|
|
|
266
|
+ if err, _ := os.callbackBase(oauthConfig, code, userInfoEndpoint, user); err != nil {
|
|
|
267
|
+ return err, nil
|
|
353
|
268
|
}
|
|
354
|
|
- return
|
|
|
269
|
+ return nil, user.ToOauthUser()
|
|
355
|
270
|
}
|
|
356
|
271
|
|
|
357
|
|
-func (os *OauthService) OidcCallback(code string) (error error, userData *OidcUserdata) {
|
|
358
|
|
- err, oauthConfig := os.GetOauthConfig(model.OauthTypeOidc)
|
|
|
272
|
+// Callback: Get user information by code and op(Oauth provider)
|
|
|
273
|
+func (os *OauthService) Callback(code string, op string) (err error, oauthUser *model.OauthUser) {
|
|
|
274
|
+ var oauthInfo *model.Oauth
|
|
|
275
|
+ var oauthConfig *oauth2.Config
|
|
|
276
|
+ err, oauthInfo, oauthConfig = os.GetOauthConfig(op)
|
|
|
277
|
+ // oauthType is already validated in GetOauthConfig
|
|
359
|
278
|
if err != nil {
|
|
360
|
279
|
return err, nil
|
|
361
|
280
|
}
|
|
362
|
|
- // 使用代理配置创建 HTTP 客户端
|
|
363
|
|
- httpClient := getHTTPClientWithProxy()
|
|
364
|
|
- ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
|
|
365
|
|
-
|
|
366
|
|
- token, err := oauthConfig.Exchange(ctx, code)
|
|
367
|
|
- if err != nil {
|
|
368
|
|
- global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
|
|
369
|
|
- error = errors.New("GetOauthTokenError")
|
|
370
|
|
- return
|
|
371
|
|
- }
|
|
372
|
|
-
|
|
373
|
|
- // 使用带有代理的 HTTP 客户端获取用户信息
|
|
374
|
|
- client := oauthConfig.Client(ctx, token)
|
|
375
|
|
- g := os.InfoByOp(model.OauthTypeOidc)
|
|
376
|
|
- err, endpoint := FetchOidcConfig(g.Issuer)
|
|
377
|
|
- if err != nil {
|
|
378
|
|
- global.Logger.Warn("failed fetching OIDC configuration: ", err)
|
|
379
|
|
- error = errors.New("FetchOidcConfigError")
|
|
380
|
|
- return
|
|
381
|
|
- }
|
|
382
|
|
- resp, err := client.Get(endpoint.UserInfo)
|
|
383
|
|
- if err != nil {
|
|
384
|
|
- global.Logger.Warn("failed getting user info: ", err)
|
|
385
|
|
- error = errors.New("GetOauthUserInfoError")
|
|
386
|
|
- return
|
|
387
|
|
- }
|
|
388
|
|
- defer func(Body io.ReadCloser) {
|
|
389
|
|
- err := Body.Close()
|
|
|
281
|
+ oauthType := oauthInfo.OauthType
|
|
|
282
|
+ switch oauthType {
|
|
|
283
|
+ case model.OauthTypeGithub:
|
|
|
284
|
+ err, oauthUser = os.githubCallback(oauthConfig, code)
|
|
|
285
|
+ case model.OauthTypeOidc, model.OauthTypeGoogle:
|
|
|
286
|
+ err, endpoint := os.FetchOidcEndpoint(oauthInfo.Issuer)
|
|
390
|
287
|
if err != nil {
|
|
391
|
|
- global.Logger.Warn("failed closing response body: ", err)
|
|
|
288
|
+ return err, nil
|
|
392
|
289
|
}
|
|
393
|
|
- }(resp.Body)
|
|
394
|
|
-
|
|
395
|
|
- // 解析用户信息
|
|
396
|
|
- if err = json.NewDecoder(resp.Body).Decode(&userData); err != nil {
|
|
397
|
|
- global.Logger.Warn("failed decoding user info: ", err)
|
|
398
|
|
- error = errors.New("DecodeOauthUserInfoError")
|
|
399
|
|
- return
|
|
400
|
|
- }
|
|
401
|
|
- return
|
|
|
290
|
+ err, oauthUser = os.oidcCallback(oauthConfig, code, endpoint.UserInfo)
|
|
|
291
|
+ default:
|
|
|
292
|
+ return errors.New("unsupported OAuth type"), nil
|
|
|
293
|
+ }
|
|
|
294
|
+ return err, oauthUser
|
|
402
|
295
|
}
|
|
403
|
296
|
|
|
404
|
|
-func (os *OauthService) UserThirdInfo(op, openid string) *model.UserThird {
|
|
|
297
|
+
|
|
|
298
|
+func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
|
|
405
|
299
|
ut := &model.UserThird{}
|
|
406
|
|
- global.DB.Where("open_id = ? and third_type = ?", openid, op).First(ut)
|
|
|
300
|
+ global.DB.Where("open_id = ? and op = ?", openId, op).First(ut)
|
|
407
|
301
|
return ut
|
|
408
|
302
|
}
|
|
409
|
303
|
|
|
410
|
|
-func (os *OauthService) BindGithubUser(openid, username string, userId uint) error {
|
|
411
|
|
- return os.BindOauthUser(model.OauthTypeGithub, openid, username, userId)
|
|
412
|
|
-}
|
|
413
|
|
-
|
|
414
|
|
-func (os *OauthService) BindGoogleUser(email, username string, userId uint) error {
|
|
415
|
|
- return os.BindOauthUser(model.OauthTypeGoogle, email, username, userId)
|
|
416
|
|
-}
|
|
417
|
|
-
|
|
418
|
|
-func (os *OauthService) BindOidcUser(sub, username string, userId uint) error {
|
|
419
|
|
- return os.BindOauthUser(model.OauthTypeOidc, sub, username, userId)
|
|
420
|
|
-}
|
|
421
|
|
-
|
|
422
|
|
-func (os *OauthService) BindOauthUser(thirdType, openid, username string, userId uint) error {
|
|
423
|
|
- utr := &model.UserThird{
|
|
424
|
|
- OpenId: openid,
|
|
425
|
|
- ThirdType: thirdType,
|
|
426
|
|
- ThirdName: username,
|
|
427
|
|
- UserId: userId,
|
|
|
304
|
+// BindOauthUser: Bind third party account
|
|
|
305
|
+func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, op string) error {
|
|
|
306
|
+ utr := &model.UserThird{}
|
|
|
307
|
+ err, oauthType := os.GetTypeByOp(op)
|
|
|
308
|
+ if err != nil {
|
|
|
309
|
+ return err
|
|
428
|
310
|
}
|
|
|
311
|
+ utr.FromOauthUser(userId, oauthUser, oauthType, op)
|
|
429
|
312
|
return global.DB.Create(utr).Error
|
|
430
|
313
|
}
|
|
431
|
314
|
|
|
432
|
|
-func (os *OauthService) UnBindGithubUser(userid uint) error {
|
|
433
|
|
- return os.UnBindThird(model.OauthTypeGithub, userid)
|
|
|
315
|
+// UnBindOauthUser: Unbind third party account
|
|
|
316
|
+func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
|
|
|
317
|
+ return os.UnBindThird(op, userId)
|
|
434
|
318
|
}
|
|
435
|
|
-func (os *OauthService) UnBindGoogleUser(userid uint) error {
|
|
436
|
|
- return os.UnBindThird(model.OauthTypeGoogle, userid)
|
|
437
|
|
-}
|
|
438
|
|
-func (os *OauthService) UnBindOidcUser(userid uint) error {
|
|
439
|
|
- return os.UnBindThird(model.OauthTypeOidc, userid)
|
|
440
|
|
-}
|
|
441
|
|
-func (os *OauthService) UnBindThird(thirdType string, userid uint) error {
|
|
442
|
|
- return global.DB.Where("user_id = ? and third_type = ?", userid, thirdType).Delete(&model.UserThird{}).Error
|
|
|
319
|
+
|
|
|
320
|
+// UnBindThird: Unbind third party account
|
|
|
321
|
+func (os *OauthService) UnBindThird(op string, userId uint) error {
|
|
|
322
|
+ return global.DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
|
|
443
|
323
|
}
|
|
444
|
324
|
|
|
445
|
325
|
// DeleteUserByUserId: When user is deleted, delete all third party bindings
|
|
446
|
|
-func (os *OauthService) DeleteUserByUserId(userid uint) error {
|
|
447
|
|
- return global.DB.Where("user_id = ?", userid).Delete(&model.UserThird{}).Error
|
|
|
326
|
+func (os *OauthService) DeleteUserByUserId(userId uint) error {
|
|
|
327
|
+ return global.DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
|
|
448
|
328
|
}
|
|
449
|
329
|
|
|
450
|
|
-// InfoById 根据id取用户信息
|
|
|
330
|
+// InfoById 根据id获取Oauth信息
|
|
451
|
331
|
func (os *OauthService) InfoById(id uint) *model.Oauth {
|
|
452
|
|
- u := &model.Oauth{}
|
|
453
|
|
- global.DB.Where("id = ?", id).First(u)
|
|
454
|
|
- return u
|
|
|
332
|
+ oauthInfo := &model.Oauth{}
|
|
|
333
|
+ global.DB.Where("id = ?", id).First(oauthInfo)
|
|
|
334
|
+ return oauthInfo
|
|
455
|
335
|
}
|
|
456
|
336
|
|
|
457
|
|
-// InfoByOp 根据op取用户信息
|
|
|
337
|
+// InfoByOp 根据op获取Oauth信息
|
|
458
|
338
|
func (os *OauthService) InfoByOp(op string) *model.Oauth {
|
|
459
|
|
- u := &model.Oauth{}
|
|
460
|
|
- global.DB.Where("op = ?", op).First(u)
|
|
461
|
|
- return u
|
|
|
339
|
+ oauthInfo := &model.Oauth{}
|
|
|
340
|
+ global.DB.Where("op = ?", op).First(oauthInfo)
|
|
|
341
|
+ return oauthInfo
|
|
462
|
342
|
}
|
|
|
343
|
+
|
|
|
344
|
+// Helper function to get scopes by operation
|
|
|
345
|
+func (os *OauthService) getScopesByOp(op string) []string {
|
|
|
346
|
+ scopes := os.InfoByOp(op).Scopes
|
|
|
347
|
+ return os.constructScopes(scopes)
|
|
|
348
|
+}
|
|
|
349
|
+
|
|
|
350
|
+// Helper function to construct scopes
|
|
|
351
|
+func (os *OauthService) constructScopes(scopes string) []string {
|
|
|
352
|
+ scopes = strings.TrimSpace(scopes)
|
|
|
353
|
+ if scopes == "" {
|
|
|
354
|
+ scopes = model.OIDC_DEFAULT_SCOPES
|
|
|
355
|
+ }
|
|
|
356
|
+ return strings.Split(scopes, ",")
|
|
|
357
|
+}
|
|
|
358
|
+
|
|
463
|
359
|
func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
|
|
464
|
360
|
res = &model.OauthList{}
|
|
465
|
361
|
res.Page = int64(page)
|
|
|
@@ -474,16 +370,95 @@ func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
|
|
474
|
370
|
return
|
|
475
|
371
|
}
|
|
476
|
372
|
|
|
|
373
|
+// GetTypeByOp 根据op获取OauthType
|
|
|
374
|
+func (os *OauthService) GetTypeByOp(op string) (error, string) {
|
|
|
375
|
+ oauthInfo := &model.Oauth{}
|
|
|
376
|
+ if global.DB.Where("op = ?", op).First(oauthInfo).Error != nil {
|
|
|
377
|
+ return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
|
|
|
378
|
+ }
|
|
|
379
|
+ return nil, oauthInfo.OauthType
|
|
|
380
|
+}
|
|
|
381
|
+
|
|
|
382
|
+// ValidateOauthProvider 验证Oauth提供者是否正确
|
|
|
383
|
+func (os *OauthService) ValidateOauthProvider(op string) error {
|
|
|
384
|
+ if !os.IsOauthProviderExist(op) {
|
|
|
385
|
+ return fmt.Errorf("OAuth provider with op '%s' not found", op)
|
|
|
386
|
+ }
|
|
|
387
|
+ return nil
|
|
|
388
|
+}
|
|
|
389
|
+
|
|
|
390
|
+// IsOauthProviderExist 验证Oauth提供者是否存在
|
|
|
391
|
+func (os *OauthService) IsOauthProviderExist(op string) bool {
|
|
|
392
|
+ oauthInfo := &model.Oauth{}
|
|
|
393
|
+ // 使用 Gorm 的 Take 方法查找符合条件的记录
|
|
|
394
|
+ if err := global.DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
|
|
|
395
|
+ return false
|
|
|
396
|
+ }
|
|
|
397
|
+ return true
|
|
|
398
|
+}
|
|
|
399
|
+
|
|
477
|
400
|
// Create 创建
|
|
478
|
|
-func (os *OauthService) Create(u *model.Oauth) error {
|
|
479
|
|
- res := global.DB.Create(u).Error
|
|
|
401
|
+func (os *OauthService) Create(oauthInfo *model.Oauth) error {
|
|
|
402
|
+ err := oauthInfo.FormatOauthInfo()
|
|
|
403
|
+ if err != nil {
|
|
|
404
|
+ return err
|
|
|
405
|
+ }
|
|
|
406
|
+ res := global.DB.Create(oauthInfo).Error
|
|
480
|
407
|
return res
|
|
481
|
408
|
}
|
|
482
|
|
-func (os *OauthService) Delete(u *model.Oauth) error {
|
|
483
|
|
- return global.DB.Delete(u).Error
|
|
|
409
|
+func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
|
|
|
410
|
+ return global.DB.Delete(oauthInfo).Error
|
|
484
|
411
|
}
|
|
485
|
412
|
|
|
486
|
413
|
// Update 更新
|
|
487
|
|
-func (os *OauthService) Update(u *model.Oauth) error {
|
|
488
|
|
- return global.DB.Model(u).Updates(u).Error
|
|
|
414
|
+func (os *OauthService) Update(oauthInfo *model.Oauth) error {
|
|
|
415
|
+ err := oauthInfo.FormatOauthInfo()
|
|
|
416
|
+ if err != nil {
|
|
|
417
|
+ return err
|
|
|
418
|
+ }
|
|
|
419
|
+ return global.DB.Model(oauthInfo).Updates(oauthInfo).Error
|
|
489
|
420
|
}
|
|
|
421
|
+
|
|
|
422
|
+// GetOauthProviders 获取所有的provider
|
|
|
423
|
+func (os *OauthService) GetOauthProviders() []string {
|
|
|
424
|
+ var res []string
|
|
|
425
|
+ global.DB.Model(&model.Oauth{}).Pluck("op", &res)
|
|
|
426
|
+ return res
|
|
|
427
|
+}
|
|
|
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
|
+
|
|
|
438
|
+ // check the response status code
|
|
|
439
|
+ if resp.StatusCode != http.StatusOK {
|
|
|
440
|
+ return fmt.Errorf("failed to fetch emails: %s", resp.Status)
|
|
|
441
|
+ }
|
|
|
442
|
+
|
|
|
443
|
+ // decode the response
|
|
|
444
|
+ var emails []struct {
|
|
|
445
|
+ Email string `json:"email"`
|
|
|
446
|
+ Primary bool `json:"primary"`
|
|
|
447
|
+ Verified bool `json:"verified"`
|
|
|
448
|
+ }
|
|
|
449
|
+
|
|
|
450
|
+ if err := json.NewDecoder(resp.Body).Decode(&emails); err != nil {
|
|
|
451
|
+ return fmt.Errorf("failed to decode response: %w", err)
|
|
|
452
|
+ }
|
|
|
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
|
+
|
|
|
463
|
+ return fmt.Errorf("no primary verified email found")
|
|
|
464
|
+}
|