1
1
mirror of https://github.com/go-gitea/gitea synced 2024-12-23 00:54:28 +00:00

add publickey

This commit is contained in:
Lunny Xiao 2014-02-25 16:13:47 +08:00
parent bbf5345004
commit d42c194aad

View File

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