2019-12-16 23:22:09 +08:00
|
|
|
// Copyright (c) Mainflux
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package mocks
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
|
|
|
|
2020-12-30 06:02:35 +08:00
|
|
|
"github.com/mainflux/mainflux/auth"
|
2022-01-28 00:03:57 +08:00
|
|
|
"github.com/mainflux/mainflux/pkg/errors"
|
2019-12-16 23:22:09 +08:00
|
|
|
)
|
|
|
|
|
2020-12-30 06:02:35 +08:00
|
|
|
var _ auth.KeyRepository = (*keyRepositoryMock)(nil)
|
2019-12-16 23:22:09 +08:00
|
|
|
|
|
|
|
type keyRepositoryMock struct {
|
|
|
|
mu sync.Mutex
|
2020-12-30 06:02:35 +08:00
|
|
|
keys map[string]auth.Key
|
2019-12-16 23:22:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewKeyRepository creates in-memory user repository
|
2020-12-30 06:02:35 +08:00
|
|
|
func NewKeyRepository() auth.KeyRepository {
|
2019-12-16 23:22:09 +08:00
|
|
|
return &keyRepositoryMock{
|
2020-12-30 06:02:35 +08:00
|
|
|
keys: make(map[string]auth.Key),
|
2019-12-16 23:22:09 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-30 06:02:35 +08:00
|
|
|
func (krm *keyRepositoryMock) Save(ctx context.Context, key auth.Key) (string, error) {
|
2019-12-16 23:22:09 +08:00
|
|
|
krm.mu.Lock()
|
|
|
|
defer krm.mu.Unlock()
|
|
|
|
|
|
|
|
if _, ok := krm.keys[key.ID]; ok {
|
2022-01-28 00:03:57 +08:00
|
|
|
return "", errors.ErrConflict
|
2019-12-16 23:22:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
krm.keys[key.ID] = key
|
|
|
|
return key.ID, nil
|
|
|
|
}
|
2020-12-30 06:02:35 +08:00
|
|
|
func (krm *keyRepositoryMock) Retrieve(ctx context.Context, issuerID, id string) (auth.Key, error) {
|
2019-12-16 23:22:09 +08:00
|
|
|
krm.mu.Lock()
|
|
|
|
defer krm.mu.Unlock()
|
|
|
|
|
2020-10-28 02:42:53 +08:00
|
|
|
if key, ok := krm.keys[id]; ok && key.IssuerID == issuerID {
|
2019-12-16 23:22:09 +08:00
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
|
2022-01-28 00:03:57 +08:00
|
|
|
return auth.Key{}, errors.ErrNotFound
|
2019-12-16 23:22:09 +08:00
|
|
|
}
|
2020-10-28 02:42:53 +08:00
|
|
|
func (krm *keyRepositoryMock) Remove(ctx context.Context, issuerID, id string) error {
|
2019-12-16 23:22:09 +08:00
|
|
|
krm.mu.Lock()
|
|
|
|
defer krm.mu.Unlock()
|
2020-10-28 02:42:53 +08:00
|
|
|
if key, ok := krm.keys[id]; ok && key.IssuerID == issuerID {
|
2019-12-16 23:22:09 +08:00
|
|
|
delete(krm.keys, id)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|