Support 'all' scope

This commit is contained in:
harryzcy 2022-09-06 05:44:15 -04:00
parent b013747a98
commit 794484a4ce
No known key found for this signature in database
GPG key ID: CC2953E050C19686
2 changed files with 19 additions and 5 deletions

View file

@ -13,6 +13,8 @@ import (
type AccessTokenScope string
const (
AccessTokenScopeAll = "all"
AccessTokenScopeRepo = "repo"
AccessTokenScopeRepoStatus = "repo:status"
AccessTokenScopePublicRepo = "public_repo"
@ -65,6 +67,12 @@ var AllAccessTokenScopes = []string{
AccessTokenScopeAdminGPGKey, AccessTokenScopeWriteGPGKey, AccessTokenScopeReadGPGKey,
}
// AccessTokenScopeBitmap represents a bitmap of access token scopes.
type AccessTokenScopeBitmap uint64
// AccessTokenScopeAllBitmap is the bitmap of all access token scopes.
var AccessTokenScopeAllBitmap AccessTokenScopeBitmap = 1<<uint(len(AllAccessTokenScopes)) - 1
// Parse parses the scope string into a bitmap, thus removing possible duplicates.
func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) {
list := strings.Split(string(s), ",")
@ -74,6 +82,9 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) {
if v == "" {
continue
}
if v == AccessTokenScopeAll {
return AccessTokenScopeAllBitmap, nil
}
idx := sliceIndex(AllAccessTokenScopes, v)
if idx < 0 {
@ -94,9 +105,6 @@ func (s AccessTokenScope) Normalize() (AccessTokenScope, error) {
return bitmap.ToScope(), nil
}
// AccessTokenScopeBitmap represents a bitmap of access token scopes.
type AccessTokenScopeBitmap uint64
// ToScope returns a normalized scope string without any duplicates.
func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope {
var scopes []string
@ -144,7 +152,11 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope {
}
}
return AccessTokenScope(strings.Join(scopes, ","))
scope := AccessTokenScope(strings.Join(scopes, ","))
if scope == "repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key" {
return AccessTokenScopeAll
}
return scope
}
func sliceIndex(slice []string, element string) int {

View file

@ -33,7 +33,9 @@ func TestAccessTokenScope_Normalize(t *testing.T) {
{"package,write:package,delete:package", "package", nil},
{"admin:gpg_key", "admin:gpg_key", nil},
{"admin:gpg_key,write:gpg_key", "admin:gpg_key", nil},
{"admin:gpg_key,write:gpg_key,user", "admin:gpg_key,user", nil},
{"admin:gpg_key,write:gpg_key,user", "user,admin:gpg_key", nil},
{"all", "all", nil},
{"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key", "all", nil},
}
for _, test := range tests {