feat: store auto-cert log to db

This commit is contained in:
0xJacky 2023-02-15 12:51:12 +08:00
parent e9d26ded1c
commit a9aacce0ad
No known key found for this signature in database
GPG key ID: B6E4A6E4A561BAF0
8 changed files with 771 additions and 726 deletions

View file

@ -14,8 +14,8 @@ class Domain extends Curd {
return http.get('template') return http.get('template')
} }
add_auto_cert(domain: string) { add_auto_cert(domain: string, data: any) {
return http.post('auto_cert/' + domain) return http.post('auto_cert/' + domain, data)
} }
remove_auto_cert(domain: string) { remove_auto_cert(domain: string) {

View file

@ -2,15 +2,15 @@
import {useGettext} from 'vue3-gettext' import {useGettext} from 'vue3-gettext'
import {input} from '@/components/StdDataEntry' import {input} from '@/components/StdDataEntry'
import {customRender, datetime} from '@/components/StdDataDisplay/StdTableTransformer' import {customRender, datetime} from '@/components/StdDataDisplay/StdTableTransformer'
import {h} from 'vue'
import {Badge} from 'ant-design-vue' import {Badge} from 'ant-design-vue'
import cert from '@/api/cert' import cert from '@/api/cert'
import StdCurd from '@/components/StdDataDisplay/StdCurd.vue' import StdCurd from '@/components/StdDataDisplay/StdCurd.vue'
import Template from '@/views/template/Template.vue' import Template from '@/views/template/Template.vue'
import CodeEditor from '@/components/CodeEditor/CodeEditor.vue' import CodeEditor from '@/components/CodeEditor/CodeEditor.vue'
import CertInfo from '@/views/domain/cert/CertInfo.vue' import CertInfo from '@/views/domain/cert/CertInfo.vue'
import {h} from 'vue'
const {$gettext} = useGettext() const {$gettext, interpolate} = useGettext()
const columns = [{ const columns = [{
title: () => $gettext('Name'), title: () => $gettext('Name'),
@ -81,11 +81,33 @@ const columns = [{
row-key="name" row-key="name"
> >
<template #beforeEdit="{data}"> <template #beforeEdit="{data}">
<div v-if="data.auto_cert===1" style="margin-bottom: 15px"> <template v-if="data.auto_cert===1">
<a-alert <div style="margin-bottom: 15px">
:message="$gettext('Auto cert is enabled, please do not modify this certification.')" type="info" <a-alert
show-icon/> :message="$gettext('Auto cert is enabled, please do not modify this certification.')"
</div> type="info"
show-icon/>
</div>
<div v-if="!data.filename" style="margin-bottom: 15px">
<a-alert
:message="$gettext('This auto-cert item is invalid, please remove it.')"
type="error"
show-icon/>
</div>
<div v-else-if="!data.domains" style="margin-bottom: 15px">
<a-alert
:message="interpolate($gettext('Domains list is empty, try to reopen auto-cert for %{config}'), {config: data.filename})"
type="error"
show-icon/>
</div>
<div v-if="data.log" style="margin-bottom: 15px">
<a-form layout="vertical">
<a-form-item :label="$gettext('Auto-Cert Log')">
<p>{{ data.log }}</p>
</a-form-item>
</a-form>
</div>
</template>
<a-form layout="vertical" v-if="data.certificate_info"> <a-form layout="vertical" v-if="data.certificate_info">
<a-form-item :label="$gettext('Certificate Status')"> <a-form-item :label="$gettext('Certificate Status')">
<cert-info :cert="data.certificate_info"/> <cert-info :cert="data.certificate_info"/>

View file

@ -61,7 +61,7 @@ function callback(ssl_certificate: string, ssl_certificate_key: string) {
function change_auto_cert(r: boolean) { function change_auto_cert(r: boolean) {
if (r) { if (r) {
domain.add_auto_cert(props.config_name).then(() => { domain.add_auto_cert(props.config_name, {domains: name.value.trim().split(' ')}).then(() => {
message.success(interpolate($gettext('Auto-renewal enabled for %{name}'), {name: name.value})) message.success(interpolate($gettext('Auto-renewal enabled for %{name}'), {name: name.value}))
}).catch(e => { }).catch(e => {
message.error(e.message ?? interpolate($gettext('Enable auto-renewal failed for %{name}'), {name: name.value})) message.error(e.message ?? interpolate($gettext('Enable auto-renewal failed for %{name}'), {name: name.value}))

View file

@ -1,349 +1,350 @@
package api package api
import ( import (
"github.com/0xJacky/Nginx-UI/server/model" "github.com/0xJacky/Nginx-UI/server/model"
"github.com/0xJacky/Nginx-UI/server/pkg/cert" "github.com/0xJacky/Nginx-UI/server/pkg/cert"
"github.com/0xJacky/Nginx-UI/server/pkg/nginx" "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/spf13/cast" "github.com/spf13/cast"
"log" "log"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
) )
const ( const (
Success = "success" Success = "success"
Info = "info" Info = "info"
Error = "error" Error = "error"
) )
type IssueCertResponse struct { type IssueCertResponse struct {
Status string `json:"status"` Status string `json:"status"`
Message string `json:"message"` Message string `json:"message"`
SSLCertificate string `json:"ssl_certificate,omitempty"` SSLCertificate string `json:"ssl_certificate,omitempty"`
SSLCertificateKey string `json:"ssl_certificate_key,omitempty"` SSLCertificateKey string `json:"ssl_certificate_key,omitempty"`
} }
func handleIssueCertLogChan(conn *websocket.Conn, logChan chan string) { func handleIssueCertLogChan(conn *websocket.Conn, logChan chan string) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Println("api.handleIssueCertLogChan recover", err) log.Println("api.handleIssueCertLogChan recover", err)
} }
}() }()
for logString := range logChan { for logString := range logChan {
err := conn.WriteJSON(IssueCertResponse{ err := conn.WriteJSON(IssueCertResponse{
Status: Info, Status: Info,
Message: logString, Message: logString,
}) })
if err != nil { if err != nil {
log.Println("Error handleIssueCertLogChan", err) log.Println("Error handleIssueCertLogChan", err)
return return
} }
} }
} }
func IssueCert(c *gin.Context) { func IssueCert(c *gin.Context) {
var upGrader = websocket.Upgrader{ var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
return true return true
}, },
} }
// upgrade http to websocket // upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil) ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
} }
defer func(ws *websocket.Conn) { defer func(ws *websocket.Conn) {
err := ws.Close() err := ws.Close()
if err != nil { if err != nil {
log.Println("defer websocket close err", err) log.Println("defer websocket close err", err)
} }
}(ws) }(ws)
// read // read
var buffer struct { var buffer struct {
ServerName []string `json:"server_name"` ServerName []string `json:"server_name"`
} }
err = ws.ReadJSON(&buffer) err = ws.ReadJSON(&buffer)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
} }
logChan := make(chan string, 1) certModel, err := model.FirstOrCreateCert(c.Param("name"))
errChan := make(chan error, 1)
go cert.IssueCert(buffer.ServerName, logChan, errChan) if err != nil {
log.Println(err)
}
go handleIssueCertLogChan(ws, logChan) logChan := make(chan string, 1)
errChan := make(chan error, 1)
// block, unless errChan closed go cert.IssueCert(buffer.ServerName, logChan, errChan)
for err = range errChan {
log.Println("Error cert.IssueCert", err)
err = ws.WriteJSON(IssueCertResponse{ go handleIssueCertLogChan(ws, logChan)
Status: Error,
Message: err.Error(),
})
if err != nil { // block, until errChan closes
log.Println("Error WriteJSON", err) for err = range errChan {
return errLog := &cert.AutoCertErrorLog{}
} errLog.SetCertModel(&certModel)
errLog.Exit("issue cert", err)
return err = ws.WriteJSON(IssueCertResponse{
} Status: Error,
Message: err.Error(),
})
close(logChan) if err != nil {
log.Println("Error WriteJSON", err)
return
}
certDirName := strings.Join(buffer.ServerName, "_") return
sslCertificatePath := nginx.GetConfPath("ssl", certDirName, "fullchain.cer") }
sslCertificateKeyPath := nginx.GetConfPath("ssl", certDirName, "private.key")
certModel, err := model.FirstOrCreateCert(c.Param("name")) certDirName := strings.Join(buffer.ServerName, "_")
sslCertificatePath := nginx.GetConfPath("ssl", certDirName, "fullchain.cer")
sslCertificateKeyPath := nginx.GetConfPath("ssl", certDirName, "private.key")
if err != nil { err = certModel.Updates(&model.Cert{
log.Println(err) Domains: buffer.ServerName,
} SSLCertificatePath: sslCertificatePath,
SSLCertificateKeyPath: sslCertificateKeyPath,
})
err = certModel.Updates(&model.Cert{ if err != nil {
Domains: buffer.ServerName, log.Println(err)
SSLCertificatePath: sslCertificatePath, err = ws.WriteJSON(IssueCertResponse{
SSLCertificateKeyPath: sslCertificateKeyPath, Status: Error,
}) Message: err.Error(),
})
return
}
if err != nil { certModel.ClearLog()
log.Println(err)
err = ws.WriteJSON(IssueCertResponse{
Status: Error,
Message: err.Error(),
})
return
}
err = ws.WriteJSON(IssueCertResponse{ err = ws.WriteJSON(IssueCertResponse{
Status: Success, Status: Success,
Message: "Issued certificate successfully", Message: "Issued certificate successfully",
SSLCertificate: sslCertificatePath, SSLCertificate: sslCertificatePath,
SSLCertificateKey: sslCertificateKeyPath, SSLCertificateKey: sslCertificateKeyPath,
}) })
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
} }
} }
func GetCertList(c *gin.Context) { func GetCertList(c *gin.Context) {
certList := model.GetCertList(c.Query("name"), c.Query("domain")) certList := model.GetCertList(c.Query("name"), c.Query("domain"))
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"data": certList, "data": certList,
}) })
} }
func getCert(c *gin.Context, certModel *model.Cert) { func getCert(c *gin.Context, certModel *model.Cert) {
type resp struct { type resp struct {
*model.Cert *model.Cert
SSLCertification string `json:"ssl_certification"` SSLCertification string `json:"ssl_certification"`
SSLCertificationKey string `json:"ssl_certification_key"` SSLCertificationKey string `json:"ssl_certification_key"`
CertificateInfo *CertificateInfo `json:"certificate_info,omitempty"` CertificateInfo *CertificateInfo `json:"certificate_info,omitempty"`
} }
var sslCertificationBytes, sslCertificationKeyBytes []byte var sslCertificationBytes, sslCertificationKeyBytes []byte
var certificateInfo *CertificateInfo var certificateInfo *CertificateInfo
if certModel.SSLCertificatePath != "" { if certModel.SSLCertificatePath != "" {
if _, err := os.Stat(certModel.SSLCertificatePath); err == nil { if _, err := os.Stat(certModel.SSLCertificatePath); err == nil {
sslCertificationBytes, _ = os.ReadFile(certModel.SSLCertificatePath) sslCertificationBytes, _ = os.ReadFile(certModel.SSLCertificatePath)
} }
pubKey, err := cert.GetCertInfo(certModel.SSLCertificatePath) pubKey, err := cert.GetCertInfo(certModel.SSLCertificatePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
certificateInfo = &CertificateInfo{ certificateInfo = &CertificateInfo{
SubjectName: pubKey.Subject.CommonName, SubjectName: pubKey.Subject.CommonName,
IssuerName: pubKey.Issuer.CommonName, IssuerName: pubKey.Issuer.CommonName,
NotAfter: pubKey.NotAfter, NotAfter: pubKey.NotAfter,
NotBefore: pubKey.NotBefore, NotBefore: pubKey.NotBefore,
} }
} }
if certModel.SSLCertificateKeyPath != "" { if certModel.SSLCertificateKeyPath != "" {
if _, err := os.Stat(certModel.SSLCertificateKeyPath); err == nil { if _, err := os.Stat(certModel.SSLCertificateKeyPath); err == nil {
sslCertificationKeyBytes, _ = os.ReadFile(certModel.SSLCertificateKeyPath) sslCertificationKeyBytes, _ = os.ReadFile(certModel.SSLCertificateKeyPath)
} }
} }
c.JSON(http.StatusOK, resp{ c.JSON(http.StatusOK, resp{
certModel, certModel,
string(sslCertificationBytes), string(sslCertificationBytes),
string(sslCertificationKeyBytes), string(sslCertificationKeyBytes),
certificateInfo, certificateInfo,
}) })
} }
func GetCert(c *gin.Context) { func GetCert(c *gin.Context) {
certModel, err := model.FirstCertByID(cast.ToInt(c.Param("id"))) certModel, err := model.FirstCertByID(cast.ToInt(c.Param("id")))
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
getCert(c, &certModel) getCert(c, &certModel)
} }
func AddCert(c *gin.Context) { func AddCert(c *gin.Context) {
var json struct { var json struct {
Name string `json:"name"` Name string `json:"name"`
SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"` SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"` SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
SSLCertification string `json:"ssl_certification"` SSLCertification string `json:"ssl_certification"`
SSLCertificationKey string `json:"ssl_certification_key"` SSLCertificationKey string `json:"ssl_certification_key"`
} }
if !BindAndValid(c, &json) { if !BindAndValid(c, &json) {
return return
} }
certModel := &model.Cert{ certModel := &model.Cert{
Name: json.Name, Name: json.Name,
SSLCertificatePath: json.SSLCertificatePath, SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath, SSLCertificateKeyPath: json.SSLCertificateKeyPath,
} }
err := certModel.Insert() err := certModel.Insert()
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
if json.SSLCertification != "" { if json.SSLCertification != "" {
err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644) err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
if json.SSLCertificationKey != "" { if json.SSLCertificationKey != "" {
err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644) err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
getCert(c, certModel) getCert(c, certModel)
} }
func ModifyCert(c *gin.Context) { func ModifyCert(c *gin.Context) {
id := cast.ToInt(c.Param("id")) id := cast.ToInt(c.Param("id"))
certModel, err := model.FirstCertByID(id) certModel, err := model.FirstCertByID(id)
var json struct { var json struct {
Name string `json:"name"` Name string `json:"name"`
Domain string `json:"domain" binding:"required"` SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"` SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"` SSLCertification string `json:"ssl_certification"`
SSLCertification string `json:"ssl_certification"` SSLCertificationKey string `json:"ssl_certification_key"`
SSLCertificationKey string `json:"ssl_certification_key"` }
}
if !BindAndValid(c, &json) { if !BindAndValid(c, &json) {
return return
} }
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = certModel.Updates(&model.Cert{ err = certModel.Updates(&model.Cert{
Name: json.Name, Name: json.Name,
SSLCertificatePath: json.SSLCertificatePath, SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath, SSLCertificateKeyPath: json.SSLCertificateKeyPath,
}) })
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
if json.SSLCertification != "" { if json.SSLCertification != "" {
err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644) err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
if json.SSLCertificationKey != "" { if json.SSLCertificationKey != "" {
err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644) err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
GetCert(c) GetCert(c)
} }
func RemoveCert(c *gin.Context) { func RemoveCert(c *gin.Context) {
id := cast.ToInt(c.Param("id")) id := cast.ToInt(c.Param("id"))
certModel, err := model.FirstCertByID(id) certModel, err := model.FirstCertByID(id)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = certModel.Remove() err = certModel.Remove()
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusNoContent, nil) c.JSON(http.StatusNoContent, nil)
} }

View file

@ -1,430 +1,440 @@
package api package api
import ( import (
"github.com/0xJacky/Nginx-UI/server/model" "github.com/0xJacky/Nginx-UI/server/model"
"github.com/0xJacky/Nginx-UI/server/pkg/cert" "github.com/0xJacky/Nginx-UI/server/pkg/cert"
"github.com/0xJacky/Nginx-UI/server/pkg/config_list" "github.com/0xJacky/Nginx-UI/server/pkg/config_list"
"github.com/0xJacky/Nginx-UI/server/pkg/helper" "github.com/0xJacky/Nginx-UI/server/pkg/helper"
"github.com/0xJacky/Nginx-UI/server/pkg/nginx" "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"log" "log"
"net/http" "net/http"
"os" "os"
"strings" "strings"
"time" "time"
) )
func GetDomains(c *gin.Context) { func GetDomains(c *gin.Context) {
name := c.Query("name") name := c.Query("name")
orderBy := c.Query("order_by") orderBy := c.Query("order_by")
sort := c.DefaultQuery("sort", "desc") sort := c.DefaultQuery("sort", "desc")
mySort := map[string]string{ mySort := map[string]string{
"enabled": "bool", "enabled": "bool",
"name": "string", "name": "string",
"modify": "time", "modify": "time",
} }
configFiles, err := os.ReadDir(nginx.GetConfPath("sites-available")) configFiles, err := os.ReadDir(nginx.GetConfPath("sites-available"))
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
enabledConfig, err := os.ReadDir(nginx.GetConfPath("sites-enabled")) enabledConfig, err := os.ReadDir(nginx.GetConfPath("sites-enabled"))
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
enabledConfigMap := make(map[string]bool) enabledConfigMap := make(map[string]bool)
for i := range enabledConfig { for i := range enabledConfig {
enabledConfigMap[enabledConfig[i].Name()] = true enabledConfigMap[enabledConfig[i].Name()] = true
} }
var configs []gin.H var configs []gin.H
for i := range configFiles { for i := range configFiles {
file := configFiles[i] file := configFiles[i]
fileInfo, _ := file.Info() fileInfo, _ := file.Info()
if !file.IsDir() { if !file.IsDir() {
if name != "" && !strings.Contains(file.Name(), name) { if name != "" && !strings.Contains(file.Name(), name) {
continue continue
} }
configs = append(configs, gin.H{ configs = append(configs, gin.H{
"name": file.Name(), "name": file.Name(),
"size": fileInfo.Size(), "size": fileInfo.Size(),
"modify": fileInfo.ModTime(), "modify": fileInfo.ModTime(),
"enabled": enabledConfigMap[file.Name()], "enabled": enabledConfigMap[file.Name()],
}) })
} }
} }
configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs) configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"data": configs, "data": configs,
}) })
} }
type CertificateInfo struct { type CertificateInfo struct {
SubjectName string `json:"subject_name"` SubjectName string `json:"subject_name"`
IssuerName string `json:"issuer_name"` IssuerName string `json:"issuer_name"`
NotAfter time.Time `json:"not_after"` NotAfter time.Time `json:"not_after"`
NotBefore time.Time `json:"not_before"` NotBefore time.Time `json:"not_before"`
} }
func GetDomain(c *gin.Context) { func GetDomain(c *gin.Context) {
rewriteName, ok := c.Get("rewriteConfigFileName") rewriteName, ok := c.Get("rewriteConfigFileName")
name := c.Param("name") name := c.Param("name")
// for modify filename // for modify filename
if ok { if ok {
name = rewriteName.(string) name = rewriteName.(string)
} }
path := nginx.GetConfPath("sites-available", name) path := nginx.GetConfPath("sites-available", name)
enabled := true enabled := true
if _, err := os.Stat(nginx.GetConfPath("sites-enabled", name)); os.IsNotExist(err) { if _, err := os.Stat(nginx.GetConfPath("sites-enabled", name)); os.IsNotExist(err) {
enabled = false enabled = false
} }
c.Set("maybe_error", "nginx_config_syntax_error") c.Set("maybe_error", "nginx_config_syntax_error")
config, err := nginx.ParseNgxConfig(path) config, err := nginx.ParseNgxConfig(path)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.Set("maybe_error", "") c.Set("maybe_error", "")
certInfoMap := make(map[int]CertificateInfo) certInfoMap := make(map[int]CertificateInfo)
for serverIdx, server := range config.Servers { for serverIdx, server := range config.Servers {
for _, directive := range server.Directives { for _, directive := range server.Directives {
if directive.Directive == "ssl_certificate" { if directive.Directive == "ssl_certificate" {
pubKey, err := cert.GetCertInfo(directive.Params) pubKey, err := cert.GetCertInfo(directive.Params)
if err != nil { if err != nil {
log.Println("Failed to get certificate information", err) log.Println("Failed to get certificate information", err)
break break
} }
certInfoMap[serverIdx] = CertificateInfo{ certInfoMap[serverIdx] = CertificateInfo{
SubjectName: pubKey.Subject.CommonName, SubjectName: pubKey.Subject.CommonName,
IssuerName: pubKey.Issuer.CommonName, IssuerName: pubKey.Issuer.CommonName,
NotAfter: pubKey.NotAfter, NotAfter: pubKey.NotAfter,
NotBefore: pubKey.NotBefore, NotBefore: pubKey.NotBefore,
} }
break break
} }
} }
} }
certModel, _ := model.FirstCert(name) certModel, _ := model.FirstCert(name)
c.Set("maybe_error", "nginx_config_syntax_error") c.Set("maybe_error", "nginx_config_syntax_error")
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"enabled": enabled, "enabled": enabled,
"name": name, "name": name,
"config": config.FmtCode(), "config": config.FmtCode(),
"tokenized": config, "tokenized": config,
"auto_cert": certModel.AutoCert == model.AutoCertEnabled, "auto_cert": certModel.AutoCert == model.AutoCertEnabled,
"cert_info": certInfoMap, "cert_info": certInfoMap,
}) })
} }
func SaveDomain(c *gin.Context) { func SaveDomain(c *gin.Context) {
name := c.Param("name") name := c.Param("name")
if name == "" { if name == "" {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
"message": "param name is empty", "message": "param name is empty",
}) })
return return
} }
var json struct { var json struct {
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
Content string `json:"content" binding:"required"` Content string `json:"content" binding:"required"`
Overwrite bool `json:"overwrite"` Overwrite bool `json:"overwrite"`
} }
if !BindAndValid(c, &json) { if !BindAndValid(c, &json) {
return return
} }
path := nginx.GetConfPath("sites-available", name) path := nginx.GetConfPath("sites-available", name)
if !json.Overwrite && helper.FileExists(path) { if !json.Overwrite && helper.FileExists(path) {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists", "message": "File exists",
}) })
return return
} }
err := os.WriteFile(path, []byte(json.Content), 0644) err := os.WriteFile(path, []byte(json.Content), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
enabledConfigFilePath := nginx.GetConfPath("sites-enabled", name) enabledConfigFilePath := nginx.GetConfPath("sites-enabled", name)
// rename the config file if needed // rename the config file if needed
if name != json.Name { if name != json.Name {
newPath := nginx.GetConfPath("sites-available", json.Name) newPath := nginx.GetConfPath("sites-available", json.Name)
// check if dst file exists, do not rename // check if dst file exists, do not rename
if helper.FileExists(newPath) { if helper.FileExists(newPath) {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists", "message": "File exists",
}) })
return return
} }
// recreate soft link // recreate soft link
if helper.FileExists(enabledConfigFilePath) { if helper.FileExists(enabledConfigFilePath) {
_ = os.Remove(enabledConfigFilePath) _ = os.Remove(enabledConfigFilePath)
enabledConfigFilePath = nginx.GetConfPath("sites-enabled", json.Name) enabledConfigFilePath = nginx.GetConfPath("sites-enabled", json.Name)
err = os.Symlink(newPath, enabledConfigFilePath) err = os.Symlink(newPath, enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
err = os.Rename(path, newPath) err = os.Rename(path, newPath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
name = json.Name name = json.Name
c.Set("rewriteConfigFileName", name) c.Set("rewriteConfigFileName", name)
} }
enabledConfigFilePath = nginx.GetConfPath("sites-enabled", name) enabledConfigFilePath = nginx.GetConfPath("sites-enabled", name)
if helper.FileExists(enabledConfigFilePath) { if helper.FileExists(enabledConfigFilePath) {
// Test nginx configuration // Test nginx configuration
output := nginx.TestConf() output := nginx.TestConf()
if nginx.GetLogLevel(output) >= nginx.Warn { if nginx.GetLogLevel(output) >= nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
"error": "nginx_config_syntax_error", "error": "nginx_config_syntax_error",
}) })
return return
} }
output = nginx.Reload() output = nginx.Reload()
if nginx.GetLogLevel(output) >= nginx.Warn { if nginx.GetLogLevel(output) >= nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
}) })
return return
} }
} }
GetDomain(c) GetDomain(c)
} }
func EnableDomain(c *gin.Context) { func EnableDomain(c *gin.Context) {
configFilePath := nginx.GetConfPath("sites-available", c.Param("name")) configFilePath := nginx.GetConfPath("sites-available", c.Param("name"))
enabledConfigFilePath := nginx.GetConfPath("sites-enabled", c.Param("name")) enabledConfigFilePath := nginx.GetConfPath("sites-enabled", c.Param("name"))
_, err := os.Stat(configFilePath) _, err := os.Stat(configFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) { if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) {
err = os.Symlink(configFilePath, enabledConfigFilePath) err = os.Symlink(configFilePath, enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
// Test nginx config, if not pass then disable the site. // Test nginx config, if not pass then disable the site.
output := nginx.TestConf() output := nginx.TestConf()
if nginx.GetLogLevel(output) >= nginx.Warn { if nginx.GetLogLevel(output) >= nginx.Warn {
_ = os.Remove(enabledConfigFilePath) _ = os.Remove(enabledConfigFilePath)
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
}) })
return return
} }
output = nginx.Reload() output = nginx.Reload()
if nginx.GetLogLevel(output) >= nginx.Warn { if nginx.GetLogLevel(output) >= nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
}) })
return return
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "ok", "message": "ok",
}) })
} }
func DisableDomain(c *gin.Context) { func DisableDomain(c *gin.Context) {
enabledConfigFilePath := nginx.GetConfPath("sites-enabled", c.Param("name")) enabledConfigFilePath := nginx.GetConfPath("sites-enabled", c.Param("name"))
_, err := os.Stat(enabledConfigFilePath) _, err := os.Stat(enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.Remove(enabledConfigFilePath) err = os.Remove(enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
// delete auto cert record // delete auto cert record
certModel := model.Cert{Filename: c.Param("name")} certModel := model.Cert{Filename: c.Param("name")}
err = certModel.Remove() err = certModel.Remove()
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
output := nginx.Reload() output := nginx.Reload()
if nginx.GetLogLevel(output) >= nginx.Warn { if nginx.GetLogLevel(output) >= nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
}) })
return return
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "ok", "message": "ok",
}) })
} }
func DeleteDomain(c *gin.Context) { func DeleteDomain(c *gin.Context) {
var err error var err error
name := c.Param("name") name := c.Param("name")
availablePath := nginx.GetConfPath("sites-available", name) availablePath := nginx.GetConfPath("sites-available", name)
enabledPath := nginx.GetConfPath("sites-enabled", name) enabledPath := nginx.GetConfPath("sites-enabled", name)
if _, err = os.Stat(availablePath); os.IsNotExist(err) { if _, err = os.Stat(availablePath); os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{ c.JSON(http.StatusNotFound, gin.H{
"message": "site not found", "message": "site not found",
}) })
return return
} }
if _, err = os.Stat(enabledPath); err == nil { if _, err = os.Stat(enabledPath); err == nil {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
"message": "site is enabled", "message": "site is enabled",
}) })
return return
} }
certModel := model.Cert{Filename: name} certModel := model.Cert{Filename: name}
_ = certModel.Remove() _ = certModel.Remove()
err = os.Remove(availablePath) err = os.Remove(availablePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "ok", "message": "ok",
}) })
} }
func AddDomainToAutoCert(c *gin.Context) { func AddDomainToAutoCert(c *gin.Context) {
name := c.Param("name") name := c.Param("name")
certModel, err := model.FirstOrCreateCert(name)
if err != nil { var json struct {
ErrHandler(c, err) Domains []string `json:"domains"`
return }
}
err = certModel.Updates(&model.Cert{ if !BindAndValid(c, &json) {
Name: name, return
AutoCert: model.AutoCertEnabled, }
})
if err != nil { certModel, err := model.FirstOrCreateCert(name)
ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, certModel) if err != nil {
ErrHandler(c, err)
return
}
err = certModel.Updates(&model.Cert{
Name: name,
Domains: json.Domains,
AutoCert: model.AutoCertEnabled,
})
if err != nil {
ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, certModel)
} }
func RemoveDomainFromAutoCert(c *gin.Context) { func RemoveDomainFromAutoCert(c *gin.Context) {
name := c.Param("name") name := c.Param("name")
certModel, err := model.FirstCert(name) certModel, err := model.FirstCert(name)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = certModel.Updates(&model.Cert{ err = certModel.Updates(&model.Cert{
AutoCert: model.AutoCertDisabled, AutoCert: model.AutoCertDisabled,
}) })
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusOK, nil) c.JSON(http.StatusOK, nil)
} }
func DuplicateSite(c *gin.Context) { func DuplicateSite(c *gin.Context) {
name := c.Param("name") name := c.Param("name")
var json struct { var json struct {
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
} }
if !BindAndValid(c, &json) { if !BindAndValid(c, &json) {
return return
} }
src := nginx.GetConfPath("sites-available", name) src := nginx.GetConfPath("sites-available", name)
dst := nginx.GetConfPath("sites-available", json.Name) dst := nginx.GetConfPath("sites-available", json.Name)
if helper.FileExists(dst) { if helper.FileExists(dst) {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists", "message": "File exists",
}) })
return return
} }
_, err := helper.CopyFile(src, dst) _, err := helper.CopyFile(src, dst)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"dst": dst, "dst": dst,
}) })
} }

