Brijesh's Git Server — whodis @ 9855dd11af38dc3c6f883757b5d07e963c3dc2e2

built this as a refresher on handling webauthn

core/internal/database/database.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
package database

import (
	"context"
	"core/internal/models"
	"database/sql"
	"log"
	"os"

	"github.com/go-webauthn/webauthn/webauthn"
	_ "github.com/joho/godotenv/autoload"
	_ "github.com/mattn/go-sqlite3"
)

type Service interface {
	Close() error
	CreateTables(ctx context.Context) error

	// User-related methods
	GetUserByID(ctx context.Context, id string) (*models.User, error)
	GetUserByName(ctx context.Context, name string) (*models.User, error)
	SaveUser(ctx context.Context, user *models.User) error

	// Credential-related methods
	SaveCredential(ctx context.Context, credential *models.Credential) error
	GetCredentialsForUser(ctx context.Context, userID string) ([]webauthn.Credential, error)
	UpdateCredentialSignCount(ctx context.Context, credentialID []byte, signCount uint32) error
}

type service struct {
	db *sql.DB
}

var (
	dburl      = os.Getenv("BLUEPRINT_DB_URL")
	dbInstance *service
)

func New() Service {
	if dbInstance != nil {
		return dbInstance
	}

	db, err := sql.Open("sqlite3", dburl)
	if err != nil {
		log.Fatal(err)
	}

	dbInstance = &service{
		db: db,
	}
	return dbInstance
}

func (s *service) Close() error {
	log.Printf("Disconnected from database: %s", dburl)
	return s.db.Close()
}