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

89 lines
1.6 KiB

package models
import (
"fmt"
"os"
11 years ago
"os/exec"
11 years ago
"os/user"
"path/filepath"
"time"
)
var (
11 years ago
//publicKeyRootPath string
sshPath string
appPath string
tmplPublicKey = "### autogenerated by gitgos, DO NOT EDIT\n" +
11 years ago
"command=\"%s serv key-%d\",no-port-forwarding," +
"no-X11-forwarding,no-agent-forwarding,no-pty %s\n"
)
11 years ago
func exePath() (string, error) {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return "", err
}
return filepath.Abs(file)
}
11 years ago
func homeDir() string {
user, err := user.Current()
if err != nil {
return "/"
}
return user.HomeDir
}
11 years ago
func init() {
var err error
appPath, err = exePath()
if err != nil {
println(err.Error())
os.Exit(2)
}
11 years ago
sshPath = filepath.Join(homeDir(), ".ssh")
11 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"`
}
11 years ago
func GenAuthorizedKey(keyId int64, key string) string {
return fmt.Sprintf(tmplPublicKey, appPath, keyId, key)
}
11 years ago
func AddPublicKey(key *PublicKey) error {
_, err := orm.Insert(key)
if err != nil {
return err
}
11 years ago
err = SaveAuthorizedKeyFile(key)
if err != nil {
_, err2 := orm.Delete(key)
if err2 != nil {
// TODO: logo the error
}
return err
}
return nil
}
11 years ago
func SaveAuthorizedKeyFile(key *PublicKey) error {
p := filepath.Join(sshPath, "authorized_keys")
11 years ago
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return err
}
11 years ago
//os.Chmod(p, 0600)
11 years ago
_, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
return err
}