github.com/RichardKnop/Go-oauth2-server@v1.0.1/oauth/scope.go (about) 1 package oauth 2 3 import ( 4 "errors" 5 "sort" 6 "strings" 7 8 "github.com/RichardKnop/go-oauth2-server/models" 9 ) 10 11 var ( 12 // ErrInvalidScope ... 13 ErrInvalidScope = errors.New("Invalid scope") 14 ) 15 16 // GetScope takes a requested scope and, if it's empty, returns the default 17 // scope, if not empty, it validates the requested scope 18 func (s *Service) GetScope(requestedScope string) (string, error) { 19 // Return the default scope if the requested scope is empty 20 if requestedScope == "" { 21 return s.GetDefaultScope(), nil 22 } 23 24 // If the requested scope exists in the database, return it 25 if s.ScopeExists(requestedScope) { 26 return requestedScope, nil 27 } 28 29 // Otherwise return error 30 return "", ErrInvalidScope 31 } 32 33 // GetDefaultScope returns the default scope 34 func (s *Service) GetDefaultScope() string { 35 // Fetch default scopes 36 var scopes []string 37 s.db.Model(new(models.OauthScope)).Where("is_default = ?", true).Pluck("scope", &scopes) 38 39 // Sort the scopes alphabetically 40 sort.Strings(scopes) 41 42 // Return space delimited scope string 43 return strings.Join(scopes, " ") 44 } 45 46 // ScopeExists checks if a scope exists 47 func (s *Service) ScopeExists(requestedScope string) bool { 48 // Split the requested scope string 49 scopes := strings.Split(requestedScope, " ") 50 51 // Count how many of requested scopes exist in the database 52 var count int 53 s.db.Model(new(models.OauthScope)).Where("scope in (?)", scopes).Count(&count) 54 55 // Return true only if all requested scopes found 56 return count == len(scopes) 57 }