You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

publickey.go 1.5 kB

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

No Description