Browse Source

WIP: Add option for HTTP Basic Authentication for nodes

node_auth
codesoap 2 months ago
parent
commit
298ce14b20
  1. 17
      cmd/atto/main.go
  2. 25
      node_auth.go
  3. 10
      util.go

17
cmd/atto/main.go

@ -38,6 +38,13 @@ the send subcommand sends funds to an address. @@ -38,6 +38,13 @@ the send subcommand sends funds to an address.
ACCOUNT_INDEX is an optional parameter, which must be a number between 0
and 4,294,967,295. It allows you to use multiple accounts derived from
the same seed. By default the account with index 0 is chosen.
Environment:
ATTO_BASIC_AUTH_USERNAME The username for HTTP Basic Authentication.
If set, HTTP Basic Authentication will be
used when making requests to the node.
ATTO_BASIC_AUTH_PASSWORD The password to use for HTTP Basic
Authentication.
`
var accountIndexFlag uint
@ -71,6 +78,16 @@ func init() { @@ -71,6 +78,16 @@ func init() {
flag.Usage()
os.Exit(1)
}
setUpNodeAuthentication()
}
func setUpNodeAuthentication() {
if os.Getenv("ATTO_BASIC_AUTH_USERNAME") != "" {
atto.DefaultNodeAuthenticator = atto.NodeBasicAuth{
Username: os.Getenv("ATTO_BASIC_AUTH_USERNAME"),
Password: os.Getenv("ATTO_BASIC_AUTH_PASSWORD"),
}
}
}
func main() {

25
node_auth.go

@ -0,0 +1,25 @@ @@ -0,0 +1,25 @@
package atto
import "net/http"
// The DefaultNodeAuthenticator is the NodeAuthenticator that is used to
// authenticate all HTTP requests that are sent to a node. If it is nil,
// no authentication will be performed.
var DefaultNodeAuthenticator NodeAuthenticator
// A NodeAuthenticator can add authentication credentials to an HTTP
// request.
type NodeAuthenticator interface {
Authenticate(request *http.Request)
}
// NodeBasicAuth holds HTTP Basic Authentication credentials.
type NodeBasicAuth struct {
Username string // The HTTP Basic Authentication username.
Password string // The HTTP Basic Authentication password.
}
// Authenticate adds the HTTP Basic Authentication headers to request.
func (auth NodeBasicAuth) Authenticate(request *http.Request) {
request.SetBasicAuth(auth.Username, auth.Password)
}

10
util.go

@ -107,7 +107,15 @@ func revertBytes(in []byte) []byte { @@ -107,7 +107,15 @@ func revertBytes(in []byte) []byte {
}
func doRPC(requestBody, node string) (responseBytes []byte, err error) {
resp, err := http.Post(node, "application/json", strings.NewReader(requestBody))
req, err := http.NewRequest("POST", node, strings.NewReader(requestBody))
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
if DefaultNodeAuthenticator != nil {
DefaultNodeAuthenticator.Authenticate(req)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}

Loading…
Cancel
Save