generated from resonatecoop/id-server-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
scope.go
88 lines (70 loc) · 1.98 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
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
package oauth
import (
"context"
"errors"
"sort"
"strings"
"github.com/resonatecoop/user-api/model"
"github.com/uptrace/bun"
)
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 {
ctx := context.Background()
// Fetch default scopes
var scopes []string
rows, err := s.db.NewSelect().
Model((*model.Scope)(nil)).
Where("is_default = ?", true).
Rows(ctx)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
scope := new(model.Scope)
if err := s.db.ScanRow(ctx, rows, scope); err != nil {
panic(err)
}
scopes = append(scopes, scope.Name)
}
if err := rows.Err(); err != nil {
panic(err)
}
// s.db.NewSelect().Model(new(model.Scope)).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 {
ctx := context.Background()
// Split the requested scope string
scopes := strings.Split(requestedScope, " ")
var available_scopes []model.Scope
// Count how many of requested scopes exist in the database
count, _ := s.db.NewSelect().
Model(&available_scopes).
Where("name IN (?)", bun.In(scopes)).
ScanAndCount(ctx)
// Return true only if all requested scopes found
return count == len(scopes)
}