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.

100 lines
1.9 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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 DeletePublicKey(key *PublicKey) error {
  68. _, err := orm.Delete(key)
  69. return err
  70. }
  71. func ListPublicKey(userId int64) ([]PublicKey, error) {
  72. keys := make([]PublicKey, 0)
  73. err := orm.Find(&keys, &PublicKey{OwnerId: userId})
  74. return keys, err
  75. }
  76. func SaveAuthorizedKeyFile(key *PublicKey) error {
  77. p := filepath.Join(sshPath, "authorized_keys")
  78. f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  79. if err != nil {
  80. return err
  81. }
  82. //os.Chmod(p, 0600)
  83. _, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
  84. return err
  85. }