Skip to content

Commit

Permalink
Support basic authorization (#149)
Browse files Browse the repository at this point in the history
  • Loading branch information
andig authored May 14, 2020
1 parent f45abfe commit 3147596
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,10 @@ uri: https://volkszaehler/api/data/<uuid>.json?from=now
method: GET # default HTTP method
headers:
- content-type: application/json
auth: # basic authorization
type: basic
user: foo
password: bar
insecure: false # set to true to trust self-signed certificates
jq: .data.tuples[0][1] # parse response json
scale: 0.001 # floating point factor applied to result, e.g. for kW to W conversion
Expand Down
25 changes: 25 additions & 0 deletions provider/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package provider

import (
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"math"
Expand All @@ -25,6 +26,21 @@ type HTTP struct {
jq *gojq.Query
}

// Auth is the authorization config
type Auth struct {
Type, User, Password string
}

// NewAuth creates authorization headers from config
func NewAuth(log *util.Logger, auth Auth, headers map[string]string) {
if strings.ToLower(auth.Type) != "basic" {
log.FATAL.Fatalf("config: unsupported auth type: %s", auth.Type)
}

basicAuth := auth.User + ":" + auth.Password
headers["Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(basicAuth))
}

// NewHTTPProviderFromConfig creates a HTTP provider
func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) *HTTP {
cc := struct {
Expand All @@ -34,6 +50,7 @@ func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) *
Jq string
Scale float64
Insecure bool
Auth Auth
}{}
util.DecodeOther(log, other, &cc)

Expand All @@ -49,6 +66,14 @@ func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) *
scale: cc.Scale,
}

// handle basic auth
if cc.Auth.Type != "" {
if p.headers == nil {
p.headers = make(map[string]string)
}
NewAuth(log, cc.Auth, p.headers)
}

// ignore the self signed certificate
if cc.Insecure {
customTransport := http.DefaultTransport.(*http.Transport).Clone()
Expand Down

0 comments on commit 3147596

Please sign in to comment.