Parse scope for request when adding a token

This commit is contained in:
harryzcy 2022-09-07 10:34:34 -04:00
parent cfcbdba1f8
commit 4b570b83f8
No known key found for this signature in database
GPG key ID: CC2953E050C19686
3 changed files with 43 additions and 2 deletions

View file

@ -44,8 +44,9 @@ func ApplicationsPost(ctx *context.Context) {
}
t := &auth_model.AccessToken{
UID: ctx.Doer.ID,
Name: form.Name,
UID: ctx.Doer.ID,
Name: form.Name,
Scope: form.GetScope(),
}
exist, err := auth_model.AccessTokenByNameExists(t)

View file

@ -8,11 +8,14 @@ package forms
import (
"mime/multipart"
"net/http"
"reflect"
"strings"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web/middleware"
"gitea.com/go-chi/binding"
@ -403,6 +406,19 @@ func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) bi
return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
}
func (f *NewAccessTokenForm) GetScope() auth_model.AccessTokenScope {
scope := ""
v := reflect.ValueOf(*f)
for i := 0; i < v.NumField(); i++ {
if strings.HasPrefix(v.Type().Field(i).Name, "Scope") && v.Field(i).Bool() {
singleScope := v.Type().Field(i).Name[5:]
scope += util.ToSnakeCase(singleScope) + ","
}
}
scope = strings.TrimSuffix(scope, ",")
return auth_model.AccessTokenScope(scope)
}
// EditOAuth2ApplicationForm form for editing oauth2 applications
type EditOAuth2ApplicationForm struct {
Name string `binding:"Required;MaxSize(255)" form:"application_name"`

View file

@ -5,8 +5,10 @@
package forms
import (
"strconv"
"testing"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert"
@ -84,3 +86,25 @@ func TestRegisterForm_IsDomainAllowed_BlocklistedEmail(t *testing.T) {
assert.Equal(t, v.valid, form.IsEmailDomainAllowed())
}
}
func TestNewAccessTokenForm_GetScope(t *testing.T) {
tests := []struct {
form NewAccessTokenForm
scope auth_model.AccessTokenScope
}{
{
form: NewAccessTokenForm{Name: "test", ScopeRepo: true},
scope: "repo",
},
{
form: NewAccessTokenForm{Name: "test", ScopeRepo: true, ScopeUser: true},
scope: "repo,user",
},
}
for i, test := range tests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
assert.Equal(t, test.scope, test.form.GetScope())
})
}
}