scopes

Paddy 2015-12-05 Child:b93938562a17

0:b2ab1ab8f157 Go to Latest

scopes/scope.go

First pass at a scopes package. We need a minimal scopes package that we'll be able to share around. I don't want it embedded in auth, because then all the requirements of auth have to be pulled into whatever package wants to import type Scope, which seems silly. So this is the bare minimum of the beginning of a new service that separates Scopes out from auth.

History
1 package scopes
3 import (
4 "errors"
5 "fmt"
7 "golang.org/x/net/context"
8 )
10 var (
11 ErrNoStorer = errors.New("Storer not set in Context")
12 ErrScopeNotFound = errors.New("Scope not found")
13 )
15 type ErrScopeAlreadyExists string
17 func (e ErrScopeAlreadyExists) Error() string {
18 return fmt.Sprintf("scope %s already exists", string(e))
19 }
21 // Scope represents a limit on the access that a grant provides.
22 type Scope struct {
23 ID string
24 Name string
25 Description string
26 }
28 func ApplyChange(change ScopeChange, scope Scope) Scope {
29 changed := scope
30 if change.Name != nil {
31 changed.Name = *change.Name
32 }
33 if change.Description != nil {
34 changed.Description = *change.Description
35 }
36 return changed
37 }
39 type Scopes []Scope
41 func (s Scopes) Len() int {
42 return len(s)
43 }
45 func (s Scopes) Swap(i, j int) {
46 s[i], s[j] = s[j], s[i]
47 }
49 func (s Scopes) Less(i, j int) bool {
50 return s[i].ID < s[j].ID
51 }
53 func (s Scopes) Strings() []string {
54 res := make([]string, len(s))
55 for pos, scope := range s {
56 res[pos] = scope.ID
57 }
58 return res
59 }
61 func stringsToScopes(s []string) Scopes {
62 res := make(Scopes, len(s))
63 for pos, scope := range s {
64 res[pos] = Scope{ID: scope}
65 }
66 return res
67 }
69 // ScopeChange represents a change to a Scope.
70 type ScopeChange struct {
71 ScopeID string
72 Name *string
73 Description *string
74 }
76 func (s ScopeChange) Empty() bool {
77 return s.Name == nil && s.Description == nil
78 }
80 type Storer interface {
81 CreateScopes(scopes []Scope, ctx context.Context) error
82 GetScopes(ids []string, ctx context.Context) (map[string]Scope, error)
83 UpdateScope(change ScopeChange, ctx context.Context) error
84 RemoveScopes(ids []string, ctx context.Context) error
85 ListScopes(ctx context.Context) ([]Scope, error)
86 }