certificate.go 7.5 KB

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