92 lines
2.1 KiB
Go
92 lines
2.1 KiB
Go
package api
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"scm/crt"
|
|
"scm/model"
|
|
"scm/utils"
|
|
)
|
|
|
|
func CreateCert(w http.ResponseWriter, r *http.Request) {
|
|
var requestData model.CreateCertRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&requestData); err != nil {
|
|
http.Error(w, "invalid JSON format", http.StatusBadRequest)
|
|
return
|
|
}
|
|
caCert, caKey, err := crt.LoadRootCertAndKey(
|
|
fmt.Sprintf(
|
|
"%s/%s/%s.crt",
|
|
os.Getenv("CERTS_PATH"),
|
|
"root",
|
|
"root",
|
|
),
|
|
fmt.Sprintf(
|
|
"%s/%s/%s.key",
|
|
os.Getenv("CERTS_PATH"),
|
|
"root",
|
|
"root",
|
|
),
|
|
requestData.CAKeyPassword,
|
|
)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
fmt.Println("error loading certificate and key:", err)
|
|
return
|
|
}
|
|
// TODO: Implement create certificate endpoint
|
|
serverKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
fmt.Println("error generating server key:", err)
|
|
return
|
|
}
|
|
serverCert, err := crt.CreateServerCert(caCert, caKey, serverKey, requestData)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
fmt.Println("error creating server certificate:", err)
|
|
return
|
|
}
|
|
err = utils.CheckExistsOrCreateDir(requestData.DNSNames[0])
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
err = crt.SavePEMFile(
|
|
fmt.Sprintf(
|
|
"%s/%s/%s.crt",
|
|
os.Getenv("CERTS_PATH"),
|
|
requestData.DNSNames[0],
|
|
requestData.DNSNames[0],
|
|
),
|
|
"CERTIFICATE",
|
|
serverCert,
|
|
)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
fmt.Println("error saving certificate:", err)
|
|
return
|
|
}
|
|
err = crt.SavePEMFile(
|
|
fmt.Sprintf(
|
|
"%s/%s/%s.key",
|
|
os.Getenv("CERTS_PATH"),
|
|
requestData.DNSNames[0],
|
|
requestData.DNSNames[0],
|
|
),
|
|
"RSA PRIVATE KEY",
|
|
x509.MarshalPKCS1PrivateKey(serverKey),
|
|
)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
fmt.Println("error saving private key:", err)
|
|
return
|
|
}
|
|
fmt.Fprintf(w, "%s", `{"status": "success", "message": "Certificate created successfully"}`)
|
|
}
|