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.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/memstore.go	Sat Dec 05 14:54:57 2015 -0800
     1.3 @@ -0,0 +1,80 @@
     1.4 +package scopes
     1.5 +
     1.6 +import (
     1.7 +	"sort"
     1.8 +	"sync"
     1.9 +
    1.10 +	"golang.org/x/net/context"
    1.11 +)
    1.12 +
    1.13 +type Memstore struct {
    1.14 +	scopes map[string]Scope
    1.15 +	lock   sync.RWMutex
    1.16 +}
    1.17 +
    1.18 +func (m *Memstore) CreateScopes(scopes []Scope, ctx context.Context) error {
    1.19 +	m.lock.Lock()
    1.20 +	defer m.lock.Unlock()
    1.21 +
    1.22 +	for _, scope := range scopes {
    1.23 +		if _, ok := m.scopes[scope.ID]; ok {
    1.24 +			return ErrScopeAlreadyExists(scope.ID)
    1.25 +		}
    1.26 +	}
    1.27 +	for _, scope := range scopes {
    1.28 +		m.scopes[scope.ID] = scope
    1.29 +	}
    1.30 +	return nil
    1.31 +}
    1.32 +
    1.33 +func (m *Memstore) GetScopes(ids []string, ctx context.Context) (map[string]Scope, error) {
    1.34 +	m.lock.RLock()
    1.35 +	defer m.lock.RUnlock()
    1.36 +
    1.37 +	scopes := map[string]Scope{}
    1.38 +	for _, id := range ids {
    1.39 +		scope, ok := m.scopes[id]
    1.40 +		if !ok {
    1.41 +			continue
    1.42 +		}
    1.43 +		scopes[id] = scope
    1.44 +	}
    1.45 +	return scopes, nil
    1.46 +}
    1.47 +
    1.48 +func (m *Memstore) UpdateScope(change ScopeChange, ctx context.Context) error {
    1.49 +	m.lock.Lock()
    1.50 +	defer m.lock.Unlock()
    1.51 +
    1.52 +	scope, ok := m.scopes[change.ScopeID]
    1.53 +	if !ok {
    1.54 +		return ErrScopeNotFound
    1.55 +	}
    1.56 +	scope = ApplyChange(change, scope)
    1.57 +	m.scopes[change.ScopeID] = scope
    1.58 +	return nil
    1.59 +}
    1.60 +
    1.61 +func (m *Memstore) RemoveScopes(ids []string, ctx context.Context) error {
    1.62 +	m.lock.Lock()
    1.63 +	defer m.lock.Unlock()
    1.64 +
    1.65 +	for _, id := range ids {
    1.66 +		delete(m.scopes, id)
    1.67 +	}
    1.68 +	return nil
    1.69 +}
    1.70 +
    1.71 +func (m *Memstore) ListScopes(ctx context.Context) ([]Scope, error) {
    1.72 +	m.lock.RLock()
    1.73 +	defer m.lock.RUnlock()
    1.74 +
    1.75 +	scopes := []Scope{}
    1.76 +	for _, scope := range m.scopes {
    1.77 +		scopes = append(scopes, scope)
    1.78 +	}
    1.79 +	sorted := Scopes(scopes)
    1.80 +	sort.Sort(sorted)
    1.81 +	scopes = sorted
    1.82 +	return scopes, nil
    1.83 +}