2024-01-25 17:58:55 +01:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
2024-02-25 00:29:39 +01:00
|
|
|
"git.gnous.eu/gnouseu/plakken/internal/secret"
|
2024-01-25 17:58:55 +01:00
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DBConfig struct {
|
|
|
|
DB *redis.Client
|
|
|
|
}
|
|
|
|
|
2024-04-10 19:34:36 +02:00
|
|
|
var ctx = context.Background() //nolint:gochecknoglobals
|
2024-01-25 17:58:55 +01:00
|
|
|
|
2024-04-10 19:34:36 +02:00
|
|
|
// InitDB initialise redis connection settings.
|
2024-01-25 17:58:55 +01:00
|
|
|
func InitDB(addr string, user string, password string, db int) *redis.Options {
|
|
|
|
DBConfig := &redis.Options{
|
|
|
|
Addr: addr,
|
|
|
|
Username: user,
|
|
|
|
Password: password,
|
|
|
|
DB: db,
|
|
|
|
}
|
|
|
|
|
|
|
|
return DBConfig
|
|
|
|
}
|
|
|
|
|
2024-04-10 19:34:36 +02:00
|
|
|
// ConnectDB make new database connection.
|
2024-01-25 17:58:55 +01:00
|
|
|
func ConnectDB(dbConfig *redis.Options) *redis.Client {
|
2024-04-10 19:34:36 +02:00
|
|
|
localDB := redis.NewClient(dbConfig)
|
|
|
|
|
|
|
|
return localDB
|
2024-01-25 17:58:55 +01:00
|
|
|
}
|
|
|
|
|
2024-04-10 19:34:36 +02:00
|
|
|
// Ping test connection to Redis database.
|
2024-02-21 14:22:40 +01:00
|
|
|
func Ping(db *redis.Client) error {
|
|
|
|
status := db.Ping(ctx)
|
|
|
|
if status.String() != "ping: PONG" {
|
2024-02-25 00:29:39 +01:00
|
|
|
return &pingError{}
|
2024-02-21 14:22:40 +01:00
|
|
|
}
|
2024-04-10 19:34:36 +02:00
|
|
|
|
2024-02-21 14:22:40 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-01-25 17:58:55 +01:00
|
|
|
func (config DBConfig) InsertPaste(key string, content string, secret string, ttl time.Duration) {
|
|
|
|
type dbSchema struct {
|
|
|
|
content string
|
|
|
|
secret string
|
|
|
|
}
|
|
|
|
|
|
|
|
hash := dbSchema{
|
|
|
|
content: content,
|
|
|
|
secret: secret,
|
|
|
|
}
|
|
|
|
err := config.DB.HSet(ctx, key, "content", hash.content).Err()
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
err = config.DB.HSet(ctx, key, "secret", hash.secret).Err()
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
if ttl > -1 {
|
|
|
|
config.DB.Expire(ctx, key, ttl)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-10 19:34:36 +02:00
|
|
|
func (config DBConfig) URLExist(url string) bool {
|
2024-01-25 17:58:55 +01:00
|
|
|
return config.DB.Exists(ctx, url).Val() == 1
|
|
|
|
}
|
|
|
|
|
2024-02-25 00:29:39 +01:00
|
|
|
func (config DBConfig) VerifySecret(url string, token string) (bool, error) {
|
|
|
|
storedHash := config.DB.HGet(ctx, url, "secret").Val()
|
|
|
|
|
|
|
|
result, err := secret.VerifyPassword(token, storedHash)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
2024-01-25 17:58:55 +01:00
|
|
|
}
|