feat: sync certificates to remote server #293, #363, #411

This commit is contained in:
Jacky 2024-06-18 17:39:05 +08:00
parent 11e460765a
commit b3486a42a5
No known key found for this signature in database
GPG key ID: 215C21B10DF38B4D
41 changed files with 2429 additions and 1649 deletions

View file

@ -4,6 +4,8 @@ import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cert"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/internal/notification"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
@ -86,6 +88,7 @@ type certJson struct {
ChallengeMethod string `json:"challenge_method"`
DnsCredentialID int `json:"dns_credential_id"`
ACMEUserID int `json:"acme_user_id"`
SyncNodeIds []int `json:"sync_node_ids"`
}
func AddCert(c *gin.Context) {
@ -103,6 +106,7 @@ func AddCert(c *gin.Context) {
ChallengeMethod: json.ChallengeMethod,
DnsCredentialID: json.DnsCredentialID,
ACMEUserID: json.ACMEUserID,
SyncNodeIds: json.SyncNodeIds,
}
err := certModel.Insert()
@ -126,6 +130,12 @@ func AddCert(c *gin.Context) {
return
}
err = cert.SyncToRemoteServer(certModel)
if err != nil {
notification.Error("Sync Certificate Error", err.Error())
return
}
c.JSON(http.StatusOK, Transformer(certModel))
}
@ -154,6 +164,7 @@ func ModifyCert(c *gin.Context) {
KeyType: json.KeyType,
DnsCredentialID: json.DnsCredentialID,
ACMEUserID: json.ACMEUserID,
SyncNodeIds: json.SyncNodeIds,
})
if err != nil {
@ -175,9 +186,58 @@ func ModifyCert(c *gin.Context) {
return
}
err = cert.SyncToRemoteServer(certModel)
if err != nil {
notification.Error("Sync Certificate Error", err.Error())
return
}
GetCert(c)
}
func RemoveCert(c *gin.Context) {
cosy.Core[model.Cert](c).Destroy()
}
func SyncCertificate(c *gin.Context) {
var json cert.SyncCertificatePayload
if !api.BindAndValid(c, &json) {
return
}
certModel := &model.Cert{
Name: json.Name,
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
KeyType: json.KeyType,
AutoCert: model.AutoCertSync,
}
db := model.UseDB()
err := db.Where(certModel).FirstOrCreate(certModel).Error
if err != nil {
api.ErrHandler(c, err)
return
}
content := &cert.Content{
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
SSLCertificate: json.SSLCertificate,
SSLCertificateKey: json.SSLCertificateKey,
}
err = content.WriteFile()
if err != nil {
api.ErrHandler(c, err)
return
}
nginx.Reload()
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

View file

@ -16,6 +16,7 @@ func InitCertificateRouter(r *gin.RouterGroup) {
r.POST("cert", AddCert)
r.POST("cert/:id", ModifyCert)
r.DELETE("cert/:id", RemoveCert)
r.PUT("cert_sync", SyncCertificate)
r.GET("certificate/dns_providers", GetDNSProvidersList)
r.GET("certificate/dns_provider/:code", GetDNSProvider)
}