97 lines
2.2 KiB
Go
97 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
|
|
webpush "github.com/SherClockHolmes/webpush-go"
|
|
"github.com/joho/godotenv"
|
|
)
|
|
|
|
func main() {
|
|
writeEnv := flag.Bool("write-env", false, "VAPID-Schlüssel direkt in eine .env-Datei schreiben")
|
|
envPath := flag.String("env", ".env", "Pfad der zu aktualisierenden .env-Datei")
|
|
flag.Parse()
|
|
|
|
_ = godotenv.Load()
|
|
|
|
privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
email := strings.TrimSpace(os.Getenv("ADMIN_EMAIL"))
|
|
if email == "" {
|
|
email = "admin@example.com"
|
|
}
|
|
|
|
values := map[string]string{
|
|
"VAPID_PUBLIC_KEY": publicKey,
|
|
"VAPID_PRIVATE_KEY": privateKey,
|
|
"VAPID_SUBSCRIBER": "mailto:" + email,
|
|
}
|
|
|
|
if *writeEnv {
|
|
if err := writeVAPIDEnv(*envPath, values); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Printf("VAPID-Konfiguration wurde in %s geschrieben.\n", *envPath)
|
|
return
|
|
}
|
|
|
|
fmt.Printf("VAPID_PUBLIC_KEY=%s\n", values["VAPID_PUBLIC_KEY"])
|
|
fmt.Printf("VAPID_PRIVATE_KEY=%s\n", values["VAPID_PRIVATE_KEY"])
|
|
fmt.Printf("VAPID_SUBSCRIBER=%s\n", values["VAPID_SUBSCRIBER"])
|
|
}
|
|
|
|
func writeVAPIDEnv(path string, values map[string]string) error {
|
|
content, err := os.ReadFile(path)
|
|
if err != nil && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
|
|
lines := []string{}
|
|
if len(content) > 0 {
|
|
lines = strings.Split(strings.ReplaceAll(string(content), "\r\n", "\n"), "\n")
|
|
}
|
|
|
|
for _, line := range lines {
|
|
key, value, found := strings.Cut(line, "=")
|
|
if !found {
|
|
continue
|
|
}
|
|
if (key == "VAPID_PUBLIC_KEY" || key == "VAPID_PRIVATE_KEY") &&
|
|
strings.TrimSpace(value) != "" {
|
|
return fmt.Errorf("in %s sind bereits VAPID-Schlüssel vorhanden", path)
|
|
}
|
|
}
|
|
|
|
updated := map[string]bool{}
|
|
for index, line := range lines {
|
|
key, _, found := strings.Cut(line, "=")
|
|
if !found {
|
|
continue
|
|
}
|
|
if value, ok := values[key]; ok {
|
|
lines[index] = key + "=" + value
|
|
updated[key] = true
|
|
}
|
|
}
|
|
|
|
for _, key := range []string{
|
|
"VAPID_PUBLIC_KEY",
|
|
"VAPID_PRIVATE_KEY",
|
|
"VAPID_SUBSCRIBER",
|
|
} {
|
|
if !updated[key] {
|
|
lines = append(lines, key+"="+values[key])
|
|
}
|
|
}
|
|
|
|
output := strings.TrimRight(strings.Join(lines, "\n"), "\n") + "\n"
|
|
return os.WriteFile(path, []byte(output), 0o600)
|
|
}
|