Skip to content

Commit

Permalink
re-login if we are told 401
Browse files Browse the repository at this point in the history
  • Loading branch information
asymmetricia committed Sep 30, 2020
1 parent a3687c2 commit 427ff0e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion types/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func NewMatchers(in []string) ([]*Matcher, error) {
if len(name) >= 2 && name[0] == '/' && name[len(name)-1] == '/' {
re, err := regexp.Compile(`(?i:` + name[1:len(name)-1] + `)`)
if err != nil {
return nil, fmt.Errorf("compiling %q as regexp: %w", err)
return nil, fmt.Errorf("compiling %q as regexp: %w", name[1:len(name)-1], err)
}
ret = append(ret, &Matcher{Regexp: re})
} else {
Expand Down
24 changes: 24 additions & 0 deletions types/unifi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package types

import (
"fmt"
"strings"
"time"

"github.com/rs/zerolog"
Expand All @@ -24,9 +25,12 @@ type Unifi struct {
seenClients map[string]string
unifiClient *unifi.Unifi
ch chan Client
loginBackoff time.Duration
}

func (u *Unifi) Login(log zerolog.Logger) error {
time.Sleep(u.loginBackoff)

var err error
u.unifiClient, err = unifi.NewUnifi(&unifi.Config{
User: u.Username,
Expand All @@ -41,6 +45,14 @@ func (u *Unifi) Login(log zerolog.Logger) error {
},
})

if err == nil {
u.loginBackoff = 0
} else if u.loginBackoff == 0 {
u.loginBackoff = time.Second
} else if u.loginBackoff < time.Minute {
u.loginBackoff *= 2
}

return err
}

Expand Down Expand Up @@ -104,11 +116,23 @@ func NewUnifi(username, password, host string, port int, verifyTls bool,

func (u *Unifi) clients(log zerolog.Logger) ([]Client, error) {
sites, err := u.unifiClient.GetSites()
if err != nil && strings.Contains(err.Error(), "code from server 401") {
err = u.Login(log)
if err == nil {
sites, err = u.unifiClient.GetSites()
}
}
if err != nil {
return nil, fmt.Errorf("getting sites: %w", err)
}

unifiClients, err := u.unifiClient.GetClients(sites)
if err != nil && strings.Contains(err.Error(), "code from server 401") {
err = u.Login(log)
if err == nil {
unifiClients, err = u.unifiClient.GetClients(sites)
}
}
if err != nil {
return nil, fmt.Errorf("getting clients: %w", err)
}
Expand Down

0 comments on commit 427ff0e

Please sign in to comment.