publickey.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package models
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. )
  8. var (
  9. publicKeyRootPath string
  10. tmplPublicKey = "### autogenerated by gitgos, DO NOT EDIT\n" +
  11. "command=\"gitosis-serve %s\",no-port-forwarding," +
  12. "no-X11-forwarding,no-agent-forwarding,no-pty %s"
  13. )
  14. type PublicKey struct {
  15. Id int64
  16. OwnerId int64 `xorm:"index"`
  17. Name string `xorm:"unique not null"`
  18. Content string `xorm:"text not null"`
  19. Created time.Time `xorm:"created"`
  20. Updated time.Time `xorm:"updated"`
  21. }
  22. func GenAuthorizedKey(user, key string) string {
  23. return fmt.Sprintf(tmplPublicKey, user, key)
  24. }
  25. func AddPublicKey(key *PublicKey, user string) error {
  26. _, err := orm.Insert(key)
  27. if err != nil {
  28. return err
  29. }
  30. err = SaveAuthorizedKeyFile(user, key.Content)
  31. if err != nil {
  32. _, err2 := orm.Delete(key)
  33. if err2 != nil {
  34. // TODO: logo the error
  35. }
  36. return err
  37. }
  38. return nil
  39. }
  40. func SaveAuthorizedKeyFile(user, key string) error {
  41. f, err := os.Create(filepath.Join(publicKeyRootPath, user+".pub"))
  42. if err != nil {
  43. return err
  44. }
  45. _, err = f.WriteString(GenAuthorizedKey(user, key))
  46. return err
  47. }