@@ -22,7 +22,7 @@ import (
2222
2323type builder struct {
2424 fileOpts []func (* mir_config.MirConfig )
25- credentials * string
25+ credentialsFiles [] string
2626 deviceId * string
2727 deviceIdGenerator * IdGenerator
2828 deviceIdPrefix * IdPrefix
@@ -82,8 +82,28 @@ func (b builder) DeviceIdPrefix(p IdPrefix) builder {
8282 return b
8383}
8484
85- func (b builder ) UserCredentials (fullPath string ) builder {
86- b .credentials = & fullPath
85+ func (b builder ) UserCredentialsFile (fullPath string ) builder {
86+ b .credentialsFiles = append (b .credentialsFiles , fullPath )
87+ return b
88+ }
89+
90+ // Look for a user credentials file at those locations in order to authenticate:
91+ // - ./device.creds
92+ // - ~/.config/mir/device.creds
93+ // - /etc/mir/device.creds
94+ func (b builder ) DefaultUserCredentialsFile () builder {
95+ userHomeDir , err := os .UserHomeDir ()
96+ if err != nil {
97+ fmt .Println ("$HOME is not defined" )
98+ userHomeDir = "./"
99+ }
100+ xdgConfigHome := filepath .Join (userHomeDir , ".config" , "mir" , "device.creds" )
101+
102+ b .credentialsFiles = append (b .credentialsFiles ,
103+ "/etc/mir/device.creds" ,
104+ xdgConfigHome ,
105+ "./device.creds" ,
106+ )
87107 return b
88108}
89109
@@ -94,15 +114,12 @@ func (b builder) Target(t string) builder {
94114 return b
95115}
96116
97- // Use a configuration file to load the
98- // device_id and the target. Specifying those configs
99- // in the builder pattern have greater priority
100- // then loading from the config file.
101- // The file is loaded in folders:
102- // - ./device.yaml
103- // - ~/.config/mir/device.yaml
104- // - /etc/mir/device.yaml
105- // $HOME/.config/mir/device.[json|yaml]
117+ // Use a configuration file to load device configs.
118+ // Specifying those configs in the builder pattern have greater priority
119+ // then loading from the config file. The file is loaded in folders:
120+ // - ./device.yaml
121+ // - ~/.config/mir/device.yaml
122+ // - /etc/mir/device.yaml
106123func (b builder ) DefaultConfigFile () builder {
107124 format := mir_config .Yaml
108125 fileName := "device.yaml"
@@ -247,8 +264,17 @@ func (b builder) build(extraCfg any) (*Mir, error) {
247264 } else if cfg .Mir .Target == "" {
248265 cfg .Mir .Target = "nats://127.0.0.1:4222"
249266 }
250- if b .credentials != nil {
251- cfg .Mir .Credentials = * b .credentials
267+ // Add credential file path
268+ if cfg .Mir .Credentials != "" {
269+ b .credentialsFiles = append (b .credentialsFiles , cfg .Mir .Credentials )
270+ }
271+ // Look for first file to exist
272+ for i := len (b .credentialsFiles ) - 1 ; i >= 0 ; i -- {
273+ c := b .credentialsFiles [i ]
274+ if _ , err := os .Stat (c ); err == nil {
275+ cfg .Mir .Credentials = c
276+ break
277+ }
252278 }
253279 if b .logLevel != nil {
254280 cfg .Mir .LogLevel = b .logLevel .String ()
0 commit comments