github.com/wostzone/hub/auth@v0.0.0-20220118060317-7bb375743b17/pkg/configstore/ConfigStore.go (about)

     1  package configstore
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/sirupsen/logrus"
     6  	"io/ioutil"
     7  	"os"
     8  	"path"
     9  )
    10  
    11  // ConfigStore storage for user configuration snippets
    12  type ConfigStore struct {
    13  	// folder containing the configuration files per user
    14  	storeFolder string
    15  }
    16  
    17  // Close the store
    18  func (cfgStore *ConfigStore) Close() {
    19  	logrus.Infof("ConfigStore.Close")
    20  }
    21  
    22  // Get user application config from the store
    23  // Returns a string with configuration text or an empty string if the store doesn't exist
    24  func (cfgStore *ConfigStore) Get(userID, appID string) string {
    25  	logrus.Infof("ConfigStore.Get userID='%s', appID='%s'", userID, appID)
    26  	cfgFileName := fmt.Sprintf("%s.%s.cfg", userID, appID)
    27  	cfgFilePath := path.Join(cfgStore.storeFolder, cfgFileName)
    28  	configText, err := ioutil.ReadFile(cfgFilePath)
    29  	if err != nil {
    30  		logrus.Infof("ConfigStore.Get: %s", err)
    31  		return ""
    32  	}
    33  	return string(configText)
    34  }
    35  
    36  // Put user application configuration into the store.
    37  // This writes the configText to a file <userID>.<appID>.cfg in the store folder
    38  //
    39  //  userID is the ID of the user whose store to update
    40  //  appID is the configuration application ID
    41  //  configText is the configuration in text format
    42  func (cfgStore *ConfigStore) Put(userID, appID string, configText string) error {
    43  	logrus.Infof("ConfigStore.Put")
    44  	cfgFileName := fmt.Sprintf("%s.%s.cfg", userID, appID)
    45  	cfgFilePath := path.Join(cfgStore.storeFolder, cfgFileName)
    46  	err := ioutil.WriteFile(cfgFilePath, []byte(configText), 0600)
    47  	return err
    48  }
    49  
    50  // Open the store
    51  // Create the folder if it doesn't exist
    52  func (cfgStore *ConfigStore) Open() error {
    53  	var err error
    54  	// Right now open doesn't do much, except creating the folder if needed.
    55  	// Future improvements might use a sqlite or other database type solution
    56  	logrus.Infof("ConfigStore.Open. location='%s'", cfgStore.storeFolder)
    57  	if _, err := os.Stat(cfgStore.storeFolder); err != nil {
    58  		err = os.MkdirAll(cfgStore.storeFolder, 0755)
    59  	}
    60  	if err != nil {
    61  		return err
    62  	}
    63  	return err
    64  }
    65  
    66  func NewConfigStore(storeFolder string) *ConfigStore {
    67  	cfgFolder := &ConfigStore{storeFolder: storeFolder}
    68  	return cfgFolder
    69  }