This commit is contained in:
Lunny Xiao 2014-02-25 16:13:47 +08:00
Родитель bbf5345004
Коммит d42c194aad
1 изменённых файлов: 30 добавлений и 8 удалений

Просмотреть файл

@ -3,17 +3,37 @@ package models
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
)
var (
publicKeyRootPath string
sshPath string = "/Users/lunny/.ssh"
appPath string
tmplPublicKey = "### autogenerated by gitgos, DO NOT EDIT\n" +
"command=\"gitosis-serve %s\",no-port-forwarding," +
"no-X11-forwarding,no-agent-forwarding,no-pty %s"
"command=\"%s serv key-%d\",no-port-forwarding," +
"no-X11-forwarding,no-agent-forwarding,no-pty %s\n"
)
func exePath() (string, error) {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return "", err
}
return filepath.Abs(file)
}
func init() {
var err error
appPath, err = exePath()
if err != nil {
println(err.Error())
os.Exit(2)
}
}
type PublicKey struct {
Id int64
OwnerId int64 `xorm:"index"`
@ -23,8 +43,8 @@ type PublicKey struct {
Updated time.Time `xorm:"updated"`
}
func GenAuthorizedKey(user, key string) string {
return fmt.Sprintf(tmplPublicKey, user, key)
func GenAuthorizedKey(keyId int64, key string) string {
return fmt.Sprintf(tmplPublicKey, appPath, keyId, key)
}
func AddPublicKey(key *PublicKey, user string) error {
@ -33,7 +53,7 @@ func AddPublicKey(key *PublicKey, user string) error {
return err
}
err = SaveAuthorizedKeyFile(user, key.Content)
err = SaveAuthorizedKeyFile(key)
if err != nil {
_, err2 := orm.Delete(key)
if err2 != nil {
@ -45,11 +65,13 @@ func AddPublicKey(key *PublicKey, user string) error {
return nil
}
func SaveAuthorizedKeyFile(user, key string) error {
f, err := os.Create(filepath.Join(publicKeyRootPath, user+".pub"))
func SaveAuthorizedKeyFile(key *PublicKey) error {
p := filepath.Join(sshPath, "authorized_keys")
f, err := os.Create(p)
if err != nil {
return err
}
_, err = f.WriteString(GenAuthorizedKey(user, key))
os.Chmod(p, 0600)
_, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
return err
}