Goit

Simple and lightweight Git web server
git clone https://git.omkov.net/Goit
git clone [email protected]:Goit
Log | Tree | Refs | README | Download

Goit/src/goit/keys.go (85 lines, 1.5 KiB) -rw-r--r-- blame download

0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
// Copyright (C) 2025, Jakob Wakeling
// All rights reserved.

package goit

type Key struct {
	ID          int64   `json:"id"`
	OwnerID     int64   `json:"owner_id"`
	Type        KeyType `json:"type"`
	Description string  `json:"description"`
	Key         []byte  `json:"key"`
}

type KeyType int32

const (
	SSH_Auth KeyType = 0
)

func KeyTypeFromString(s string) KeyType {
	switch s {
	case "ssh-auth":
		return SSH_Auth
	default:
		return -1
	}
}

func (t KeyType) String() string {
	return [...]string{"ssh-auth"}[t]
}

func GetKeys(uid int64) ([]Key, error) {
	keys := []Key{}

	rows, err := db.Query("SELECT id, owner_id, type, description, key FROM keys WHERE owner_id = ?", uid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		k := Key{}
		if err := rows.Scan(&k.ID, &k.OwnerID, &k.Type, &k.Description, &k.Key); err != nil {
			return nil, err
		}

		keys = append(keys, k)
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	return keys, nil
}

/* Input key ID is ignored. */
func AddKey(key Key) error {
	if _, err := db.Exec(
		"INSERT INTO keys (owner_id, type, description, key) VALUES (?, ?, ?, ?)",
		key.OwnerID, key.Type, key.Description, key.Key,
	); err != nil {
		return err
	}

	if err := UpdateAuthorizedKeys(); err != nil {
		return err
	}

	return nil
}

func DelKey(kid int64) error {
	if _, err := db.Exec("DELETE FROM keys WHERE id = ?", kid); err != nil {
		return err
	}

	if err := UpdateAuthorizedKeys(); err != nil {
		return err
	}

	return nil
}