Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package models
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "time"
  8. "github.com/Unknwon/com"
  9. )
  10. var (
  11. //publicKeyRootPath string
  12. sshPath string
  13. appPath string
  14. tmplPublicKey = "### autogenerated by gitgos, DO NOT EDIT\n" +
  15. "command=\"%s serv key-%d\",no-port-forwarding," +
  16. "no-X11-forwarding,no-agent-forwarding,no-pty %s\n"
  17. )
  18. func exePath() (string, error) {
  19. file, err := exec.LookPath(os.Args[0])
  20. if err != nil {
  21. return "", err
  22. }
  23. return filepath.Abs(file)
  24. }
  25. func homeDir() string {
  26. home, err := com.HomeDir()
  27. if err != nil {
  28. return "/"
  29. }
  30. return home
  31. }
  32. func init() {
  33. var err error
  34. appPath, err = exePath()
  35. if err != nil {
  36. println(err.Error())
  37. os.Exit(2)
  38. }
  39. sshPath = filepath.Join(homeDir(), ".ssh")
  40. }
  41. type PublicKey struct {
  42. Id int64
  43. OwnerId int64 `xorm:"index"`
  44. Name string `xorm:"unique not null"`
  45. Content string `xorm:"text not null"`
  46. Created time.Time `xorm:"created"`
  47. Updated time.Time `xorm:"updated"`
  48. }
  49. func GenAuthorizedKey(keyId int64, key string) string {
  50. return fmt.Sprintf(tmplPublicKey, appPath, keyId, key)
  51. }
  52. func AddPublicKey(key *PublicKey) error {
  53. _, err := orm.Insert(key)
  54. if err != nil {
  55. return err
  56. }
  57. err = SaveAuthorizedKeyFile(key)
  58. if err != nil {
  59. _, err2 := orm.Delete(key)
  60. if err2 != nil {
  61. // TODO: log the error
  62. }
  63. return err
  64. }
  65. return nil
  66. }
  67. func SaveAuthorizedKeyFile(key *PublicKey) error {
  68. p := filepath.Join(sshPath, "authorized_keys")
  69. f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  70. if err != nil {
  71. return err
  72. }
  73. //os.Chmod(p, 0600)
  74. _, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
  75. return err
  76. }