Add generate fingerprint of ssh key

This commit is contained in:
Unknown 2014-03-16 06:16:03 -04:00
parent c83657307e
commit ca956d5cec
2 changed files with 34 additions and 14 deletions

View file

@ -11,6 +11,7 @@ import (
"io" "io"
"os" "os"
"os/exec" "os/exec"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
"sync" "sync"
@ -57,29 +58,48 @@ func init() {
} }
type PublicKey struct { type PublicKey struct {
Id int64 Id int64
OwnerId int64 `xorm:"index"` OwnerId int64 `xorm:"index"`
Name string `xorm:"unique not null"` Name string `xorm:"unique not null"`
Content string `xorm:"text not null"` Fingerprint string
Created time.Time `xorm:"created"` Content string `xorm:"text not null"`
Updated time.Time `xorm:"updated"` Created time.Time `xorm:"created"`
Updated time.Time `xorm:"updated"`
} }
func GenAuthorizedKey(keyId int64, key string) string { func GenAuthorizedKey(keyId int64, key string) string {
return fmt.Sprintf(tmplPublicKey, appPath, keyId, key) return fmt.Sprintf(tmplPublicKey, appPath, keyId, key)
} }
func AddPublicKey(key *PublicKey) error { func AddPublicKey(key *PublicKey) (err error) {
_, err := orm.Insert(key) // Calculate fingerprint.
tmpPath := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
"id_rsa.pub")
os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
f, err := os.Create(tmpPath)
if err != nil { if err != nil {
return
}
if _, err = f.WriteString(key.Content); err != nil {
return err
}
f.Close()
stdout, _, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
if err != nil {
return err
} else if len(stdout) < 2 {
return errors.New("Not enough output for calculating fingerprint")
}
key.Fingerprint = strings.Split(stdout, " ")[1]
// Save SSH key.
if _, err = orm.Insert(key); err != nil {
return err return err
} }
err = SaveAuthorizedKeyFile(key) if err = SaveAuthorizedKeyFile(key); err != nil {
if err != nil { if _, err2 := orm.Delete(key); err2 != nil {
_, err2 := orm.Delete(key) return err2
if err2 != nil {
// TODO: log the error
} }
return err return err
} }

View file

@ -21,7 +21,7 @@
<li class="list-group-item"><span class="name">SSH Key's name</span></li>{{range .Keys}} <li class="list-group-item"><span class="name">SSH Key's name</span></li>{{range .Keys}}
<li class="list-group-item"> <li class="list-group-item">
<span class="name">{{.Name}}</span> <span class="name">{{.Name}}</span>
<span class="print">(print code)</span> <span class="print">({{.Fingerprint}})</span>
<a href="#" class="btn btn-link btn-danger right delete" rel="{{.Id}}" data-del="{{.Id}}">Delete</a> <a href="#" class="btn btn-link btn-danger right delete" rel="{{.Id}}" data-del="{{.Id}}">Delete</a>
</li>{{end}} </li>{{end}}
<li class="list-group-item"> <li class="list-group-item">