Brijesh's Git Server — whodis @ 23552493e95c13cd1e2b0619d8cba081a7bce19b

built this as a refresher on handling webauthn

core/internal/database/user.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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
package database

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

	"github.com/go-webauthn/webauthn/protocol"
	"github.com/go-webauthn/webauthn/webauthn"
	"github.com/google/uuid"
)

// GetUserByID retrieves a user by their ID
func (s *service) GetUserByID(ctx context.Context, id string) (*models.User, error) {
	var user models.User
	err := s.db.QueryRowContext(ctx, `
		SELECT id, name, display_name FROM users WHERE id = ?
	`, id).Scan(&user.ID, &user.Name, &user.DisplayName)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil // User not found
		}
		return nil, err
	}

	// Load user's credentials
	credentials, err := s.GetCredentialsForUser(ctx, user.ID)
	if err != nil {
		return nil, err
	}
	user.Credentials = credentials

	return &user, nil
}

// GetUserByName retrieves a user by their username
func (s *service) GetUserByName(ctx context.Context, name string) (*models.User, error) {
	var user models.User
	err := s.db.QueryRowContext(ctx, `
		SELECT id, name, display_name FROM users WHERE name = ?
	`, name).Scan(&user.ID, &user.Name, &user.DisplayName)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil // User not found
		}
		return nil, err
	}

	// Load user's credentials
	credentials, err := s.GetCredentialsForUser(ctx, user.ID)
	if err != nil {
		return nil, err
	}
	user.Credentials = credentials

	return &user, nil
}

// SaveUser saves a new user to the database
func (s *service) SaveUser(ctx context.Context, user *models.User) error {
	_, err := s.db.ExecContext(ctx, `
		INSERT INTO users (id, name, display_name) VALUES (?, ?, ?)
	`, user.ID, user.Name, user.DisplayName)
	return err
}

// SaveCredential saves a new credential to the database
func (s *service) SaveCredential(ctx context.Context, credential *models.Credential) error {
	// Check if the user has any backup-eligible credentials
	existingCreds, err := s.GetCredentialsForUser(ctx, credential.UserID)
	if err != nil {
		return err
	}

	if len(existingCreds) == 0 {
		credential.BackupEligible = true
	} else {
		credential.BackupEligible = false
	}

	recordID := uuid.New().String()

	// Log the credential being saved
	log.Printf("Saving credential: %+v", credential)

	_, err = s.db.ExecContext(ctx, `
		INSERT INTO credentials (
			id,
			user_id,
			public_key,
			credential_id,
			sign_count,
			aaguid,
			clone_warning,
			attachment,
			backup_eligible,
			backup_state
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	`,
		recordID,
		credential.UserID,
		credential.PublicKey,
		credential.CredentialID,
		credential.SignCount,
		credential.AAGUID,
		credential.CloneWarning,
		string(credential.Attachment),
		credential.BackupEligible,
		credential.BackupState,
	)

	if err != nil {
		log.Printf("Error saving credential: %v", err)
		return err
	}

	log.Printf("Successfully saved credential with ID: %s", recordID)
	return nil
}

// GetCredentialsForUser retrieves all credentials for a given user
func (s *service) GetCredentialsForUser(ctx context.Context, userID string) ([]webauthn.Credential, error) {
	rows, err := s.db.QueryContext(ctx, `
		SELECT
			credential_id,
			public_key,
			sign_count,
			aaguid,
			clone_warning,
			attachment,
			backup_eligible,
			backup_state
		FROM credentials
		WHERE user_id = ?
	`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var credentials []webauthn.Credential
	for rows.Next() {
		var cred models.Credential
		var attachmentStr string
		err := rows.Scan(
			&cred.CredentialID,
			&cred.PublicKey,
			&cred.SignCount,
			&cred.AAGUID,
			&cred.CloneWarning,
			&attachmentStr,
			&cred.BackupEligible,
			&cred.BackupState,
		)
		if err != nil {
			return nil, err
		}
		cred.UserID = userID
		cred.Attachment = protocol.AuthenticatorAttachment(attachmentStr)

		// Log the credential details for debugging
		log.Printf("Retrieved credential from DB: %+v", cred)

		wanCred := cred.ToWebauthnCredential()
		log.Printf("Converted to WebAuthn credential: %+v", wanCred)

		credentials = append(credentials, wanCred)
	}
	return credentials, rows.Err()
}

// UpdateCredentialSignCount updates the signCount for a given credential
func (s *service) UpdateCredentialSignCount(ctx context.Context, credentialID []byte, signCount uint32) error {
	_, err := s.db.ExecContext(ctx, `
		UPDATE credentials
		SET sign_count = ?
		WHERE credential_id = ?
	`, signCount, credentialID)
	return err
}