github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/api/auth/blocklist.go (about) 1 package auth 2 3 import ( 4 "context" 5 "fmt" 6 "sync" 7 ) 8 9 var DefaultBlockList BlockList = &InMemoryBlockList{ 10 blocked: map[string]bool{}, 11 } 12 13 // BlockList manages a list of blocked IDs. 14 type BlockList interface { 15 // IsBlocked returns true if the id is blocked 16 IsBlocked(ctx context.Context, id, namespace string) (bool, error) 17 // Add adds an ID to the blocklist 18 Add(ctx context.Context, id, namespace string) error 19 // Remove removes an ID from the blocklist 20 Remove(ctx context.Context, id, namespace string) error 21 // List returns the entire list of blocked IDs 22 List(ctx context.Context) ([]string, error) 23 } 24 25 // InMemoryBlockList is an implementation of BlockList that maintains the list in memory only. 26 type InMemoryBlockList struct { 27 sync.RWMutex 28 blocked map[string]bool 29 } 30 31 func (i *InMemoryBlockList) IsBlocked(ctx context.Context, id, namespace string) (bool, error) { 32 i.RLock() 33 defer i.RUnlock() 34 return i.blocked[fmt.Sprintf("%s:%s", namespace, id)], nil 35 } 36 37 func (i *InMemoryBlockList) Add(ctx context.Context, id, namespace string) error { 38 i.Lock() 39 defer i.Unlock() 40 i.blocked[fmt.Sprintf("%s:%s", namespace, id)] = true 41 return nil 42 } 43 44 func (i *InMemoryBlockList) Remove(ctx context.Context, id, namespace string) error { 45 i.Lock() 46 defer i.Unlock() 47 delete(i.blocked, fmt.Sprintf("%s:%s", namespace, id)) 48 return nil 49 } 50 51 func (i *InMemoryBlockList) List(ctx context.Context) ([]string, error) { 52 i.RLock() 53 defer i.RUnlock() 54 res := make([]string, len(i.blocked)) 55 idx := 0 56 for k, _ := range i.blocked { 57 res[idx] = k 58 idx++ 59 } 60 return res, nil 61 }