scopes

Paddy 2015-12-05 Child:b93938562a17

0:b2ab1ab8f157 Go to Latest

scopes/memstore.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 "sort"
5 "sync"
7 "golang.org/x/net/context"
8 )
10 type Memstore struct {
11 scopes map[string]Scope
12 lock sync.RWMutex
13 }
15 func (m *Memstore) CreateScopes(scopes []Scope, ctx context.Context) error {
16 m.lock.Lock()
17 defer m.lock.Unlock()
19 for _, scope := range scopes {
20 if _, ok := m.scopes[scope.ID]; ok {
21 return ErrScopeAlreadyExists(scope.ID)
22 }
23 }
24 for _, scope := range scopes {
25 m.scopes[scope.ID] = scope
26 }
27 return nil
28 }
30 func (m *Memstore) GetScopes(ids []string, ctx context.Context) (map[string]Scope, error) {
31 m.lock.RLock()
32 defer m.lock.RUnlock()
34 scopes := map[string]Scope{}
35 for _, id := range ids {
36 scope, ok := m.scopes[id]
37 if !ok {
38 continue
39 }
40 scopes[id] = scope
41 }
42 return scopes, nil
43 }
45 func (m *Memstore) UpdateScope(change ScopeChange, ctx context.Context) error {
46 m.lock.Lock()
47 defer m.lock.Unlock()
49 scope, ok := m.scopes[change.ScopeID]
50 if !ok {
51 return ErrScopeNotFound
52 }
53 scope = ApplyChange(change, scope)
54 m.scopes[change.ScopeID] = scope
55 return nil
56 }
58 func (m *Memstore) RemoveScopes(ids []string, ctx context.Context) error {
59 m.lock.Lock()
60 defer m.lock.Unlock()
62 for _, id := range ids {
63 delete(m.scopes, id)
64 }
65 return nil
66 }
68 func (m *Memstore) ListScopes(ctx context.Context) ([]Scope, error) {
69 m.lock.RLock()
70 defer m.lock.RUnlock()
72 scopes := []Scope{}
73 for _, scope := range m.scopes {
74 scopes = append(scopes, scope)
75 }
76 sorted := Scopes(scopes)
77 sort.Sort(sorted)
78 scopes = sorted
79 return scopes, nil
80 }