github.com/lologarithm/mattermost-server@v5.3.2-0.20181002060438-c82a84ed765b+incompatible/app/plugin_key_value_store.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"crypto/sha256"
     8  	"encoding/base64"
     9  	"net/http"
    10  
    11  	"github.com/mattermost/mattermost-server/mlog"
    12  	"github.com/mattermost/mattermost-server/model"
    13  )
    14  
    15  func getKeyHash(key string) string {
    16  	hash := sha256.New()
    17  	hash.Write([]byte(key))
    18  	return base64.StdEncoding.EncodeToString(hash.Sum(nil))
    19  }
    20  
    21  func (a *App) SetPluginKey(pluginId string, key string, value []byte) *model.AppError {
    22  	kv := &model.PluginKeyValue{
    23  		PluginId: pluginId,
    24  		Key:      getKeyHash(key),
    25  		Value:    value,
    26  	}
    27  
    28  	result := <-a.Srv.Store.Plugin().SaveOrUpdate(kv)
    29  
    30  	if result.Err != nil {
    31  		mlog.Error(result.Err.Error())
    32  	}
    33  
    34  	return result.Err
    35  }
    36  
    37  func (a *App) GetPluginKey(pluginId string, key string) ([]byte, *model.AppError) {
    38  	result := <-a.Srv.Store.Plugin().Get(pluginId, getKeyHash(key))
    39  
    40  	if result.Err != nil {
    41  		if result.Err.StatusCode == http.StatusNotFound {
    42  			return nil, nil
    43  		}
    44  		mlog.Error(result.Err.Error())
    45  		return nil, result.Err
    46  	}
    47  
    48  	kv := result.Data.(*model.PluginKeyValue)
    49  
    50  	return kv.Value, nil
    51  }
    52  
    53  func (a *App) DeletePluginKey(pluginId string, key string) *model.AppError {
    54  	result := <-a.Srv.Store.Plugin().Delete(pluginId, getKeyHash(key))
    55  
    56  	if result.Err != nil {
    57  		mlog.Error(result.Err.Error())
    58  	}
    59  
    60  	return result.Err
    61  }