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.
gitea/models/publickey.go

78 lines
1.5 KiB

package models
import (
"fmt"
"os"
11 years ago
"os/exec"
"path/filepath"
"time"
)
var (
publicKeyRootPath string
11 years ago
sshPath string = "/Users/lunny/.ssh"
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)
}
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"`
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)
}
func AddPublicKey(key *PublicKey, user string) 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")
f, err := os.Create(p)
if err != nil {
return err
}
11 years ago
os.Chmod(p, 0600)
_, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
return err
}