mirror of
https://github.com/0xJacky/nginx-ui.git
synced 2025-05-11 02:15:48 +02:00
fix: server_name split issue in SAN cert
This commit is contained in:
parent
bf3edfaa44
commit
175d19a206
17 changed files with 534 additions and 534 deletions
|
@ -525,7 +525,7 @@ function initSortable() {
|
||||||
:okText="$gettext('OK')"
|
:okText="$gettext('OK')"
|
||||||
:title="$gettext('Are you sure you want to delete?')"
|
:title="$gettext('Are you sure you want to delete?')"
|
||||||
@confirm="destroy(record[rowKey])">
|
@confirm="destroy(record[rowKey])">
|
||||||
<a-button type="link" size="small" v-translate>Delete</a-button>
|
<a-button type="link" size="small">{{ $gettext('Delete') }}</a-button>
|
||||||
</a-popconfirm>
|
</a-popconfirm>
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
@ -164,7 +164,7 @@ function wsOnMessage(m: { data: any }) {
|
||||||
</p>
|
</p>
|
||||||
<p v-if="cpu_info">
|
<p v-if="cpu_info">
|
||||||
{{ $gettext('CPU:') + ' ' }}
|
{{ $gettext('CPU:') + ' ' }}
|
||||||
<span class="cpu-model">{{ cpu_info[0]?.modelName }}</span>
|
<span class="cpu-model">{{ cpu_info[0]?.modelName || 'core' }}</span>
|
||||||
<span class="cpu-mhz">{{ (cpu_info[0]?.mhz / 1000).toFixed(2) + 'GHz' }}</span>
|
<span class="cpu-mhz">{{ (cpu_info[0]?.mhz / 1000).toFixed(2) + 'GHz' }}</span>
|
||||||
* {{ cpu_info.length }}
|
* {{ cpu_info.length }}
|
||||||
</p>
|
</p>
|
||||||
|
@ -303,10 +303,6 @@ function wsOnMessage(m: { data: any }) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.os-platform {
|
|
||||||
text-transform: capitalize;
|
|
||||||
}
|
|
||||||
|
|
||||||
.load-avg-describe {
|
.load-avg-describe {
|
||||||
@media (max-width: 1600px) and (min-width: 1200px) {
|
@media (max-width: 1600px) and (min-width: 1200px) {
|
||||||
display: none;
|
display: none;
|
||||||
|
|
|
@ -25,7 +25,7 @@ watch(route, () => {
|
||||||
const update = ref(0)
|
const update = ref(0)
|
||||||
|
|
||||||
const ngx_config = reactive({
|
const ngx_config = reactive({
|
||||||
filename: '',
|
name: '',
|
||||||
upstreams: [],
|
upstreams: [],
|
||||||
servers: []
|
servers: []
|
||||||
})
|
})
|
||||||
|
|
|
@ -7,7 +7,7 @@ import ChangeCert from '@/views/domain/cert/ChangeCert.vue'
|
||||||
|
|
||||||
const {$gettext} = useGettext()
|
const {$gettext} = useGettext()
|
||||||
|
|
||||||
const props = defineProps(['directivesMap', 'current_server_directives', 'enabled', 'cert_info'])
|
const props = defineProps(['config_name', 'directivesMap', 'current_server_directives', 'enabled', 'cert_info'])
|
||||||
|
|
||||||
const emit = defineEmits(['callback', 'update:enabled'])
|
const emit = defineEmits(['callback', 'update:enabled'])
|
||||||
|
|
||||||
|
@ -38,6 +38,7 @@ const enabled = computed({
|
||||||
<change-cert :directives-map="props.directivesMap"/>
|
<change-cert :directives-map="props.directivesMap"/>
|
||||||
|
|
||||||
<issue-cert
|
<issue-cert
|
||||||
|
:config_name="config_name"
|
||||||
:current_server_directives="props.current_server_directives"
|
:current_server_directives="props.current_server_directives"
|
||||||
:directives-map="props.directivesMap"
|
:directives-map="props.directivesMap"
|
||||||
v-model:enabled="enabled"
|
v-model:enabled="enabled"
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {useGettext} from 'vue3-gettext'
|
import {useGettext} from 'vue3-gettext'
|
||||||
import {computed, h, nextTick, onMounted, ref, VNode, watch} from 'vue'
|
import {computed, nextTick, ref, watch} from 'vue'
|
||||||
import {message} from 'ant-design-vue'
|
import {message} from 'ant-design-vue'
|
||||||
import domain from '@/api/domain'
|
import domain from '@/api/domain'
|
||||||
import websocket from '@/lib/websocket'
|
import websocket from '@/lib/websocket'
|
||||||
|
@ -8,7 +8,7 @@ import Template from '@/views/template/Template.vue'
|
||||||
|
|
||||||
const {$gettext, interpolate} = useGettext()
|
const {$gettext, interpolate} = useGettext()
|
||||||
|
|
||||||
const props = defineProps(['directivesMap', 'current_server_directives', 'enabled'])
|
const props = defineProps(['config_name', 'directivesMap', 'current_server_directives', 'enabled'])
|
||||||
|
|
||||||
const emit = defineEmits(['changeEnabled', 'callback', 'update:enabled'])
|
const emit = defineEmits(['changeEnabled', 'callback', 'update:enabled'])
|
||||||
|
|
||||||
|
@ -50,7 +50,7 @@ function job() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
issue_cert(name.value, callback)
|
issue_cert(props.config_name, name.value, callback)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -61,13 +61,13 @@ 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(name.value).then(() => {
|
domain.add_auto_cert(props.config_name).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}))
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
domain.remove_auto_cert(name.value).then(() => {
|
domain.remove_auto_cert(props.config_name).then(() => {
|
||||||
message.success(interpolate($gettext('Auto-renewal disabled for %{name}'), {name: name.value}))
|
message.success(interpolate($gettext('Auto-renewal disabled for %{name}'), {name: name.value}))
|
||||||
}).catch(e => {
|
}).catch(e => {
|
||||||
message.error(e.message ?? interpolate($gettext('Disable auto-renewal failed for %{name}'), {name: name.value}))
|
message.error(e.message ?? interpolate($gettext('Disable auto-renewal failed for %{name}'), {name: name.value}))
|
||||||
|
@ -86,7 +86,7 @@ function log(msg: string) {
|
||||||
(logContainer.value as any as Element).scroll({top: 320, left: 0, behavior: 'smooth'})
|
(logContainer.value as any as Element).scroll({top: 320, left: 0, behavior: 'smooth'})
|
||||||
}
|
}
|
||||||
|
|
||||||
const issue_cert = async (server_name: string, callback: Function) => {
|
const issue_cert = async (config_name: string, server_name: string, callback: Function) => {
|
||||||
progressStatus.value = 'active'
|
progressStatus.value = 'active'
|
||||||
modalClosable.value = false
|
modalClosable.value = false
|
||||||
modalVisible.value = true
|
modalVisible.value = true
|
||||||
|
@ -95,7 +95,7 @@ const issue_cert = async (server_name: string, callback: Function) => {
|
||||||
|
|
||||||
log($gettext('Getting the certificate, please wait...'))
|
log($gettext('Getting the certificate, please wait...'))
|
||||||
|
|
||||||
const ws = websocket('/api/cert/issue', false)
|
const ws = websocket(`/api/domain/${config_name}/cert`, false)
|
||||||
|
|
||||||
ws.onopen = () => {
|
ws.onopen = () => {
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
|
|
|
@ -168,6 +168,7 @@ watch(current_server_index, () => {
|
||||||
<template v-if="current_support_ssl&&enabled">
|
<template v-if="current_support_ssl&&enabled">
|
||||||
<cert
|
<cert
|
||||||
v-if="current_support_ssl"
|
v-if="current_support_ssl"
|
||||||
|
:config_name="ngx_config.name"
|
||||||
:cert_info="props.cert_info?.[k]"
|
:cert_info="props.cert_info?.[k]"
|
||||||
:current_server_directives="current_server_directives"
|
:current_server_directives="current_server_directives"
|
||||||
:directives-map="directivesMap"
|
:directives-map="directivesMap"
|
||||||
|
|
|
@ -66,7 +66,7 @@ export default defineConfig({
|
||||||
server: {
|
server: {
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api': {
|
'/api': {
|
||||||
target: 'https://nginx.jackyu.cn/',
|
target: 'http://127.0.0.1:9001/',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
secure: false,
|
secure: false,
|
||||||
ws: true
|
ws: true
|
||||||
|
|
1
go.mod
1
go.mod
|
@ -39,6 +39,7 @@ require (
|
||||||
github.com/jpillora/s3 v1.1.4 // indirect
|
github.com/jpillora/s3 v1.1.4 // indirect
|
||||||
github.com/json-iterator/go v1.1.9 // indirect
|
github.com/json-iterator/go v1.1.9 // indirect
|
||||||
github.com/leodido/go-urn v1.2.0 // indirect
|
github.com/leodido/go-urn v1.2.0 // indirect
|
||||||
|
github.com/lib/pq v1.10.7 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.12 // indirect
|
github.com/mattn/go-isatty v0.0.12 // indirect
|
||||||
github.com/mattn/go-sqlite3 v1.14.5 // indirect
|
github.com/mattn/go-sqlite3 v1.14.5 // indirect
|
||||||
github.com/miekg/dns v1.1.40 // indirect
|
github.com/miekg/dns v1.1.40 // indirect
|
||||||
|
|
2
go.sum
2
go.sum
|
@ -280,6 +280,8 @@ github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvf
|
||||||
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
|
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
|
||||||
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
|
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
|
||||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||||
|
github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw=
|
||||||
|
github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
github.com/linode/linodego v0.25.3/go.mod h1:GSBKPpjoQfxEfryoCRcgkuUOCuVtGHWhzI8OMdycNTE=
|
github.com/linode/linodego v0.25.3/go.mod h1:GSBKPpjoQfxEfryoCRcgkuUOCuVtGHWhzI8OMdycNTE=
|
||||||
github.com/liquidweb/go-lwApi v0.0.0-20190605172801-52a4864d2738/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=
|
github.com/liquidweb/go-lwApi v0.0.0-20190605172801-52a4864d2738/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=
|
||||||
github.com/liquidweb/go-lwApi v0.0.5/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=
|
github.com/liquidweb/go-lwApi v0.0.5/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=
|
||||||
|
|
2
main.go
2
main.go
|
@ -54,7 +54,7 @@ func prog(state overseer.State) {
|
||||||
}
|
}
|
||||||
|
|
||||||
s := gocron.NewScheduler(time.UTC)
|
s := gocron.NewScheduler(time.UTC)
|
||||||
job, err := s.Every(1).Hour().SingletonMode().Do(cert.AutoCert)
|
job, err := s.Every(1).Minute().SingletonMode().Do(cert.AutoObtain)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("AutoCert Job: %v, Err: %v\n", job, err)
|
log.Fatalf("AutoCert Job: %v, Err: %v\n", job, err)
|
||||||
|
|
|
@ -87,8 +87,6 @@ func IssueCert(c *gin.Context) {
|
||||||
|
|
||||||
go cert.IssueCert(buffer.ServerName, logChan, errChan)
|
go cert.IssueCert(buffer.ServerName, logChan, errChan)
|
||||||
|
|
||||||
domain := strings.Join(buffer.ServerName, "_")
|
|
||||||
|
|
||||||
go handleIssueCertLogChan(ws, logChan)
|
go handleIssueCertLogChan(ws, logChan)
|
||||||
|
|
||||||
// block, unless errChan closed
|
// block, unless errChan closed
|
||||||
|
@ -110,22 +108,29 @@ func IssueCert(c *gin.Context) {
|
||||||
|
|
||||||
close(logChan)
|
close(logChan)
|
||||||
|
|
||||||
sslCertificatePath := nginx.GetConfPath("ssl", domain, "fullchain.cer")
|
certDirName := strings.Join(buffer.ServerName, "_")
|
||||||
sslCertificateKeyPath := nginx.GetConfPath("ssl", domain, "private.key")
|
sslCertificatePath := nginx.GetConfPath("ssl", certDirName, "fullchain.cer")
|
||||||
|
sslCertificateKeyPath := nginx.GetConfPath("ssl", certDirName, "private.key")
|
||||||
|
|
||||||
certModel, err := model.FirstOrCreateCert(domain)
|
certModel, err := model.FirstOrCreateCert(c.Param("name"))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = certModel.Updates(&model.Cert{
|
err = certModel.Updates(&model.Cert{
|
||||||
|
Domains: buffer.ServerName,
|
||||||
SSLCertificatePath: sslCertificatePath,
|
SSLCertificatePath: sslCertificatePath,
|
||||||
SSLCertificateKeyPath: sslCertificateKeyPath,
|
SSLCertificateKeyPath: sslCertificateKeyPath,
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
|
err = ws.WriteJSON(IssueCertResponse{
|
||||||
|
Status: Error,
|
||||||
|
Message: err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = ws.WriteJSON(IssueCertResponse{
|
err = ws.WriteJSON(IssueCertResponse{
|
||||||
|
@ -150,9 +155,9 @@ func GetCertList(c *gin.Context) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
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"`
|
||||||
|
@ -202,13 +207,12 @@ func GetCert(c *gin.Context) {
|
||||||
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"`
|
||||||
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"`
|
||||||
|
@ -217,19 +221,13 @@ func AddCert(c *gin.Context) {
|
||||||
if !BindAndValid(c, &json) {
|
if !BindAndValid(c, &json) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
certModel, err := model.FirstOrCreateCert(json.Domain)
|
certModel := &model.Cert{
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
ErrHandler(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = certModel.Updates(&model.Cert{
|
|
||||||
Name: json.Name,
|
Name: json.Name,
|
||||||
Domain: json.Domain,
|
|
||||||
SSLCertificatePath: json.SSLCertificatePath,
|
SSLCertificatePath: json.SSLCertificatePath,
|
||||||
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
|
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
|
||||||
})
|
}
|
||||||
|
|
||||||
|
err := certModel.Insert()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ErrHandler(c, err)
|
ErrHandler(c, err)
|
||||||
|
@ -291,7 +289,6 @@ func ModifyCert(c *gin.Context) {
|
||||||
|
|
||||||
err = certModel.Updates(&model.Cert{
|
err = certModel.Updates(&model.Cert{
|
||||||
Name: json.Name,
|
Name: json.Name,
|
||||||
Domain: json.Domain,
|
|
||||||
SSLCertificatePath: json.SSLCertificatePath,
|
SSLCertificatePath: json.SSLCertificatePath,
|
||||||
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
|
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
|
||||||
})
|
})
|
||||||
|
|
|
@ -1,435 +1,426 @@
|
||||||
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)
|
||||||
var serverName string
|
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 == "server_name" {
|
pubKey, err := cert.GetCertInfo(directive.Params)
|
||||||
serverName = strings.ReplaceAll(directive.Params, " ", "_")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if directive.Directive == "ssl_certificate" {
|
if err != nil {
|
||||||
|
log.Println("Failed to get certificate information", err)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
pubKey, err := cert.GetCertInfo(directive.Params)
|
certInfoMap[serverIdx] = CertificateInfo{
|
||||||
|
SubjectName: pubKey.Subject.CommonName,
|
||||||
|
IssuerName: pubKey.Issuer.CommonName,
|
||||||
|
NotAfter: pubKey.NotAfter,
|
||||||
|
NotBefore: pubKey.NotBefore,
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
break
|
||||||
log.Println("Failed to get certificate information", err)
|
}
|
||||||
break
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
certInfoMap[serverIdx] = CertificateInfo{
|
certModel, _ := model.FirstCert(name)
|
||||||
SubjectName: pubKey.Subject.CommonName,
|
|
||||||
IssuerName: pubKey.Issuer.CommonName,
|
|
||||||
NotAfter: pubKey.NotAfter,
|
|
||||||
NotBefore: pubKey.NotBefore,
|
|
||||||
}
|
|
||||||
|
|
||||||
break
|
c.Set("maybe_error", "nginx_config_syntax_error")
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
certModel, _ := model.FirstCert(serverName)
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"enabled": enabled,
|
||||||
c.Set("maybe_error", "nginx_config_syntax_error")
|
"name": name,
|
||||||
|
"config": config.FmtCode(),
|
||||||
c.JSON(http.StatusOK, gin.H{
|
"tokenized": config,
|
||||||
"enabled": enabled,
|
"auto_cert": certModel.AutoCert == model.AutoCertEnabled,
|
||||||
"name": name,
|
"cert_info": certInfoMap,
|
||||||
"config": config.FmtCode(),
|
})
|
||||||
"tokenized": config,
|
|
||||||
"auto_cert": certModel.AutoCert == model.AutoCertEnabled,
|
|
||||||
"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{Domain: 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{Domain: 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) {
|
||||||
domain := c.Param("domain")
|
name := c.Param("name")
|
||||||
domain = strings.ReplaceAll(domain, " ", "_")
|
certModel, err := model.FirstOrCreateCert(name)
|
||||||
certModel, err := model.FirstOrCreateCert(domain)
|
|
||||||
|
|
||||||
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.AutoCertEnabled,
|
AutoCert: model.AutoCertEnabled,
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ErrHandler(c, err)
|
ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, certModel)
|
c.JSON(http.StatusOK, certModel)
|
||||||
}
|
}
|
||||||
|
|
||||||
func RemoveDomainFromAutoCert(c *gin.Context) {
|
func RemoveDomainFromAutoCert(c *gin.Context) {
|
||||||
domain := c.Param("domain")
|
name := c.Param("name")
|
||||||
domain = strings.ReplaceAll(domain, " ", "_")
|
certModel := model.Cert{
|
||||||
certModel := model.Cert{
|
Filename: name,
|
||||||
Domain: domain,
|
}
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,6 +2,7 @@ package model
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
||||||
|
"github.com/lib/pq"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -10,28 +11,35 @@ const (
|
||||||
AutoCertDisabled = -1
|
AutoCertDisabled = -1
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type CertDomains []string
|
||||||
|
|
||||||
type Cert struct {
|
type Cert struct {
|
||||||
Model
|
Model
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Domain string `json:"domain"`
|
Domains pq.StringArray `json:"domains" gorm:"type:text[]"`
|
||||||
SSLCertificatePath string `json:"ssl_certificate_path"`
|
Filename string `json:"filename"`
|
||||||
SSLCertificateKeyPath string `json:"ssl_certificate_key_path"`
|
SSLCertificatePath string `json:"ssl_certificate_path"`
|
||||||
AutoCert int `json:"auto_cert"`
|
SSLCertificateKeyPath string `json:"ssl_certificate_key_path"`
|
||||||
|
AutoCert int `json:"auto_cert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func FirstCert(domain string) (c Cert, err error) {
|
func FirstCert(confName string) (c Cert, err error) {
|
||||||
err = db.First(&c, &Cert{
|
err = db.First(&c, &Cert{
|
||||||
Domain: domain,
|
Filename: confName,
|
||||||
}).Error
|
}).Error
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func FirstOrCreateCert(domain string) (c Cert, err error) {
|
func FirstOrCreateCert(confName string) (c Cert, err error) {
|
||||||
err = db.FirstOrCreate(&c, &Cert{Domain: domain}).Error
|
err = db.FirstOrCreate(&c, &Cert{Filename: confName}).Error
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Cert) Insert() 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)
|
||||||
|
@ -49,7 +57,7 @@ func GetAutoCertList() (c []Cert) {
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, v := range t {
|
for _, v := range t {
|
||||||
if enabledConfigMap[v.Domain] == true {
|
if enabledConfigMap[v.Filename] == true {
|
||||||
c = append(c, v)
|
c = append(c, v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -76,9 +84,9 @@ func FirstCertByID(id int) (c Cert, err error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Cert) Updates(n *Cert) error {
|
func (c *Cert) Updates(n *Cert) error {
|
||||||
return db.Model(c).Updates(n).Error
|
return db.Model(&Cert{}).Where("filename", c.Filename).Updates(n).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Cert) Remove() error {
|
func (c *Cert) Remove() error {
|
||||||
return db.Where("domain", c.Domain).Delete(c).Error
|
return db.Where("filename", c.Filename).Delete(c).Error
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,6 @@ package cert
|
||||||
import (
|
import (
|
||||||
"github.com/0xJacky/Nginx-UI/server/model"
|
"github.com/0xJacky/Nginx-UI/server/model"
|
||||||
"log"
|
"log"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -19,7 +18,7 @@ func handleIssueCertLogChan(logChan chan string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func AutoCert() {
|
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)
|
||||||
|
@ -27,19 +26,12 @@ func AutoCert() {
|
||||||
}()
|
}()
|
||||||
log.Println("[AutoCert] Start")
|
log.Println("[AutoCert] Start")
|
||||||
autoCertList := model.GetAutoCertList()
|
autoCertList := model.GetAutoCertList()
|
||||||
for i := range autoCertList {
|
for _, certModel := range autoCertList {
|
||||||
domain := autoCertList[i].Domain
|
confName := certModel.Filename
|
||||||
|
|
||||||
certModel, err := model.FirstCert(domain)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Println("[AutoCert] Error get certificate from database", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if certModel.SSLCertificatePath == "" {
|
if certModel.SSLCertificatePath == "" {
|
||||||
log.Println("[AutoCert] Error ssl_certificate_path is empty, " +
|
log.Println("[AutoCert] Error ssl_certificate_path is empty, " +
|
||||||
"try to reopen auto-cert for this domain:" + domain)
|
"try to reopen auto-cert for this config:" + confName)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -49,16 +41,17 @@ func AutoCert() {
|
||||||
// Get certificate info error, ignore this domain
|
// Get certificate info error, ignore this domain
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// before 1 mo
|
// every week
|
||||||
if time.Now().Before(cert.NotBefore.AddDate(0, 1, 0)) {
|
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(strings.Split(domain, "_"), logChan, errChan)
|
go IssueCert(certModel.Domains, logChan, errChan)
|
||||||
|
|
||||||
go handleIssueCertLogChan(logChan)
|
go handleIssueCertLogChan(logChan)
|
||||||
|
|
||||||
|
@ -69,4 +62,5 @@ func AutoCert() {
|
||||||
|
|
||||||
close(logChan)
|
close(logChan)
|
||||||
}
|
}
|
||||||
|
log.Println("[AutoCert] End")
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,148 +1,155 @@
|
||||||
package cert
|
package cert
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto"
|
"crypto"
|
||||||
"crypto/ecdsa"
|
"crypto/ecdsa"
|
||||||
"crypto/elliptic"
|
"crypto/elliptic"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
"crypto/tls"
|
||||||
"github.com/0xJacky/Nginx-UI/server/settings"
|
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
||||||
"github.com/go-acme/lego/v4/certcrypto"
|
"github.com/0xJacky/Nginx-UI/server/settings"
|
||||||
"github.com/go-acme/lego/v4/certificate"
|
"github.com/go-acme/lego/v4/certcrypto"
|
||||||
"github.com/go-acme/lego/v4/challenge/http01"
|
"github.com/go-acme/lego/v4/certificate"
|
||||||
"github.com/go-acme/lego/v4/lego"
|
"github.com/go-acme/lego/v4/challenge/http01"
|
||||||
"github.com/go-acme/lego/v4/registration"
|
"github.com/go-acme/lego/v4/lego"
|
||||||
"github.com/pkg/errors"
|
"github.com/go-acme/lego/v4/registration"
|
||||||
"log"
|
"github.com/pkg/errors"
|
||||||
"os"
|
"log"
|
||||||
"path/filepath"
|
"net/http"
|
||||||
"strings"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MyUser You'll need a user or account type that implements acme.User
|
// MyUser You'll need a user or account type that implements acme.User
|
||||||
type MyUser struct {
|
type MyUser struct {
|
||||||
Email string
|
Email string
|
||||||
Registration *registration.Resource
|
Registration *registration.Resource
|
||||||
key crypto.PrivateKey
|
key crypto.PrivateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *MyUser) GetEmail() string {
|
func (u *MyUser) GetEmail() string {
|
||||||
return u.Email
|
return u.Email
|
||||||
}
|
}
|
||||||
func (u *MyUser) GetRegistration() *registration.Resource {
|
func (u *MyUser) GetRegistration() *registration.Resource {
|
||||||
return u.Registration
|
return u.Registration
|
||||||
}
|
}
|
||||||
func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
|
func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
|
||||||
return u.key
|
return u.key
|
||||||
}
|
}
|
||||||
|
|
||||||
func IssueCert(domain []string, logChan chan string, errChan chan error) {
|
func IssueCert(domain []string, logChan chan string, errChan chan error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := recover(); err != nil {
|
if err := recover(); err != nil {
|
||||||
log.Println("Issue Cert recover", err)
|
log.Println("Issue Cert recover", err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Create a user. New accounts need an email and private key to start.
|
// Create a user. New accounts need an email and private key to start.
|
||||||
logChan <- "Generating private key for registering account"
|
logChan <- "Generating private key for registering account"
|
||||||
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errChan <- errors.Wrap(err, "issue cert generate key error")
|
errChan <- errors.Wrap(err, "issue cert generate key error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
logChan <- "Preparing lego configurations"
|
logChan <- "Preparing lego configurations"
|
||||||
myUser := MyUser{
|
myUser := MyUser{
|
||||||
Email: settings.ServerSettings.Email,
|
Email: settings.ServerSettings.Email,
|
||||||
key: privateKey,
|
key: privateKey,
|
||||||
}
|
}
|
||||||
|
|
||||||
config := lego.NewConfig(&myUser)
|
config := lego.NewConfig(&myUser)
|
||||||
|
|
||||||
if settings.ServerSettings.Demo {
|
if settings.ServerSettings.Demo {
|
||||||
config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||||
}
|
}
|
||||||
|
|
||||||
if settings.ServerSettings.CADir != "" {
|
if settings.ServerSettings.CADir != "" {
|
||||||
config.CADirURL = settings.ServerSettings.CADir
|
config.CADirURL = settings.ServerSettings.CADir
|
||||||
}
|
if config.HTTPClient != nil {
|
||||||
|
config.HTTPClient.Transport = &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
config.Certificate.KeyType = certcrypto.RSA2048
|
config.Certificate.KeyType = certcrypto.RSA2048
|
||||||
|
|
||||||
logChan <- "Creating client facilitates communication with the CA server"
|
logChan <- "Creating client facilitates communication with the CA server"
|
||||||
// A client facilitates communication with the CA server.
|
// A client facilitates communication with the CA server.
|
||||||
client, err := lego.NewClient(config)
|
client, err := lego.NewClient(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errChan <- errors.Wrap(err, "issue cert new client error")
|
errChan <- errors.Wrap(err, "issue cert new client error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
logChan <- "Using HTTP01 challenge provider"
|
logChan <- "Using HTTP01 challenge provider"
|
||||||
err = client.Challenge.SetHTTP01Provider(
|
err = client.Challenge.SetHTTP01Provider(
|
||||||
http01.NewProviderServer("",
|
http01.NewProviderServer("",
|
||||||
settings.ServerSettings.HTTPChallengePort,
|
settings.ServerSettings.HTTPChallengePort,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errChan <- errors.Wrap(err, "issue cert challenge fail")
|
errChan <- errors.Wrap(err, "issue cert challenge fail")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// New users will need to register
|
// New users will need to register
|
||||||
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, "issue cert register fail")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
myUser.Registration = reg
|
myUser.Registration = reg
|
||||||
|
|
||||||
request := certificate.ObtainRequest{
|
request := certificate.ObtainRequest{
|
||||||
Domains: domain,
|
Domains: domain,
|
||||||
Bundle: true,
|
Bundle: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
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, "issue cert fail to obtain")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
name := strings.Join(domain, "_")
|
name := strings.Join(domain, "_")
|
||||||
saveDir := nginx.GetConfPath("ssl/" + name)
|
saveDir := nginx.GetConfPath("ssl/" + name)
|
||||||
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, "issue cert fail to create")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Each certificate comes back with the cert bytes, the bytes of the client's
|
// Each certificate comes back with the cert bytes, the bytes of the client's
|
||||||
// private key, and a certificate URL. SAVE THESE TO DISK.
|
// private key, and a certificate URL. SAVE THESE TO DISK.
|
||||||
logChan <- "Writing certificate to disk"
|
logChan <- "Writing certificate to disk"
|
||||||
err = os.WriteFile(filepath.Join(saveDir, "fullchain.cer"),
|
err = os.WriteFile(filepath.Join(saveDir, "fullchain.cer"),
|
||||||
certificates.Certificate, 0644)
|
certificates.Certificate, 0644)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errChan <- errors.Wrap(err, "error issue cert write fullchain.cer")
|
errChan <- errors.Wrap(err, "error issue cert write fullchain.cer")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
logChan <- "Writing certificate private key to disk"
|
logChan <- "Writing certificate private key to disk"
|
||||||
err = os.WriteFile(filepath.Join(saveDir, "private.key"),
|
err = os.WriteFile(filepath.Join(saveDir, "private.key"),
|
||||||
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, "error issue cert write key")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
close(errChan)
|
close(errChan)
|
||||||
logChan <- "Reloading nginx"
|
logChan <- "Reloading nginx"
|
||||||
|
|
||||||
nginx.Reload()
|
nginx.Reload()
|
||||||
|
|
||||||
logChan <- "Finished"
|
logChan <- "Finished"
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,61 +1,64 @@
|
||||||
package nginx
|
package nginx
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/tufanbarisyildirim/gonginx"
|
"github.com/tufanbarisyildirim/gonginx"
|
||||||
"strings"
|
"path"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
type NgxConfig struct {
|
type NgxConfig struct {
|
||||||
FileName string `json:"file_name"`
|
FileName string `json:"file_name"`
|
||||||
Upstreams []*NgxUpstream `json:"upstreams"`
|
Name string `json:"name"`
|
||||||
Servers []*NgxServer `json:"servers"`
|
Upstreams []*NgxUpstream `json:"upstreams"`
|
||||||
Custom string `json:"custom"`
|
Servers []*NgxServer `json:"servers"`
|
||||||
c *gonginx.Config
|
Custom string `json:"custom"`
|
||||||
|
c *gonginx.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
type NgxServer struct {
|
type NgxServer struct {
|
||||||
Directives []*NgxDirective `json:"directives"`
|
Directives []*NgxDirective `json:"directives"`
|
||||||
Locations []*NgxLocation `json:"locations"`
|
Locations []*NgxLocation `json:"locations"`
|
||||||
Comments string `json:"comments"`
|
Comments string `json:"comments"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type NgxUpstream struct {
|
type NgxUpstream struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Directives []*NgxDirective `json:"directives"`
|
Directives []*NgxDirective `json:"directives"`
|
||||||
Comments string `json:"comments"`
|
Comments string `json:"comments"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type NgxDirective struct {
|
type NgxDirective struct {
|
||||||
Directive string `json:"directive"`
|
Directive string `json:"directive"`
|
||||||
Params string `json:"params"`
|
Params string `json:"params"`
|
||||||
Comments string `json:"comments"`
|
Comments string `json:"comments"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type NgxLocation struct {
|
type NgxLocation struct {
|
||||||
Path string `json:"path"`
|
Path string `json:"path"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Comments string `json:"comments"`
|
Comments string `json:"comments"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *NgxDirective) Orig() string {
|
func (d *NgxDirective) Orig() string {
|
||||||
return d.Directive + " " + d.Params
|
return d.Directive + " " + d.Params
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *NgxDirective) TrimParams() {
|
func (d *NgxDirective) TrimParams() {
|
||||||
d.Params = strings.TrimRight(strings.TrimSpace(d.Params), ";")
|
d.Params = strings.TrimRight(strings.TrimSpace(d.Params), ";")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewNgxServer() *NgxServer {
|
func NewNgxServer() *NgxServer {
|
||||||
return &NgxServer{
|
return &NgxServer{
|
||||||
Locations: make([]*NgxLocation, 0),
|
Locations: make([]*NgxLocation, 0),
|
||||||
Directives: make([]*NgxDirective, 0),
|
Directives: make([]*NgxDirective, 0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewNgxConfig(filename string) *NgxConfig {
|
func NewNgxConfig(filename string) *NgxConfig {
|
||||||
return &NgxConfig{
|
return &NgxConfig{
|
||||||
FileName: filename,
|
FileName: filename,
|
||||||
Upstreams: make([]*NgxUpstream, 0),
|
Upstreams: make([]*NgxUpstream, 0),
|
||||||
}
|
Name: path.Base(filename),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -76,6 +76,7 @@ func InitRouter() *gin.Engine {
|
||||||
g.DELETE("domain/:name", api.DeleteDomain)
|
g.DELETE("domain/:name", api.DeleteDomain)
|
||||||
// duplicate site
|
// duplicate site
|
||||||
g.POST("domain/:name/duplicate", api.DuplicateSite)
|
g.POST("domain/:name/duplicate", api.DuplicateSite)
|
||||||
|
g.GET("domain/:name/cert", api.IssueCert)
|
||||||
|
|
||||||
g.GET("configs", api.GetConfigs)
|
g.GET("configs", api.GetConfigs)
|
||||||
g.GET("config/*name", api.GetConfig)
|
g.GET("config/*name", api.GetConfig)
|
||||||
|
@ -90,17 +91,15 @@ func InitRouter() *gin.Engine {
|
||||||
g.GET("template/blocks", api.GetTemplateBlockList)
|
g.GET("template/blocks", api.GetTemplateBlockList)
|
||||||
g.GET("template/block/:name", api.GetTemplateBlock)
|
g.GET("template/block/:name", api.GetTemplateBlock)
|
||||||
|
|
||||||
g.GET("cert/issue", api.IssueCert)
|
|
||||||
|
|
||||||
g.GET("certs", api.GetCertList)
|
g.GET("certs", api.GetCertList)
|
||||||
g.GET("cert/:id", api.GetCert)
|
g.GET("cert/:id", api.GetCert)
|
||||||
g.POST("cert", api.AddCert)
|
g.POST("cert", api.AddCert)
|
||||||
g.POST("cert/:id", api.ModifyCert)
|
g.POST("cert/:id", api.ModifyCert)
|
||||||
g.DELETE("cert/:id", api.RemoveCert)
|
g.DELETE("cert/:id", api.RemoveCert)
|
||||||
// Add domain to auto-renew cert list
|
// Add domain to auto-renew cert list
|
||||||
g.POST("auto_cert/:domain", api.AddDomainToAutoCert)
|
g.POST("auto_cert/:name", api.AddDomainToAutoCert)
|
||||||
// Delete domain from auto-renew cert list
|
// Delete domain from auto-renew cert list
|
||||||
g.DELETE("auto_cert/:domain", api.RemoveDomainFromAutoCert)
|
g.DELETE("auto_cert/:name", api.RemoveDomainFromAutoCert)
|
||||||
|
|
||||||
// pty
|
// pty
|
||||||
g.GET("pty", api.Pty)
|
g.GET("pty", api.Pty)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue