Skip to content

Commit

Permalink
added docs
Browse files Browse the repository at this point in the history
  • Loading branch information
wasilak committed May 22, 2023
1 parent bd87e05 commit 7ef4515
Show file tree
Hide file tree
Showing 11 changed files with 259 additions and 22 deletions.
25 changes: 25 additions & 0 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@ import (
"github.com/spf13/viper"
)

// The CacheInterface defines methods for initializing, getting, setting, and extending the
// time-to-live (TTL) of cached items.
// @property Init - Init is a method that initializes the cache with a specified cache duration. It
// takes a time.Duration parameter that represents the duration for which the cache items should be
// stored.
// @property Get - Get is a method of the CacheInterface that takes a cacheKey string as input and
// returns an interface{} and a bool. The interface{} represents the cached item associated with the
// cacheKey, and the bool indicates whether the item was found in the cache or not.
// @property Set - Set is a method of the CacheInterface that allows you to store an item in the cache
// with a given cacheKey. The item can be of any type that implements the empty interface {}.
// @property GetItemTTL - GetItemTTL is a method of the CacheInterface that returns the remaining
// time-to-live (TTL) of a cached item identified by its cacheKey. It returns the TTL as a
// time.Duration value and a boolean indicating whether the item exists in the cache or not. The TTL
// represents the time
// @property GetTTL - GetTTL is a method of the CacheInterface that returns the default time-to-live
// (TTL) duration for cached items. This duration specifies how long an item should remain in the cache
// before it is considered stale and needs to be refreshed or removed.
// @property ExtendTTL - ExtendTTL is a method in the CacheInterface that allows you to extend the
// time-to-live (TTL) of a cached item. This means that you can update the expiration time of a cached
// item to keep it in the cache for a longer period of time. This can be useful if you
type CacheInterface interface {
Init(cacheDuration time.Duration)
Get(cacheKey string) (interface{}, bool)
Expand All @@ -16,8 +36,13 @@ type CacheInterface interface {
ExtendTTL(cacheKey string, item interface{})
}

// `var CacheInstance CacheInterface` is declaring a variable named `CacheInstance` of type
// `CacheInterface`. This variable will be used to store an instance of a cache that implements the
// `CacheInterface` methods.
var CacheInstance CacheInterface

// The function initializes a cache instance based on the cache type specified in the configuration
// file.
func CacheInit() {
cacheDuration, err := time.ParseDuration(viper.GetString("cache_expire"))
if err != nil {
Expand Down
42 changes: 42 additions & 0 deletions cache/goCache.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,62 @@ import (
gocache "github.com/patrickmn/go-cache"
)

// The GoCache type represents a cache with a specified time-to-live duration.
// @property Cache - Cache is a property of type `*gocache.Cache` which is a pointer to an instance of
// the GoCache library's Cache struct. This property is used to store and manage cached data in memory.
// @property TTL - TTL stands for Time To Live and it is a duration that specifies the amount of time
// for which an item should be considered valid in the cache before it is evicted. After the TTL
// expires, the item is considered stale and will be removed from the cache on the next access or
// eviction.
type GoCache struct {
Cache *gocache.Cache
TTL time.Duration
}

// `func (c *GoCache) Init(cacheDuration time.Duration)` is a method of the `GoCache` struct that
// initializes the cache with a specified time-to-live duration. It sets the `TTL` property of the
// `GoCache` instance to the `cacheDuration` parameter and creates a new instance of the
// `gocache.Cache` struct with the same `cacheDuration` and `TTL` properties. This method is called
// when creating a new `GoCache` instance to set up the cache for use.
func (c *GoCache) Init(cacheDuration time.Duration) {
c.TTL = cacheDuration
c.Cache = gocache.New(cacheDuration, c.TTL)
}

// `func (c *GoCache) GetTTL() time.Duration {` is a method of the `GoCache` struct that returns the
// time-to-live duration (`TTL`) of the cache instance. It retrieves the `TTL` property of the
// `GoCache` instance and returns it as a `time.Duration` value. This method can be used to check the
// current `TTL` value of the cache instance.
func (c *GoCache) GetTTL() time.Duration {
return c.TTL
}

// `func (c *GoCache) Get(cacheKey string) (interface{}, bool)` is a method of the `GoCache` struct
// that retrieves an item from the cache based on the specified `cacheKey`. It returns two values: the
// cached item (as an `interface{}`) and a boolean value indicating whether the item was found in the
// cache or not. If the item is found in the cache, the boolean value will be `true`, otherwise it will
// be `false`.
func (c *GoCache) Get(cacheKey string) (interface{}, bool) {
return c.Cache.Get(cacheKey)
}

// `func (c *GoCache) Set(cacheKey string, item interface{})` is a method of the `GoCache` struct that
// sets a value in the cache with the specified `cacheKey`. The `item` parameter is the value to be
// cached and the `cacheKey` parameter is the key used to identify the cached item. The method sets the
// value in the cache with the specified `cacheKey` and a time-to-live duration (`TTL`) equal to the
// `TTL` property of the `GoCache` instance. This means that the cached item will be considered valid
// for the duration of the `TTL` and will be automatically evicted from the cache after the `TTL`
// expires.
func (c *GoCache) Set(cacheKey string, item interface{}) {
c.Cache.Set(cacheKey, item, c.TTL)
}

// `func (c *GoCache) GetItemTTL(cacheKey string) (time.Duration, bool)` is a method of the `GoCache`
// struct that retrieves the time-to-live duration (`TTL`) of a cached item identified by the specified
// `cacheKey`. It returns two values: the time-to-live duration of the cached item (as a
// `time.Duration` value) and a boolean value indicating whether the item was found in the cache or
// not. If the item is found in the cache, the boolean value will be `true`, otherwise it will be
// `false`. This method can be used to check the remaining time-to-live of a cached item.
func (c *GoCache) GetItemTTL(cacheKey string) (time.Duration, bool) {
_, expiration, found := c.Cache.GetWithExpiration(cacheKey)

Expand All @@ -37,6 +71,14 @@ func (c *GoCache) GetItemTTL(cacheKey string) (time.Duration, bool) {
return difference, found
}

// `func (c *GoCache) ExtendTTL(cacheKey string, item interface{})` is a method of the `GoCache` struct
// that extends the time-to-live duration (`TTL`) of a cached item identified by the specified
// `cacheKey`. It does this by calling the `Set` method of the `gocache.Cache` struct with the same
// `cacheKey` and `item` parameters, and with a time-to-live duration (`TTL`) equal to the `TTL`
// property of the `GoCache` instance. This means that the cached item will be considered valid for an
// additional duration of the `TTL` and will be automatically evicted from the cache after the extended
// `TTL` expires. This method can be used to refresh the time-to-live of a cached item to prevent it
// from being evicted from the cache prematurely.
func (c *GoCache) ExtendTTL(cacheKey string, item interface{}) {
c.Set(cacheKey, item)
}
57 changes: 54 additions & 3 deletions cache/redisCache.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,27 @@ import (
"time"

"github.com/go-redis/redis/v8"
"github.com/wasilak/elastauth/logger"
"golang.org/x/exp/slog"
)

// The RedisCache type represents a Redis cache with a specified time-to-live, context, address, and
// database.
// @property Cache - Cache is a pointer to a Redis client instance that is used to interact with the
// Redis cache.
// @property TTL - TTL stands for "Time To Live" and refers to the amount of time that a cached item
// will remain in the cache before it is considered expired and needs to be refreshed or removed. In
// the context of the RedisCache struct, it represents the duration of time that cached items will be
// stored in
// @property CTX - CTX is a context.Context object that is used to manage the lifecycle of a RedisCache
// instance. It is used to control the cancellation of operations and to pass values between functions.
// It is a part of the standard library in Go and is used extensively in network programming.
// @property {string} Address - Address is a string property that represents the network address of the
// Redis server. It typically includes the hostname or IP address of the server and the port number on
// which Redis is listening. For example, "localhost:6379" or "redis.example.com:6379".
// @property {int} DB - DB stands for "database" and is an integer value that represents the specific
// database within the Redis instance that the RedisCache struct will be interacting with. Redis allows
// for multiple databases to be created within a single instance, each with its own set of keys and
// values. The DB property allows the RedisCache
type RedisCache struct {
Cache *redis.Client
TTL time.Duration
Expand All @@ -17,6 +34,13 @@ type RedisCache struct {
DB int
}

// `func (c *RedisCache) Init(cacheDuration time.Duration)` is a method of the `RedisCache` struct that
// initializes a new Redis client instance and sets the cache duration (TTL) for the RedisCache
// instance. It takes a `time.Duration` parameter `cacheDuration` which represents the duration of time
// that cached items will be stored in the cache. The method creates a new Redis client instance using
// the `redis.NewClient` function and sets the `Cache` property of the `RedisCache` instance to the new
// client instance. It also sets the `CTX` property to a new `context.Background()` instance. Finally,
// it sets the `TTL` property of the `RedisCache` instance to the `cacheDuration` parameter.
func (c *RedisCache) Init(cacheDuration time.Duration) {
c.Cache = redis.NewClient(&redis.Options{
Addr: c.Address,
Expand All @@ -28,36 +52,63 @@ func (c *RedisCache) Init(cacheDuration time.Duration) {
c.TTL = cacheDuration
}

// `func (c *RedisCache) GetTTL() time.Duration {` is a method of the `RedisCache` struct that returns
// the `TTL` property of the `RedisCache` instance, which represents the duration of time that cached
// items will be stored in the cache before they are considered expired and need to be refreshed or
// removed. The method returns a `time.Duration` value.
func (c *RedisCache) GetTTL() time.Duration {
return c.TTL
}

// `func (c *RedisCache) Get(cacheKey string) (interface{}, bool)` is a method of the `RedisCache`
// struct that retrieves a cached item from the Redis cache using the specified `cacheKey`. It returns
// a tuple containing the cached item as an `interface{}` and a boolean value indicating whether the
// item was successfully retrieved from the cache or not. If the item is not found in the cache or an
// error occurs during retrieval, the method returns an empty `interface{}` and `false`.
func (c *RedisCache) Get(cacheKey string) (interface{}, bool) {
item, err := c.Cache.Get(c.CTX, cacheKey).Result()

if err != nil || len(item) == 0 {
logger.LoggerInstance.Error("Error", slog.Any("message", err))
slog.Error("Error", slog.Any("message", err))
return item, false
}

return item, true
}

// `func (c *RedisCache) Set(cacheKey string, item interface{})` is a method of the `RedisCache` struct
// that sets a value in the Redis cache with the specified `cacheKey`. It takes two parameters:
// `cacheKey`, which is a string representing the key under which the value will be stored in the
// cache, and `item`, which is an interface{} representing the value to be stored. The method uses the
// `Set` function of the Redis client to set the value in the cache with the specified key and TTL
// (time-to-live) duration. If an error occurs during the set operation, it is logged using the
// `slog.Error` function.
func (c *RedisCache) Set(cacheKey string, item interface{}) {
c.Cache.Set(c.CTX, cacheKey, item, c.TTL).Err()
}

// `func (c *RedisCache) GetItemTTL(cacheKey string) (time.Duration, bool)` is a method of the
// `RedisCache` struct that retrieves the time-to-live (TTL) duration of a cached item with the
// specified `cacheKey`. It returns a tuple containing the TTL duration as a `time.Duration` value and
// a boolean value indicating whether the TTL was successfully retrieved from the cache or not. If the
// TTL is not found in the cache or an error occurs during retrieval, the method returns a zero
// `time.Duration` value and `false`.
func (c *RedisCache) GetItemTTL(cacheKey string) (time.Duration, bool) {
item, err := c.Cache.TTL(c.CTX, cacheKey).Result()

if err != nil {
logger.LoggerInstance.Error("Error", slog.Any("message", err))
slog.Error("Error", slog.Any("message", err))
return item, false
}

return item, true
}

// `func (c *RedisCache) ExtendTTL(cacheKey string, item interface{})` is a method of the `RedisCache`
// struct that extends the time-to-live (TTL) duration of a cached item with the specified `cacheKey`.
// It uses the `Expire` function of the Redis client to set the TTL duration of the cached item to the
// value of the `TTL` property of the `RedisCache` instance. This method is useful for refreshing the
// TTL of a cached item to prevent it from expiring prematurely.
func (c *RedisCache) ExtendTTL(cacheKey string, item interface{}) {
c.Cache.Expire(c.CTX, cacheKey, c.TTL)
}
6 changes: 5 additions & 1 deletion libs/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"github.com/wasilak/elastauth/logger"
)

// This function initializes the configuration for an application using flags, environment variables,
// and a YAML configuration file.
func InitConfiguration() error {
flag.Bool("debug", false, "Debug")
flag.Bool("generateKey", false, "Generate valid encryption key for use in app")
Expand Down Expand Up @@ -60,6 +62,8 @@ func InitConfiguration() error {
return nil
}

// The function generates and sets a secret key if one is not provided or generates and prints a secret
// key if the "generateKey" flag is set to true.
func HandleSecretKey() error {
if viper.GetBool("generateKey") {
key, err := GenerateKey()
Expand All @@ -76,7 +80,7 @@ func HandleSecretKey() error {
return err
}
viper.Set("secret_key", key)
logger.LoggerInstance.Info("WARNING: No secret key provided. Setting randomly generated", slog.String("key", key))
slog.Info("WARNING: No secret key provided. Setting randomly generated", slog.String("key", key))
}

return nil
Expand Down
6 changes: 6 additions & 0 deletions libs/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import (
"io"
)

// Encrypt encrypts a string using AES-GCM algorithm with a given key. The key
// should be provided as a hexadecimal string. It returns the encrypted string
// in hexadecimal format.
func Encrypt(stringToEncrypt string, keyString string) (encryptedString string) {

//Since the key is in string, we need to convert decode it to bytes
Expand Down Expand Up @@ -42,6 +45,9 @@ func Encrypt(stringToEncrypt string, keyString string) (encryptedString string)
return fmt.Sprintf("%x", ciphertext)
}

// Decrypt decrypts a previously encrypted string using the same key used to
// encrypt it. It takes in an encrypted string and a key string as parameters
// and returns the decrypted string. The key must be in hexadecimal format.
func Decrypt(encryptedString string, keyString string) (decryptedString string) {

key, _ := hex.DecodeString(keyString)
Expand Down
Loading

0 comments on commit 7ef4515

Please sign in to comment.