You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
forgejo/models/publickey.go

90 lines
1.6 KiB
Go

package models
import (
"fmt"
"os"
10 years ago
"os/exec"
"path/filepath"
"time"
10 years ago
"github.com/Unknwon/com"
)
var (
10 years ago
//publicKeyRootPath string
sshPath string
appPath string
tmplPublicKey = "### autogenerated by gitgos, DO NOT EDIT\n" +
10 years ago
"command=\"%s serv key-%d\",no-port-forwarding," +
"no-X11-forwarding,no-agent-forwarding,no-pty %s\n"
)
10 years ago
func exePath() (string, error) {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return "", err
}
return filepath.Abs(file)
}
10 years ago
func homeDir() string {
10 years ago
home, err := com.HomeDir()
10 years ago
if err != nil {
return "/"
}
10 years ago
return home
10 years ago
}
10 years ago
func init() {
var err error
appPath, err = exePath()
if err != nil {
println(err.Error())
os.Exit(2)
}
10 years ago
sshPath = filepath.Join(homeDir(), ".ssh")
10 years ago
}
type PublicKey struct {
Id int64
OwnerId int64 `xorm:"index"`
Name string `xorm:"unique not null"`
Content string `xorm:"text not null"`
Created time.Time `xorm:"created"`
Updated time.Time `xorm:"updated"`
}
10 years ago
func GenAuthorizedKey(keyId int64, key string) string {
return fmt.Sprintf(tmplPublicKey, appPath, keyId, key)
}
10 years ago
func AddPublicKey(key *PublicKey) error {
_, err := orm.Insert(key)
if err != nil {
return err
}
10 years ago
err = SaveAuthorizedKeyFile(key)
if err != nil {
_, err2 := orm.Delete(key)
if err2 != nil {
10 years ago
// TODO: log the error
}
return err
}
return nil
}
10 years ago
func SaveAuthorizedKeyFile(key *PublicKey) error {
p := filepath.Join(sshPath, "authorized_keys")
10 years ago
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return err
}
10 years ago
//os.Chmod(p, 0600)
10 years ago
_, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
return err
}