-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth_on_code_platform.go
339 lines (283 loc) · 8.57 KB
/
auth_on_code_platform.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package controllers
import (
"fmt"
"strings"
platformAuth "github.com/opensourceways/app-cla-server/code-platform-auth"
"github.com/opensourceways/app-cla-server/code-platform-auth/platforms"
"github.com/opensourceways/app-cla-server/models"
)
type AuthController struct {
baseController
}
func (this *AuthController) Prepare() {
if this.isPostRequest() ||
strings.HasSuffix(this.routerPattern(), "/authcodeurl/:platform/:purpose") {
this.apiPrepare("")
}
}
// @Title Callback
// @Description callback of authentication by oauth2
// @Param :platform path string true "gitee/github"
// @Param :purpose path string true "purpose: login, sign"
// @Failure 400 auth_failed: authenticated on code platform failed
// @Failure 401 unsupported_code_platform: unsupported code platform
// @Failure 402 refuse_to_authorize_email: the user refused to access his/her email
// @Failure 403 no_public_email: no public email
// @Failure 500 system_error: system error
// @router /:platform/:purpose [get]
func (this *AuthController) Callback() {
purpose := this.GetString(":purpose")
platform := this.GetString(":platform")
authHelper, ok := platformAuth.Auth[purpose]
if !ok {
return
}
rs := func(errCode string, reason error) {
this.setCookies(map[string]string{"error_code": errCode, "error_msg": reason.Error()}, false)
this.redirect(authHelper.WebRedirectDir(false))
}
if this.GetString("state") != authURLState {
rs(errSystemError, fmt.Errorf("unkown state"))
return
}
if err := this.GetString("error"); err != "" {
rs(errAuthFailed, fmt.Errorf("%s, %s", err, this.GetString("error_description")))
return
}
ip, fr := this.getRemoteAddr()
if fr != nil {
rs(fr.errCode, fr.reason)
return
}
cp, err := authHelper.GetAuthInstance(platform)
if err != nil {
rs(errUnsupportedCodePlatform, err)
return
}
// gitee don't pass the scope paramter
token, err := cp.GetToken(this.GetString("code"), this.GetString("scope"))
if err != nil {
rs(errSystemError, err)
return
}
permission := ""
switch purpose {
case platformAuth.AuthApplyToLogin:
permission = PermissionOwnerOfOrg
case platformAuth.AuthApplyToSign:
permission = PermissionIndividualSigner
}
pl, ec, err := this.genACPayload(platform, permission, token)
if err != nil {
rs(ec, err)
return
}
at, err := this.newApiToken(permission, ip, pl)
if err != nil {
rs(errSystemError, err)
return
}
this.setCookies(map[string]string{apiAccessToken: at}, true)
cookies := map[string]string{"action": purpose, "platform": platform}
if permission == PermissionIndividualSigner {
cookies["sign_user"] = pl.User
cookies["sign_email"] = pl.Email
}
this.setCookies(cookies, false)
this.redirect(authHelper.WebRedirectDir(true))
}
type userAccount struct {
UserName string `json:"username"`
Password string `json:"password"`
}
// @Title Auth
// @Description authentication by user's password of code platform
// @Param :platform path string true "gitee/github"
// @Param body body controllers.userAccount true "body for auth on code platform"
// @Success 201 {object} map
// @Failure 400 missing_url_path_parameter: missing url path parameter
// @Failure 401 error_parsing_api_body: parse payload of request failed
// @Failure 402 unsupported_code_platform: unsupported code platform
// @Failure 500 system_error: system error
// @router /:platform [post]
func (this *AuthController) Auth() {
action := "auth by pw"
platform := this.GetString(":platform")
var body userAccount
if fr := this.fetchInputPayload(&body); fr != nil {
this.sendFailedResultAsResp(fr, action)
return
}
ip, fr := this.getRemoteAddr()
if fr != nil {
this.sendFailedResultAsResp(fr, action)
return
}
cp, err := platformAuth.Auth[platformAuth.AuthApplyToLogin].GetAuthInstance(platform)
if err != nil {
this.sendFailedResponse(400, errUnsupportedCodePlatform, err, action)
return
}
token, err := cp.PasswordCredentialsToken(body.UserName, body.Password)
if err != nil {
this.sendFailedResponse(500, errSystemError, err, action)
return
}
permission := PermissionOwnerOfOrg
pl, ec, err := this.genACPayload(platform, permission, token)
if err != nil {
this.sendFailedResponse(500, ec, err, action)
return
}
at, err := this.newApiToken(permission, ip, pl)
if err != nil {
this.sendFailedResponse(500, errSystemError, err, action)
return
}
this.sendSuccessResp(map[string]string{apiAccessToken: at})
}
func (this *AuthController) genACPayload(platform, permission, platformToken string) (*acForCodePlatformPayload, string, error) {
pt, err := platforms.NewPlatform(platformToken, "", platform)
if err != nil {
return nil, errSystemError, err
}
orgm := map[string]bool{}
links := map[string]models.OrgInfo{}
if permission == PermissionOwnerOfOrg {
orgs, err := pt.ListOrg()
if err == nil {
for _, item := range orgs {
orgm[item] = true
}
if r, err := models.ListLinks(platform, orgs); err == nil {
for i := range r {
links[r[i].LinkID] = r[i].OrgInfo
}
}
}
}
email := ""
if permission == PermissionIndividualSigner {
if email, err = pt.GetAuthorizedEmail(); err != nil {
if platforms.IsErrOfRefusedToAuthorizeEmail(err) {
return nil, errRefuseToAuthorizeEmail, err
}
if platforms.IsErrOfNoPulicEmail(err) {
return nil, errNoPublicEmail, err
}
return nil, errSystemError, err
}
}
user, err := pt.GetUser()
if err != nil {
return nil, errSystemError, err
}
return &acForCodePlatformPayload{
User: user,
Email: email,
Platform: platform,
PlatformToken: platformToken,
Orgs: orgm,
Links: links,
}, "", nil
}
// @Title AuthCodeURL
// @Description get authentication code url
// @Param :platform path string true "gitee/github"
// @Param :purpose path string true "purpose: login, sign"
// @Success 200 {object} map
// @Failure 400 missing_url_path_parameter: missing url path parameter
// @Failure 401 unsupported_code_platform: unsupported code platform
// @Failure 402 unkown_purpose_for_auth: unknown purpose parameter
// @router /authcodeurl/:platform/:purpose [get]
func (this *AuthController) AuthCodeURL() {
action := "fetch auth code url of gitee/github"
authHelper, ok := platformAuth.Auth[this.GetString(":purpose")]
if !ok {
this.sendFailedResponse(400, errUnkownPurposeForAuth, fmt.Errorf("unkonw purpose"), action)
return
}
cp, err := authHelper.GetAuthInstance(this.GetString(":platform"))
if err != nil {
this.sendFailedResponse(400, errUnsupportedCodePlatform, err, action)
return
}
this.sendSuccessResp(map[string]string{
"url": cp.GetAuthCodeURL(authURLState),
})
}
type acForCodePlatformPayload struct {
User string `json:"user"`
Email string `json:"email"`
Platform string `json:"platform"`
PlatformToken string `json:"platform_token"`
Orgs map[string]bool `json:"orgs"`
Links map[string]models.OrgInfo `json:"links"`
}
func (this *acForCodePlatformPayload) orgInfo(linkID string) *models.OrgInfo {
if this.Links == nil {
return nil
}
if v, ok := this.Links[linkID]; ok {
return &v
}
return nil
}
func (this *acForCodePlatformPayload) isOwnerOfLink(link string) *failedApiResult {
if this.Links == nil {
this.Links = map[string]models.OrgInfo{}
}
if _, ok := this.Links[link]; ok {
return nil
}
orgInfo, err := models.GetOrgOfLink(link)
if err != nil {
if err.IsErrorOf(models.ErrNoLink) {
return newFailedApiResult(400, errUnknownLink, err)
}
return parseModelError(err)
}
if err := this.isOwnerOfOrg(orgInfo.OrgID); err != nil {
return err
}
this.Links[link] = *orgInfo
return nil
}
func (this *acForCodePlatformPayload) isOwnerOfOrg(org string) *failedApiResult {
if this.Orgs == nil {
this.Orgs = map[string]bool{}
}
if this.Orgs[org] {
return nil
}
this.refreshOrg()
if !this.Orgs[org] {
return newFailedApiResult(400, errNotYoursOrg, fmt.Errorf("not the org of owner"))
}
return nil
}
func (this *acForCodePlatformPayload) refreshOrg() {
pt, err := platforms.NewPlatform(this.PlatformToken, "", this.Platform)
if err != nil {
return
}
// TODO token expiry
orgs, err := pt.ListOrg()
if err != nil {
return
}
for _, item := range orgs {
this.Orgs[item] = true
}
}
func (this *acForCodePlatformPayload) hasRepo(org, repo string) (bool, *failedApiResult) {
pt, err := platforms.NewPlatform(this.PlatformToken, "", this.Platform)
if err != nil {
return false, newFailedApiResult(400, errSystemError, err)
}
b, err := pt.HasRepo(org, repo)
if err != nil {
return false, newFailedApiResult(400, errSystemError, err)
}
return b, nil
}