cert.go 8.6 KB

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