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.

70 lines
1.7 KiB

  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package private
  5. import (
  6. "crypto/tls"
  7. "encoding/json"
  8. "fmt"
  9. "net"
  10. "net/http"
  11. "code.gitea.io/gitea/modules/httplib"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. )
  15. func newRequest(url, method string) *httplib.Request {
  16. return httplib.NewRequest(url, method).Header("Authorization",
  17. fmt.Sprintf("Bearer %s", setting.InternalToken))
  18. }
  19. // Response internal request response
  20. type Response struct {
  21. Err string `json:"err"`
  22. }
  23. func decodeJSONError(resp *http.Response) *Response {
  24. var res Response
  25. err := json.NewDecoder(resp.Body).Decode(&res)
  26. if err != nil {
  27. res.Err = err.Error()
  28. }
  29. return &res
  30. }
  31. func newInternalRequest(url, method string) *httplib.Request {
  32. req := newRequest(url, method).SetTLSClientConfig(&tls.Config{
  33. InsecureSkipVerify: true,
  34. })
  35. if setting.Protocol == setting.UnixSocket {
  36. req.SetTransport(&http.Transport{
  37. Dial: func(_, _ string) (net.Conn, error) {
  38. return net.Dial("unix", setting.HTTPAddr)
  39. },
  40. })
  41. }
  42. return req
  43. }
  44. // UpdatePublicKeyUpdated update publick key updates
  45. func UpdatePublicKeyUpdated(keyID int64) error {
  46. // Ask for running deliver hook and test pull request tasks.
  47. reqURL := setting.LocalURL + fmt.Sprintf("api/internal/ssh/%d/update", keyID)
  48. log.GitLogger.Trace("UpdatePublicKeyUpdated: %s", reqURL)
  49. resp, err := newInternalRequest(reqURL, "POST").Response()
  50. if err != nil {
  51. return err
  52. }
  53. defer resp.Body.Close()
  54. // All 2XX status codes are accepted and others will return an error
  55. if resp.StatusCode/100 != 2 {
  56. return fmt.Errorf("Failed to update public key: %s", decodeJSONError(resp).Err)
  57. }
  58. return nil
  59. }