certificate.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. package certificate
  2. import (
  3. "net/http"
  4. "os"
  5. "github.com/0xJacky/Nginx-UI/internal/cert"
  6. "github.com/0xJacky/Nginx-UI/internal/helper"
  7. "github.com/0xJacky/Nginx-UI/internal/nginx"
  8. "github.com/0xJacky/Nginx-UI/internal/notification"
  9. "github.com/0xJacky/Nginx-UI/model"
  10. "github.com/0xJacky/Nginx-UI/query"
  11. "github.com/gin-gonic/gin"
  12. "github.com/go-acme/lego/v4/certcrypto"
  13. "github.com/spf13/cast"
  14. "github.com/uozi-tech/cosy"
  15. "github.com/uozi-tech/cosy/logger"
  16. )
  17. type APICertificate struct {
  18. *model.Cert
  19. SSLCertificate string `json:"ssl_certificate,omitempty"`
  20. SSLCertificateKey string `json:"ssl_certificate_key,omitempty"`
  21. CertificateInfo *cert.Info `json:"certificate_info,omitempty"`
  22. }
  23. func Transformer(certModel *model.Cert) (certificate *APICertificate) {
  24. var sslCertificationBytes, sslCertificationKeyBytes []byte
  25. var certificateInfo *cert.Info
  26. if certModel.SSLCertificatePath != "" &&
  27. helper.IsUnderDirectory(certModel.SSLCertificatePath, nginx.GetConfPath()) {
  28. if _, err := os.Stat(certModel.SSLCertificatePath); err == nil {
  29. sslCertificationBytes, _ = os.ReadFile(certModel.SSLCertificatePath)
  30. if !cert.IsCertificate(string(sslCertificationBytes)) {
  31. sslCertificationBytes = []byte{}
  32. }
  33. }
  34. certificateInfo, _ = cert.GetCertInfo(certModel.SSLCertificatePath)
  35. }
  36. if certModel.SSLCertificateKeyPath != "" &&
  37. helper.IsUnderDirectory(certModel.SSLCertificateKeyPath, nginx.GetConfPath()) {
  38. if _, err := os.Stat(certModel.SSLCertificateKeyPath); err == nil {
  39. sslCertificationKeyBytes, _ = os.ReadFile(certModel.SSLCertificateKeyPath)
  40. if !cert.IsPrivateKey(string(sslCertificationKeyBytes)) {
  41. sslCertificationKeyBytes = []byte{}
  42. }
  43. }
  44. }
  45. return &APICertificate{
  46. Cert: certModel,
  47. SSLCertificate: string(sslCertificationBytes),
  48. SSLCertificateKey: string(sslCertificationKeyBytes),
  49. CertificateInfo: certificateInfo,
  50. }
  51. }
  52. func GetCertList(c *gin.Context) {
  53. s := logger.NewSessionLogger(c)
  54. s.Info("GetCertList")
  55. cosy.Core[model.Cert](c).SetFussy("name", "domain").
  56. SetTransformer(func(m *model.Cert) any {
  57. info, _ := cert.GetCertInfo(m.SSLCertificatePath)
  58. return APICertificate{
  59. Cert: m,
  60. CertificateInfo: info,
  61. }
  62. }).PagingList()
  63. }
  64. func GetCert(c *gin.Context) {
  65. q := query.Cert
  66. id := cast.ToUint64(c.Param("id"))
  67. if contextId, ok := c.Get("id"); ok {
  68. id = cast.ToUint64(contextId)
  69. }
  70. certModel, err := q.FirstByID(id)
  71. if err != nil {
  72. cosy.ErrHandler(c, err)
  73. return
  74. }
  75. c.JSON(http.StatusOK, Transformer(certModel))
  76. }
  77. func AddCert(c *gin.Context) {
  78. cosy.Core[model.Cert](c).
  79. SetValidRules(gin.H{
  80. "name": "omitempty",
  81. "ssl_certificate_path": "required,certificate_path",
  82. "ssl_certificate_key_path": "required,privatekey_path",
  83. "ssl_certificate": "omitempty,certificate",
  84. "ssl_certificate_key": "omitempty,privatekey",
  85. "key_type": "omitempty,auto_cert_key_type",
  86. "challenge_method": "omitempty,oneof=http01 dns01",
  87. "dns_credential_id": "omitempty",
  88. "acme_user_id": "omitempty",
  89. "sync_node_ids": "omitempty",
  90. "must_staple": "omitempty",
  91. "lego_disable_cname_support": "omitempty",
  92. "revoke_old": "omitempty",
  93. }).
  94. BeforeExecuteHook(func(ctx *cosy.Ctx[model.Cert]) {
  95. sslCertificate := cast.ToString(ctx.Payload["ssl_certificate"])
  96. // Detect and set certificate type
  97. if sslCertificate != "" {
  98. keyType, err := cert.GetKeyType(sslCertificate)
  99. if err == nil && keyType != "" {
  100. // Set KeyType based on certificate type
  101. switch keyType {
  102. case "2048":
  103. ctx.Model.KeyType = certcrypto.RSA2048
  104. case "3072":
  105. ctx.Model.KeyType = certcrypto.RSA3072
  106. case "4096":
  107. ctx.Model.KeyType = certcrypto.RSA4096
  108. case "P256":
  109. ctx.Model.KeyType = certcrypto.EC256
  110. case "P384":
  111. ctx.Model.KeyType = certcrypto.EC384
  112. }
  113. }
  114. }
  115. }).
  116. ExecutedHook(func(ctx *cosy.Ctx[model.Cert]) {
  117. sslCertificate := cast.ToString(ctx.Payload["ssl_certificate"])
  118. sslCertificateKey := cast.ToString(ctx.Payload["ssl_certificate_key"])
  119. if sslCertificate != "" && sslCertificateKey != "" {
  120. content := &cert.Content{
  121. SSLCertificatePath: ctx.Model.SSLCertificatePath,
  122. SSLCertificateKeyPath: ctx.Model.SSLCertificateKeyPath,
  123. SSLCertificate: sslCertificate,
  124. SSLCertificateKey: sslCertificateKey,
  125. }
  126. err := content.WriteFile()
  127. if err != nil {
  128. ctx.AbortWithError(err)
  129. return
  130. }
  131. }
  132. err := cert.SyncToRemoteServer(&ctx.Model)
  133. if err != nil {
  134. notification.Error("Sync Certificate Error", err.Error(), nil)
  135. return
  136. }
  137. ctx.Context.Set("id", ctx.Model.ID)
  138. }).
  139. SetNextHandler(GetCert).
  140. Create()
  141. }
  142. func ModifyCert(c *gin.Context) {
  143. cosy.Core[model.Cert](c).
  144. SetValidRules(gin.H{
  145. "name": "omitempty",
  146. "ssl_certificate_path": "required,certificate_path",
  147. "ssl_certificate_key_path": "required,privatekey_path",
  148. "ssl_certificate": "omitempty,certificate",
  149. "ssl_certificate_key": "omitempty,privatekey",
  150. "key_type": "omitempty,auto_cert_key_type",
  151. "challenge_method": "omitempty,oneof=http01 dns01",
  152. "dns_credential_id": "omitempty",
  153. "acme_user_id": "omitempty",
  154. "sync_node_ids": "omitempty",
  155. "must_staple": "omitempty",
  156. "lego_disable_cname_support": "omitempty",
  157. "revoke_old": "omitempty",
  158. }).
  159. BeforeExecuteHook(func(ctx *cosy.Ctx[model.Cert]) {
  160. sslCertificate := cast.ToString(ctx.Payload["ssl_certificate"])
  161. // Detect and set certificate type
  162. if sslCertificate != "" {
  163. keyType, err := cert.GetKeyType(sslCertificate)
  164. if err == nil && keyType != "" {
  165. // Set KeyType based on certificate type
  166. switch keyType {
  167. case "2048":
  168. ctx.Model.KeyType = certcrypto.RSA2048
  169. case "3072":
  170. ctx.Model.KeyType = certcrypto.RSA3072
  171. case "4096":
  172. ctx.Model.KeyType = certcrypto.RSA4096
  173. case "P256":
  174. ctx.Model.KeyType = certcrypto.EC256
  175. case "P384":
  176. ctx.Model.KeyType = certcrypto.EC384
  177. }
  178. }
  179. }
  180. }).
  181. ExecutedHook(func(ctx *cosy.Ctx[model.Cert]) {
  182. sslCertificate := cast.ToString(ctx.Payload["ssl_certificate"])
  183. sslCertificateKey := cast.ToString(ctx.Payload["ssl_certificate_key"])
  184. content := &cert.Content{
  185. SSLCertificatePath: ctx.Model.SSLCertificatePath,
  186. SSLCertificateKeyPath: ctx.Model.SSLCertificateKeyPath,
  187. SSLCertificate: sslCertificate,
  188. SSLCertificateKey: sslCertificateKey,
  189. }
  190. err := content.WriteFile()
  191. if err != nil {
  192. ctx.AbortWithError(err)
  193. return
  194. }
  195. err = cert.SyncToRemoteServer(&ctx.Model)
  196. if err != nil {
  197. notification.Error("Sync Certificate Error", err.Error(), nil)
  198. return
  199. }
  200. }).
  201. SetNextHandler(GetCert).
  202. Modify()
  203. }
  204. func RemoveCert(c *gin.Context) {
  205. cosy.Core[model.Cert](c).Destroy()
  206. }
  207. func SyncCertificate(c *gin.Context) {
  208. var json cert.SyncCertificatePayload
  209. if !cosy.BindAndValid(c, &json) {
  210. return
  211. }
  212. certModel := &model.Cert{
  213. Name: json.Name,
  214. SSLCertificatePath: json.SSLCertificatePath,
  215. SSLCertificateKeyPath: json.SSLCertificateKeyPath,
  216. KeyType: json.KeyType,
  217. AutoCert: model.AutoCertSync,
  218. }
  219. db := model.UseDB()
  220. err := db.Where(certModel).FirstOrCreate(certModel).Error
  221. if err != nil {
  222. cosy.ErrHandler(c, err)
  223. return
  224. }
  225. content := &cert.Content{
  226. SSLCertificatePath: json.SSLCertificatePath,
  227. SSLCertificateKeyPath: json.SSLCertificateKeyPath,
  228. SSLCertificate: json.SSLCertificate,
  229. SSLCertificateKey: json.SSLCertificateKey,
  230. }
  231. err = content.WriteFile()
  232. if err != nil {
  233. cosy.ErrHandler(c, err)
  234. return
  235. }
  236. nginx.Reload()
  237. c.JSON(http.StatusOK, gin.H{
  238. "message": "ok",
  239. })
  240. }