github.com/cs3org/reva/v2@v2.27.7/pkg/preferences/memory/memory.go (about)

     1  // Copyright 2018-2021 CERN
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // In applying this license, CERN does not waive the privileges and immunities
    16  // granted to it by virtue of its status as an Intergovernmental Organization
    17  // or submit itself to any jurisdiction.
    18  
    19  package memory
    20  
    21  import (
    22  	"context"
    23  	"sync"
    24  
    25  	ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
    26  	"github.com/cs3org/reva/v2/pkg/errtypes"
    27  	"github.com/cs3org/reva/v2/pkg/preferences"
    28  	"github.com/cs3org/reva/v2/pkg/preferences/registry"
    29  )
    30  
    31  func init() {
    32  	registry.Register("memory", New)
    33  }
    34  
    35  type mgr struct {
    36  	sync.RWMutex
    37  	keys map[string]map[string]string
    38  }
    39  
    40  // New returns an instance of the in-memory preferences manager.
    41  func New(m map[string]interface{}) (preferences.Manager, error) {
    42  	return &mgr{keys: make(map[string]map[string]string)}, nil
    43  }
    44  
    45  func (m *mgr) SetKey(ctx context.Context, key, namespace, value string) error {
    46  	u, ok := ctxpkg.ContextGetUser(ctx)
    47  	if !ok {
    48  		return errtypes.UserRequired("preferences: error getting user from ctx")
    49  	}
    50  	m.Lock()
    51  	defer m.Unlock()
    52  
    53  	userKey := u.Id.OpaqueId
    54  
    55  	if len(m.keys[userKey]) == 0 {
    56  		m.keys[userKey] = map[string]string{key: value}
    57  	} else {
    58  		m.keys[userKey][key] = value
    59  	}
    60  	return nil
    61  }
    62  
    63  func (m *mgr) GetKey(ctx context.Context, key, namespace string) (string, error) {
    64  	u, ok := ctxpkg.ContextGetUser(ctx)
    65  	if !ok {
    66  		return "", errtypes.UserRequired("preferences: error getting user from ctx")
    67  	}
    68  	m.RLock()
    69  	defer m.RUnlock()
    70  
    71  	userKey := u.Id.OpaqueId
    72  
    73  	if len(m.keys[userKey]) != 0 {
    74  		if value, ok := m.keys[userKey][key]; ok {
    75  			return value, nil
    76  		}
    77  	}
    78  	return "", errtypes.NotFound("preferences: key not found")
    79  }