View file

@ -1,97 +1,101 @@
package model package model
import ( import (
"github.com/0xJacky/Nginx-UI/server/pkg/nginx" "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/lib/pq" "github.com/lib/pq"
"os" "os"
) )
const ( const (
AutoCertEnabled = 1 AutoCertEnabled = 1
AutoCertDisabled = -1 AutoCertDisabled = -1
) )
type CertDomains []string type CertDomains []string
type Cert struct { type Cert struct {
Model Model
Name string `json:"name"` Name string `json:"name"`
Domains pq.StringArray `json:"domains" gorm:"type:text[]"` Domains pq.StringArray `json:"domains" gorm:"type:text[]"`
Filename string `json:"filename"` Filename string `json:"filename"`
SSLCertificatePath string `json:"ssl_certificate_path"` SSLCertificatePath string `json:"ssl_certificate_path"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path"` SSLCertificateKeyPath string `json:"ssl_certificate_key_path"`
AutoCert int `json:"auto_cert"` AutoCert int `json:"auto_cert"`
Log string `json:"log"` Log string `json:"log"`
} }
func FirstCert(confName string) (c Cert, err error) { func FirstCert(confName string) (c Cert, err error) {
err = db.First(&c, &Cert{ err = db.First(&c, &Cert{
Filename: confName, Filename: confName,
}).Error }).Error
return return
} }
func FirstOrCreateCert(confName string) (c Cert, err error) { func FirstOrCreateCert(confName string) (c Cert, err error) {
err = db.FirstOrCreate(&c, &Cert{Filename: confName}).Error err = db.FirstOrCreate(&c, &Cert{Filename: confName}).Error
return return
} }
func (c *Cert) Insert() error { func (c *Cert) Insert() error {
return db.Create(c).Error return db.Create(c).Error
} }
func GetAutoCertList() (c []*Cert) { func GetAutoCertList() (c []*Cert) {
var t []*Cert var t []*Cert
db.Where("auto_cert", AutoCertEnabled).Find(&t) db.Where("auto_cert", AutoCertEnabled).Find(&t)
// check if this domain is enabled // check if this domain is enabled
enabledConfig, err := os.ReadDir(nginx.GetConfPath("sites-enabled")) enabledConfig, err := os.ReadDir(nginx.GetConfPath("sites-enabled"))
if err != nil { if err != nil {
return return
} }
enabledConfigMap := make(map[string]bool) enabledConfigMap := make(map[string]bool)
for i := range enabledConfig { for i := range enabledConfig {
enabledConfigMap[enabledConfig[i].Name()] = true enabledConfigMap[enabledConfig[i].Name()] = true
} }
for _, v := range t { for _, v := range t {
if enabledConfigMap[v.Filename] == true { if enabledConfigMap[v.Filename] == true {
c = append(c, v) c = append(c, v)
} }
} }
return return
} }
func GetCertList(name, domain string) (c []Cert) { func GetCertList(name, domain string) (c []Cert) {
tx := db tx := db
if name != "" { if name != "" {
tx = tx.Where("name LIKE ? or domain LIKE ?", "%"+name+"%", "%"+name+"%") tx = tx.Where("name LIKE ? or domain LIKE ?", "%"+name+"%", "%"+name+"%")
} }
if domain != "" { if domain != "" {
tx = tx.Where("domain LIKE ?", "%"+domain+"%") tx = tx.Where("domain LIKE ?", "%"+domain+"%")
} }
tx.Find(&c) tx.Find(&c)
return return
} }
func FirstCertByID(id int) (c Cert, err error) { func FirstCertByID(id int) (c Cert, err error) {
err = db.First(&c, id).Error err = db.First(&c, id).Error
return return
} }
func (c *Cert) Updates(n *Cert) error { func (c *Cert) Updates(n *Cert) error {
return db.Model(&Cert{}).Where("id", c.ID).Updates(n).Error return db.Model(&Cert{}).Where("id", c.ID).Updates(n).Error
}
func (c *Cert) ClearLog() {
db.Model(&Cert{}).Where("id", c.ID).Update("log", "")
} }
func (c *Cert) Remove() error { func (c *Cert) Remove() error {
if c.Filename == "" { if c.Filename == "" {
return db.Delete(c).Error return db.Delete(c).Error
} }
return db.Where("filename", c.Filename).Delete(c).Error return db.Where("filename", c.Filename).Delete(c).Error
} }

