Commit 081632b8 authored by Kevin Lyda's avatar Kevin Lyda
Browse files

Clean up keys on USER DEL

Delete the user's keys when deleting a user.  Closes #20.
parent 75e7f8c2
Loading
Loading
Loading
Loading
+17 −0
Original line number Diff line number Diff line
@@ -197,6 +197,23 @@ func DeleteDB(q *storage.Queries, fingerprint, public string) error {
	return q.DeleteSSHKey(ctx, fingerprint)
}

// DeleteAllForLoginDB removes all SSH keys for a user from both the
// authorized_keys file and the database.
func DeleteAllForLoginDB(q *storage.Queries, login string) error {
	ctx := storage.Context()
	keys, err := q.ListSSHKeysByLogin(ctx, login)
	if err != nil {
		return err
	}
	for _, k := range keys {
		publine := fmt.Sprintf("%s %s", k.KeyType, k.Pubkey)
		if err := deleteFromFile(publine); err != nil {
			return fmt.Errorf("failed to remove key from authorized_keys: %w", err)
		}
	}
	return q.DeleteSSHKeysByLogin(ctx, login)
}

// FetchDB fetches keys from a forge and adds them to both file and DB.
func FetchDB(q *storage.Queries, login, nickname, username string) string {
	sites := map[string]string{
+4 −0
Original line number Diff line number Diff line
@@ -90,6 +90,10 @@ func ActionUserDelete(cmd *dclish.Command) error {
		fmt.Println("ERROR: SYSTEM user can't be deleted.")
		return nil
	}
	if err := key.DeleteAllForLoginDB(this.Q, u.Login); err != nil {
		fmt.Printf("ERROR: Failed to delete user's SSH keys (%s).\n", err)
		return nil
	}
	ctx := storage.Context()
	err = this.Q.DeleteUser(ctx, u.Login)
	if err != nil {
+4 −0
Original line number Diff line number Diff line
@@ -15,6 +15,10 @@ SELECT * FROM ssh_keys WHERE login = ?;
-- name: DeleteSSHKey :exec
DELETE FROM ssh_keys WHERE fingerprint = ?;

-- DeleteSSHKeysByLogin removes all SSH keys for a given user.
-- name: DeleteSSHKeysByLogin :exec
DELETE FROM ssh_keys WHERE login = ?;

-- UpdateSSHKeyLastUsed updates the last_used_at timestamp for a key.
-- name: UpdateSSHKeyLastUsed :exec
UPDATE ssh_keys SET last_used_at = CURRENT_TIMESTAMP WHERE fingerprint = ?;
+12 −0
Original line number Diff line number Diff line
@@ -49,6 +49,18 @@ func (q *Queries) DeleteSSHKey(ctx context.Context, fingerprint string) error {
	return err
}

const deleteSSHKeysByLogin = `-- name: DeleteSSHKeysByLogin :exec
DELETE FROM ssh_keys WHERE login = ?
`

// DeleteSSHKeysByLogin removes all SSH keys for a given user.
//
//	DELETE FROM ssh_keys WHERE login = ?
func (q *Queries) DeleteSSHKeysByLogin(ctx context.Context, login string) error {
	_, err := q.db.ExecContext(ctx, deleteSSHKeysByLogin, login)
	return err
}

const getSSHKeyByFingerprint = `-- name: GetSSHKeyByFingerprint :one
SELECT fingerprint, login, key_type, pubkey, comment, last_used_at, create_at FROM ssh_keys WHERE fingerprint = ?
`