Improve NATS

This commit is contained in:
Torjus Håkestad 2023-10-27 21:46:09 +02:00
parent 4afa9a01b6
commit 67716a883d
4 changed files with 44 additions and 14 deletions

1
go.mod
View File

@ -8,6 +8,7 @@ require (
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/google/uuid v1.3.1
github.com/nats-io/nats.go v1.31.0
github.com/nats-io/nkeys v0.4.5
github.com/pelletier/go-toml/v2 v2.1.0
github.com/urfave/cli/v2 v2.25.7
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.45.0

View File

@ -1,5 +1,8 @@
ListenAddr = ":8082"
NATSAddr = "nats:4222"
BaseSubject = "microfilm.auth.v1"
UserServiceBaseURL = "http://mf-users:8080"
[NATS]
Enabled = true
Addr = "nats://nats1:4222,nats://nats2:4222,nats://nats3:4222"
NKeySeed = "SUAOUHJPINF4CK6TSNZMRR5G4DKGW5S76XRNIYURPEISNMWXJIXSVWIO7Y"
Subject = "microfilm.auth.v1"

View File

@ -8,12 +8,19 @@ import (
type Config struct {
ListenAddr string `toml:"ListenAddr"`
NATSAddr string `toml:"NATSAddr"`
NATS *NATSConfig `toml:"NATS"`
BaseSubject string `toml:"BaseSubject"`
UserServiceBaseURL string `toml:"UserServiceBaseURL"`
}
type NATSConfig struct {
Enabled bool `toml:"Enabled"`
NKeySeed string `toml:"NKeySeed"`
Addr string `toml:"Addr"`
Subject string `toml:"Subject"`
}
func ConfigFromReader(r io.Reader) (*Config, error) {
decoder := toml.NewDecoder(r)
var c Config

View File

@ -20,6 +20,7 @@ import (
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/nats-io/nats.go"
"github.com/nats-io/nkeys"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
@ -72,7 +73,23 @@ func NewServer(config *Config) (*Server, error) {
srv.store = store.NewMemoryAuthStore()
conn, err := nats.Connect(config.NATSAddr)
if config.NATS.Enabled {
var opts []nats.Option
if config.NATS.NKeySeed != "" {
keys, err := nkeys.FromSeed([]byte(config.NATS.NKeySeed))
if err != nil {
return nil, err
}
pubkey, err := keys.PublicKey()
if err != nil {
return nil, err
}
srv.Logger.Debug("NATS enabled with NKeys", "pubkey", pubkey)
creds := nats.Nkey(pubkey, keys.Sign)
opts = append(opts, creds)
}
conn, err := nats.Connect(config.NATS.Addr, opts...)
if err != nil {
return nil, err
}
@ -82,6 +99,8 @@ func NewServer(config *Config) (*Server, error) {
}
srv.nats = encoded
}
srv.userClient = NewUserClient(config.UserServiceBaseURL)
// Generate keys