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/ssh.go (70 lines, 1.2 KiB) -rw-r--r-- blame download

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

package goit

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/Jamozed/Goit/src/util"
	"golang.org/x/crypto/ssh"
)

func UpdateAuthorizedKeys() error {
	if !Conf.EnableSSH {
		return nil
	}

	log.Println("Updating SSH authorized keys file")

	if err := os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".ssh"), 0700); err != nil {
		return err
	}

	f, err := os.Create(filepath.Join(os.Getenv("HOME"), ".ssh", "authorized_keys"))
	if err != nil {
		return err
	}
	defer f.Close()

	f.WriteString("# This file is managed by Goit; edits will be overwritten.\n")

	/* Write each users SSH keys to the SSH authorized keys file. */
	users, err := GetUsers()
	if err != nil {
		return err
	}

	for _, u := range users {
		keys, err := GetKeys(u.Id)
		if err != nil {
			util.PrintFuncError(err)
			continue
		}

		for _, k := range keys {
			if k.Type != SSH_Auth {
				continue
			}

			ks, err := ssh.ParsePublicKey(k.Key)
			if err != nil {
				util.PrintFuncError(err)
				continue
			}

			if _, err := f.WriteString(
				fmt.Sprintf("command=\"goit-shell %s\" %s", u.Name, string(ssh.MarshalAuthorizedKey(ks))),
			); err != nil {
				util.PrintFuncError(err)
				continue
			}
		}
	}

	return nil
}