Skip to content

Commit

Permalink
adds fritzbox session check and re-authenticate if nesessarry
Browse files Browse the repository at this point in the history
  • Loading branch information
tisba committed Oct 10, 2021
1 parent 6842df6 commit f6a443a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
26 changes: 26 additions & 0 deletions internal/fritzbox/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
"strings"
)

// PerformLogin performs a login and returns SessionInfo including
Expand Down Expand Up @@ -34,6 +35,31 @@ func (fb *FritzBox) PerformLogin(adminPassword string) error {
return nil
}

func (fb *FritzBox) CheckSession() (bool, error) {
client := fb.getHTTPClient()

requestBody := strings.NewReader("sid=" + fb.session.SID)

resp, err := client.Post(fb.Host+"/login_sid.lua?version=2", "application/x-www-form-urlencoded", requestBody)
if err != nil {
return false, err
}

body, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}
defer resp.Body.Close() // nolint: errcheck

var sessionInfo SessionInfo
err = xml.Unmarshal(body, &sessionInfo)
if err != nil {
return false, err
}

return sessionInfo.SID == fb.session.SID, nil
}

func fetchSessionInfo(client *http.Client, url string) (SessionInfo, error) {
resp, err := client.Get(url)
if err != nil {
Expand Down
13 changes: 13 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,19 @@ func main() {
config.certificateBundle = io.MultiReader(bytes.NewReader(cert.Certificate), bytes.NewReader(cert.PrivateKey))
}

sessionOk, err := fritz.CheckSession()
if err != nil {
log.Fatal(err)
}

if !sessionOk {
log.Println("Session expired, re-authenticating...")
err := fritz.PerformLogin(config.adminPassword)
if err != nil {
log.Fatal(err)
}
}

// Upload certificate and private key
status, response, err := fritz.UploadCertificate(config.certificateBundle)
if err != nil {
Expand Down

0 comments on commit f6a443a

Please sign in to comment.