View file

@ -1,117 +1,123 @@
package cert package cert
import ( import (
"fmt" "fmt"
"github.com/0xJacky/Nginx-UI/server/model" "github.com/0xJacky/Nginx-UI/server/model"
"github.com/pkg/errors" "github.com/pkg/errors"
"log" "log"
"time" "time"
) )
func handleIssueCertLogChan(logChan chan string) { func handleIssueCertLogChan(logChan chan string) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Println("[Auto Cert] handleIssueCertLogChan", err) log.Println("[Auto Cert] handleIssueCertLogChan", err)
} }
}() }()
for logString := range logChan { for logString := range logChan {
log.Println("[Auto Cert] Info", logString) log.Println("[Auto Cert] Info", logString)
} }
} }
type AutoCertErrorLog struct { type AutoCertErrorLog struct {
buffer []string buffer []string
cert *model.Cert cert *model.Cert
} }
func (t *AutoCertErrorLog) SetCertModel(cert *model.Cert) { func (t *AutoCertErrorLog) SetCertModel(cert *model.Cert) {
t.cert = cert t.cert = cert
} }
func (t *AutoCertErrorLog) Push(text string, err error) { func (t *AutoCertErrorLog) Push(text string, err error) {
t.buffer = append(t.buffer, text+" "+err.Error()) t.buffer = append(t.buffer, text+" "+err.Error())
log.Println("[AutoCert Error]", text, err) log.Println("[AutoCert Error]", text, err)
} }
func (t *AutoCertErrorLog) Exit(text string, err error) { func (t *AutoCertErrorLog) Exit(text string, err error) {
t.buffer = append(t.buffer, text+" "+err.Error()) t.buffer = append(t.buffer, text+" "+err.Error())
log.Println("[AutoCert Error]", text, err) log.Println("[AutoCert Error]", text, err)
if t.cert == nil { if t.cert == nil {
return return
} }
_ = t.cert.Updates(&model.Cert{ _ = t.cert.Updates(&model.Cert{
Log: t.ToString(), Log: t.ToString(),
}) })
} }
func (t *AutoCertErrorLog) ToString() (content string) { func (t *AutoCertErrorLog) ToString() (content string) {
for _, v := range t.buffer { for _, v := range t.buffer {
content += fmt.Sprintf("[AutoCert Error] %s\n", v) content += fmt.Sprintf("[AutoCert Error] %s\n", v)
} }
return return
} }
func AutoObtain() { func AutoObtain() {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Println("[AutoCert] Recover", err) log.Println("[AutoCert] Recover", err)
} }
}() }()
log.Println("[AutoCert] Start") log.Println("[AutoCert] Start")
autoCertList := model.GetAutoCertList() autoCertList := model.GetAutoCertList()
for _, certModel := range autoCertList { for _, certModel := range autoCertList {
confName := certModel.Filename confName := certModel.Filename
errLog := &AutoCertErrorLog{} errLog := &AutoCertErrorLog{}
errLog.SetCertModel(certModel) errLog.SetCertModel(certModel)
if len(certModel.Filename) == 0 { if len(certModel.Filename) == 0 {
errLog.Exit("", errors.New("filename is empty")) errLog.Exit("", errors.New("filename is empty"))
continue continue
} }
if len(certModel.Domains) == 0 { if len(certModel.Domains) == 0 {
errLog.Exit(confName, errors.New("domains list is empty, "+ errLog.Exit(confName, errors.New("domains list is empty, "+
"try to reopen auto-cert for this config:"+confName)) "try to reopen auto-cert for this config:"+confName))
continue continue
} }
if certModel.SSLCertificatePath != "" { if certModel.SSLCertificatePath != "" {
cert, err := GetCertInfo(certModel.SSLCertificatePath) cert, err := GetCertInfo(certModel.SSLCertificatePath)
if err != nil { if err != nil {
errLog.Push("get cert info", err) errLog.Push("get cert info", err)
// Get certificate info error, ignore this domain // Get certificate info error, ignore this domain
continue continue
} }
// every week // every week
if time.Now().Sub(cert.NotBefore).Hours()/24 < 7 { if time.Now().Sub(cert.NotBefore).Hours()/24 < 7 {
continue continue
} }
} }
// after 1 mo, reissue certificate // after 1 mo, reissue certificate
logChan := make(chan string, 1) logChan := make(chan string, 1)
errChan := make(chan error, 1) errChan := make(chan error, 1)
// support SAN certification // support SAN certification
go IssueCert(certModel.Domains, logChan, errChan) go IssueCert(certModel.Domains, logChan, errChan)
go handleIssueCertLogChan(logChan) go handleIssueCertLogChan(logChan)
// block, unless errChan closed // block, unless errChan closed
for err := range errChan { for err := range errChan {
errLog.Push("issue cert", err) errLog.Push("issue cert", err)
} }
// store error log to db
_ = certModel.Updates(&model.Cert{
Log: errLog.ToString(),
})
close(logChan) logStr := errLog.ToString()
} if logStr != "" {
log.Println("[AutoCert] End") // store error log to db
_ = certModel.Updates(&model.Cert{
Log: errLog.ToString(),
})
} else {
certModel.ClearLog()
}
close(logChan)
}
log.Println("[AutoCert] End")
} }

