59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
type DatabaseHandler struct {
|
|
database *sql.DB
|
|
token []byte
|
|
}
|
|
|
|
func NewDatabaseHandler(file string, create bool) (*DatabaseHandler, error) {
|
|
if create {
|
|
// createOrOpenDB creates or opens a SQLite database at the given path.
|
|
// Create the directory if it doesn't exist
|
|
dir := filepath.Dir(file)
|
|
|
|
err := os.MkdirAll(dir, os.ModePerm)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create directory: %w", err)
|
|
}
|
|
} else {
|
|
if _, err := os.Stat(file); err != nil {
|
|
return nil, fmt.Errorf("%s not found", file)
|
|
}
|
|
}
|
|
|
|
// Open the database (creates it if it doesn't exist)
|
|
db, err := sql.Open("sqlite", file)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to open database: %w", err)
|
|
}
|
|
|
|
// Test the connection
|
|
if err = db.Ping(); err != nil {
|
|
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
|
}
|
|
|
|
return &DatabaseHandler{database: db}, nil
|
|
}
|
|
|
|
func (dh *DatabaseHandler) SetToken(token string) {
|
|
dh.token = []byte(token)
|
|
}
|
|
|
|
func (dh *DatabaseHandler) hashField(field string) string {
|
|
h := hmac.New(sha256.New, dh.token)
|
|
h.Write([]byte(field))
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|