CSI-ES-2324/Projs/PD2/internal/gateway/datastore.go
afonso 69559f41ca
[PD2] Gateway login, logout and auth middleware done.
Co-authored-by: tsousa111 <tiagao2001@hotmail.com>
2024-05-30 00:55:59 +01:00

52 lines
1 KiB
Go

package gateway
import(
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
type DataStore struct {
db *sql.DB
}
func OpenDB() (DataStore, error) {
db, err := sql.Open("sqlite3", "gateway.db")
if err != nil {
return DataStore{}, err
}
ds := DataStore{db: db}
err = ds.CreateTables()
if err != nil {
return DataStore{}, err
}
return ds, nil
}
func (ds DataStore) CreateTables() error {
// Create users table
_, err := ds.db.Exec(`CREATE TABLE IF NOT EXISTS users (
UID TEXT PRIMARY KEY,
password BLOB
)`)
if err != nil {
return err
}
return nil
}
func (ds DataStore) GetPassword(uid string) ([]byte, error) {
var password []byte
err := ds.db.QueryRow("SELECT password FROM users WHERE UID = ?", uid).Scan(&password)
if err != nil {
return nil, err
}
return password, nil
}
func (ds DataStore) InsertUser(uid string, password []byte) error {
_, err := ds.db.Exec("INSERT INTO users (UID, password) VALUES (?, ?)", uid, password)
if err != nil {
return err
}
return nil
}