View file

@ -92,7 +92,7 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
) )
if err != nil { if err != nil {
errChan <- errors.Wrap(err, "issue cert challenge fail") errChan <- errors.Wrap(err, "fail to challenge")
return return
} }
@ -100,7 +100,7 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
logChan <- "Registering user" logChan <- "Registering user"
reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil { if err != nil {
errChan <- errors.Wrap(err, "issue cert register fail") errChan <- errors.Wrap(err, "fail to register")
return return
} }
myUser.Registration = reg myUser.Registration = reg
@ -113,7 +113,7 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
logChan <- "Obtaining certificate" logChan <- "Obtaining certificate"
certificates, err := client.Certificate.Obtain(request) certificates, err := client.Certificate.Obtain(request)
if err != nil { if err != nil {
errChan <- errors.Wrap(err, "issue cert fail to obtain") errChan <- errors.Wrap(err, "fail to obtain")
return return
} }
name := strings.Join(domain, "_") name := strings.Join(domain, "_")
@ -121,7 +121,7 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
if _, err = os.Stat(saveDir); os.IsNotExist(err) { if _, err = os.Stat(saveDir); os.IsNotExist(err) {
err = os.MkdirAll(saveDir, 0755) err = os.MkdirAll(saveDir, 0755)
if err != nil { if err != nil {
errChan <- errors.Wrap(err, "issue cert fail to create") errChan <- errors.Wrap(err, "fail to mkdir")
return return
} }
} }
@ -142,7 +142,7 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
certificates.PrivateKey, 0644) certificates.PrivateKey, 0644)
if err != nil { if err != nil {
errChan <- errors.Wrap(err, "error issue cert write key") errChan <- errors.Wrap(err, "fail to write key")
return return
} }
@ -152,4 +152,6 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
nginx.Reload() nginx.Reload()
logChan <- "Finished" logChan <- "Finished"
close(logChan)
} }