cert.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package certificate
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/api/sites"
  5. "github.com/0xJacky/Nginx-UI/internal/cert"
  6. "github.com/0xJacky/Nginx-UI/internal/cert/dns"
  7. "github.com/0xJacky/Nginx-UI/internal/logger"
  8. "github.com/0xJacky/Nginx-UI/internal/nginx"
  9. "github.com/0xJacky/Nginx-UI/model"
  10. "github.com/gin-gonic/gin"
  11. "github.com/gorilla/websocket"
  12. "github.com/spf13/cast"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. )
  18. const (
  19. Success = "success"
  20. Info = "info"
  21. Error = "error"
  22. )
  23. type IssueCertResponse struct {
  24. Status string `json:"status"`
  25. Message string `json:"message"`
  26. SSLCertificate string `json:"ssl_certificate,omitempty"`
  27. SSLCertificateKey string `json:"ssl_certificate_key,omitempty"`
  28. }
  29. func handleIssueCertLogChan(conn *websocket.Conn, logChan chan string) {
  30. defer func() {
  31. if err := recover(); err != nil {
  32. logger.Error(err)
  33. }
  34. }()
  35. for logString := range logChan {
  36. err := conn.WriteJSON(IssueCertResponse{
  37. Status: Info,
  38. Message: logString,
  39. })
  40. if err != nil {
  41. logger.Error(err)
  42. return
  43. }
  44. }
  45. }
  46. func IssueCert(c *gin.Context) {
  47. var upGrader = websocket.Upgrader{
  48. CheckOrigin: func(r *http.Request) bool {
  49. return true
  50. },
  51. }
  52. // upgrade http to websocket
  53. ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  54. if err != nil {
  55. logger.Error(err)
  56. return
  57. }
  58. defer func(ws *websocket.Conn) {
  59. _ = ws.Close()
  60. }(ws)
  61. // read
  62. buffer := &cert.ConfigPayload{}
  63. err = ws.ReadJSON(buffer)
  64. if err != nil {
  65. logger.Error(err)
  66. return
  67. }
  68. certModel, err := model.FirstOrCreateCert(c.Param("name"))
  69. if err != nil {
  70. logger.Error(err)
  71. return
  72. }
  73. logChan := make(chan string, 1)
  74. errChan := make(chan error, 1)
  75. go cert.IssueCert(buffer, logChan, errChan)
  76. go handleIssueCertLogChan(ws, logChan)
  77. // block, until errChan closes
  78. for err = range errChan {
  79. errLog := &cert.AutoCertErrorLog{}
  80. errLog.SetCertModel(&certModel)
  81. errLog.Exit("issue cert", err)
  82. err = ws.WriteJSON(IssueCertResponse{
  83. Status: Error,
  84. Message: err.Error(),
  85. })
  86. if err != nil {
  87. logger.Error(err)
  88. return
  89. }
  90. return
  91. }
  92. certDirName := strings.Join(buffer.ServerName, "_")
  93. sslCertificatePath := nginx.GetConfPath("ssl", certDirName, "fullchain.cer")
  94. sslCertificateKeyPath := nginx.GetConfPath("ssl", certDirName, "private.key")
  95. err = certModel.Updates(&model.Cert{
  96. Domains: buffer.ServerName,
  97. SSLCertificatePath: sslCertificatePath,
  98. SSLCertificateKeyPath: sslCertificateKeyPath,
  99. })
  100. if err != nil {
  101. logger.Error(err)
  102. err = ws.WriteJSON(IssueCertResponse{
  103. Status: Error,
  104. Message: err.Error(),
  105. })
  106. return
  107. }
  108. certModel.ClearLog()
  109. err = ws.WriteJSON(IssueCertResponse{
  110. Status: Success,
  111. Message: "Issued certificate successfully",
  112. SSLCertificate: sslCertificatePath,
  113. SSLCertificateKey: sslCertificateKeyPath,
  114. })
  115. if err != nil {
  116. logger.Error(err)
  117. return
  118. }
  119. }
  120. func GetCertList(c *gin.Context) {
  121. certList := model.GetCertList(c.Query("name"), c.Query("domain"))
  122. c.JSON(http.StatusOK, gin.H{
  123. "data": certList,
  124. })
  125. }
  126. func getCert(c *gin.Context, certModel *model.Cert) {
  127. type resp struct {
  128. *model.Cert
  129. SSLCertification string `json:"ssl_certification"`
  130. SSLCertificationKey string `json:"ssl_certification_key"`
  131. CertificateInfo *sites.CertificateInfo `json:"certificate_info,omitempty"`
  132. }
  133. var sslCertificationBytes, sslCertificationKeyBytes []byte
  134. var certificateInfo *sites.CertificateInfo
  135. if certModel.SSLCertificatePath != "" {
  136. if _, err := os.Stat(certModel.SSLCertificatePath); err == nil {
  137. sslCertificationBytes, _ = os.ReadFile(certModel.SSLCertificatePath)
  138. }
  139. pubKey, err := cert.GetCertInfo(certModel.SSLCertificatePath)
  140. if err != nil {
  141. api.ErrHandler(c, err)
  142. return
  143. }
  144. certificateInfo = &sites.CertificateInfo{
  145. SubjectName: pubKey.Subject.CommonName,
  146. IssuerName: pubKey.Issuer.CommonName,
  147. NotAfter: pubKey.NotAfter,
  148. NotBefore: pubKey.NotBefore,
  149. }
  150. }
  151. if certModel.SSLCertificateKeyPath != "" {
  152. if _, err := os.Stat(certModel.SSLCertificateKeyPath); err == nil {
  153. sslCertificationKeyBytes, _ = os.ReadFile(certModel.SSLCertificateKeyPath)
  154. }
  155. }
  156. c.JSON(http.StatusOK, resp{
  157. certModel,
  158. string(sslCertificationBytes),
  159. string(sslCertificationKeyBytes),
  160. certificateInfo,
  161. })
  162. }
  163. func GetCert(c *gin.Context) {
  164. certModel, err := model.FirstCertByID(cast.ToInt(c.Param("id")))
  165. if err != nil {
  166. api.ErrHandler(c, err)
  167. return
  168. }
  169. getCert(c, &certModel)
  170. }
  171. func AddCert(c *gin.Context) {
  172. var json struct {
  173. Name string `json:"name"`
  174. SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
  175. SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
  176. SSLCertification string `json:"ssl_certification"`
  177. SSLCertificationKey string `json:"ssl_certification_key"`
  178. }
  179. if !api.BindAndValid(c, &json) {
  180. return
  181. }
  182. certModel := &model.Cert{
  183. Name: json.Name,
  184. SSLCertificatePath: json.SSLCertificatePath,
  185. SSLCertificateKeyPath: json.SSLCertificateKeyPath,
  186. }
  187. err := certModel.Insert()
  188. if err != nil {
  189. api.ErrHandler(c, err)
  190. return
  191. }
  192. err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
  193. if err != nil {
  194. api.ErrHandler(c, err)
  195. return
  196. }
  197. err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
  198. if err != nil {
  199. api.ErrHandler(c, err)
  200. return
  201. }
  202. if json.SSLCertification != "" {
  203. err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644)
  204. if err != nil {
  205. api.ErrHandler(c, err)
  206. return
  207. }
  208. }
  209. if json.SSLCertificationKey != "" {
  210. err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644)
  211. if err != nil {
  212. api.ErrHandler(c, err)
  213. return
  214. }
  215. }
  216. getCert(c, certModel)
  217. }
  218. func ModifyCert(c *gin.Context) {
  219. id := cast.ToInt(c.Param("id"))
  220. var json struct {
  221. Name string `json:"name"`
  222. SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
  223. SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
  224. SSLCertification string `json:"ssl_certification"`
  225. SSLCertificationKey string `json:"ssl_certification_key"`
  226. }
  227. if !api.BindAndValid(c, &json) {
  228. return
  229. }
  230. certModel, err := model.FirstCertByID(id)
  231. if err != nil {
  232. api.ErrHandler(c, err)
  233. return
  234. }
  235. err = certModel.Updates(&model.Cert{
  236. Name: json.Name,
  237. SSLCertificatePath: json.SSLCertificatePath,
  238. SSLCertificateKeyPath: json.SSLCertificateKeyPath,
  239. })
  240. if err != nil {
  241. api.ErrHandler(c, err)
  242. return
  243. }
  244. err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
  245. if err != nil {
  246. api.ErrHandler(c, err)
  247. return
  248. }
  249. err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
  250. if err != nil {
  251. api.ErrHandler(c, err)
  252. return
  253. }
  254. if json.SSLCertification != "" {
  255. err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644)
  256. if err != nil {
  257. api.ErrHandler(c, err)
  258. return
  259. }
  260. }
  261. if json.SSLCertificationKey != "" {
  262. err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644)
  263. if err != nil {
  264. api.ErrHandler(c, err)
  265. return
  266. }
  267. }
  268. GetCert(c)
  269. }
  270. func RemoveCert(c *gin.Context) {
  271. id := cast.ToInt(c.Param("id"))
  272. certModel, err := model.FirstCertByID(id)
  273. if err != nil {
  274. api.ErrHandler(c, err)
  275. return
  276. }
  277. err = certModel.Remove()
  278. if err != nil {
  279. api.ErrHandler(c, err)
  280. return
  281. }
  282. c.JSON(http.StatusNoContent, nil)
  283. }
  284. func GetDNSProvidersList(c *gin.Context) {
  285. c.JSON(http.StatusOK, dns.GetProvidersList())
  286. }
  287. func GetDNSProvider(c *gin.Context) {
  288. code := c.Param("code")
  289. provider, ok := dns.GetProvider(code)
  290. if !ok {
  291. c.JSON(http.StatusNotFound, gin.H{
  292. "message": "provider not found",
  293. })
  294. return
  295. }
  296. c.JSON(http.StatusOK, provider)
  297. }