cert.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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/cert/dns"
  6. "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
  7. "github.com/gin-gonic/gin"
  8. "github.com/gorilla/websocket"
  9. "github.com/spf13/cast"
  10. "log"
  11. "net/http"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. )
  16. const (
  17. Success = "success"
  18. Info = "info"
  19. Error = "error"
  20. )
  21. type IssueCertResponse struct {
  22. Status string `json:"status"`
  23. Message string `json:"message"`
  24. SSLCertificate string `json:"ssl_certificate,omitempty"`
  25. SSLCertificateKey string `json:"ssl_certificate_key,omitempty"`
  26. }
  27. func handleIssueCertLogChan(conn *websocket.Conn, logChan chan string) {
  28. defer func() {
  29. if err := recover(); err != nil {
  30. log.Println("api.handleIssueCertLogChan recover", err)
  31. }
  32. }()
  33. for logString := range logChan {
  34. err := conn.WriteJSON(IssueCertResponse{
  35. Status: Info,
  36. Message: logString,
  37. })
  38. if err != nil {
  39. log.Println("Error handleIssueCertLogChan", err)
  40. return
  41. }
  42. }
  43. }
  44. func IssueCert(c *gin.Context) {
  45. var upGrader = websocket.Upgrader{
  46. CheckOrigin: func(r *http.Request) bool {
  47. return true
  48. },
  49. }
  50. // upgrade http to websocket
  51. ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  52. if err != nil {
  53. log.Println(err)
  54. return
  55. }
  56. defer func(ws *websocket.Conn) {
  57. err := ws.Close()
  58. if err != nil {
  59. log.Println("defer websocket close err", err)
  60. }
  61. }(ws)
  62. // read
  63. buffer := &cert.ConfigPayload{}
  64. err = ws.ReadJSON(buffer)
  65. if err != nil {
  66. log.Println(err)
  67. return
  68. }
  69. certModel, err := model.FirstOrCreateCert(c.Param("name"))
  70. if err != nil {
  71. log.Println(err)
  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. log.Println("Error WriteJSON", 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. log.Println(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. log.Println(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 *CertificateInfo `json:"certificate_info,omitempty"`
  132. }
  133. var sslCertificationBytes, sslCertificationKeyBytes []byte
  134. var certificateInfo *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. ErrHandler(c, err)
  142. return
  143. }
  144. certificateInfo = &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. 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 !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. ErrHandler(c, err)
  190. return
  191. }
  192. err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
  193. if err != nil {
  194. ErrHandler(c, err)
  195. return
  196. }
  197. err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
  198. if err != nil {
  199. 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. 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. 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. certModel, err := model.FirstCertByID(id)
  221. var json struct {
  222. Name string `json:"name"`
  223. SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
  224. SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
  225. SSLCertification string `json:"ssl_certification"`
  226. SSLCertificationKey string `json:"ssl_certification_key"`
  227. }
  228. if !BindAndValid(c, &json) {
  229. return
  230. }
  231. if err != nil {
  232. 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. ErrHandler(c, err)
  242. return
  243. }
  244. err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
  245. if err != nil {
  246. ErrHandler(c, err)
  247. return
  248. }
  249. err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
  250. if err != nil {
  251. 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. 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. 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. ErrHandler(c, err)
  275. return
  276. }
  277. err = certModel.Remove()
  278. if err != nil {
  279. 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. }