-
Notifications
You must be signed in to change notification settings - Fork 315
/
scope.go
57 lines (45 loc) · 1.45 KB
/
scope.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
package oauth
import (
"errors"
"sort"
"strings"
"github.com/RichardKnop/go-oauth2-server/models"
)
var (
// ErrInvalidScope ...
ErrInvalidScope = errors.New("Invalid scope")
)
// GetScope takes a requested scope and, if it's empty, returns the default
// scope, if not empty, it validates the requested scope
func (s *Service) GetScope(requestedScope string) (string, error) {
// Return the default scope if the requested scope is empty
if requestedScope == "" {
return s.GetDefaultScope(), nil
}
// If the requested scope exists in the database, return it
if s.ScopeExists(requestedScope) {
return requestedScope, nil
}
// Otherwise return error
return "", ErrInvalidScope
}
// GetDefaultScope returns the default scope
func (s *Service) GetDefaultScope() string {
// Fetch default scopes
var scopes []string
s.db.Model(new(models.OauthScope)).Where("is_default = ?", true).Pluck("scope", &scopes)
// Sort the scopes alphabetically
sort.Strings(scopes)
// Return space delimited scope string
return strings.Join(scopes, " ")
}
// ScopeExists checks if a scope exists
func (s *Service) ScopeExists(requestedScope string) bool {
// Split the requested scope string
scopes := strings.Split(requestedScope, " ")
// Count how many of requested scopes exist in the database
var count int
s.db.Model(new(models.OauthScope)).Where("scope in (?)", scopes).Count(&count)
// Return true only if all requested scopes found
return count == len(scopes)
}