github.com/grafviktor/keep-my-secret@v0.9.10-0.20230908165355-19f35cce90e5/internal/keycache/data_key_cache.go (about)

     1  // Package keycache contains an in-memory key-value database definition for storing user encryption keys
     2  package keycache
     3  
     4  import (
     5  	"log"
     6  	"sync"
     7  
     8  	"github.com/grafviktor/keep-my-secret/internal/constant"
     9  )
    10  
    11  var (
    12  	singleton *dataKeyCache
    13  	once      sync.Once
    14  )
    15  
    16  type dataKeyCache struct {
    17  	keymap map[string]string
    18  }
    19  
    20  // GetInstance - creates new cache storage for user data encryption keys.
    21  // This is in-memory key-value storage
    22  func GetInstance() *dataKeyCache {
    23  	once.Do(
    24  		func() {
    25  			singleton = &dataKeyCache{
    26  				keymap: make(map[string]string),
    27  			}
    28  		})
    29  
    30  	return singleton
    31  }
    32  
    33  // Set - sets encryption key for a login name
    34  func (u *dataKeyCache) Set(login, key string) {
    35  	log.Printf("Set data key for user %s\n", login)
    36  
    37  	u.keymap[login] = key
    38  }
    39  
    40  // Get - gets encryption key for a login name from the storage
    41  func (u *dataKeyCache) Get(login string) (string, error) {
    42  	key, ok := u.keymap[login]
    43  
    44  	if !ok {
    45  		log.Printf("Data key not found for user %s\n", login)
    46  
    47  		return "", constant.ErrNotFound
    48  	}
    49  
    50  	return key, nil
    51  }