Support ntfy auth

This commit is contained in:
Thorben Günther 2022-10-10 02:42:13 +02:00
parent e02a3d9af1
commit 93d004925b
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED
2 changed files with 38 additions and 6 deletions

View file

@ -9,7 +9,13 @@ import (
type config struct { type config struct {
HTTPAddress string HTTPAddress string
LogLevel string LogLevel string
Topic string ntfy ntfyConfig
}
type ntfyConfig struct {
Topic string
User string
Password string
} }
func readConfig(path string) (*config, error) { func readConfig(path string) (*config, error) {
@ -37,13 +43,32 @@ func readConfig(path string) (*config, error) {
} }
} }
d = cfg.Get("topic") ntfyDir := cfg.Get("ntfy")
if d == nil { if ntfyDir == nil {
return nil, fmt.Errorf("%q missing from config", "topic") return nil, fmt.Errorf("%q directive missing", "ntfy")
} }
if err := d.ParseParams(&config.Topic); err != nil {
d = ntfyDir.Children.Get("topic")
if d == nil {
return nil, fmt.Errorf("%q missing from %q directive", "topic", "ntfy")
}
if err := d.ParseParams(&config.ntfy.Topic); err != nil {
return nil, err return nil, err
} }
d = ntfyDir.Children.Get("user")
if d != nil {
if err := d.ParseParams(&config.ntfy.User); err != nil {
return nil, err
}
}
d = ntfyDir.Children.Get("password")
if d != nil {
if err := d.ParseParams(&config.ntfy.Password); err != nil {
return nil, err
}
}
return config, nil return config, nil
} }

View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/base64"
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
@ -83,11 +84,17 @@ func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) {
} }
client := &http.Client{Timeout: time.Second * 3} client := &http.Client{Timeout: time.Second * 3}
req, err := http.NewRequest(http.MethodPost, rcv.cfg.Topic, strings.NewReader(body)) req, err := http.NewRequest(http.MethodPost, rcv.cfg.ntfy.Topic, strings.NewReader(body))
if err != nil { if err != nil {
rcv.logger.Error(err) rcv.logger.Error(err)
} }
// Basic auth
if rcv.cfg.ntfy.Password != "" && rcv.cfg.ntfy.User != "" {
auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", rcv.cfg.ntfy.User, rcv.cfg.ntfy.Password)))
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", auth))
}
req.Header.Set("X-Title", title) req.Header.Set("X-Title", title)
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {