From a4fa8a48c878881aa079af2ad65483528e5968ec Mon Sep 17 00:00:00 2001 From: Farhan Khan Date: Sat, 5 Dec 2020 23:47:12 -0500 Subject: [PATCH] added authentication --- poll/instance.go | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/poll/instance.go b/poll/instance.go index 1b1352c..910ffc5 100644 --- a/poll/instance.go +++ b/poll/instance.go @@ -23,6 +23,34 @@ func PollMastodonPleroma(endpoint string, reportPostChan chan ReportPost) { http_client := http.Client{} parsing_error := 0 unprocess_error := 0 + use_auth := false + + var last_refresh int64 + var client_id string + var client_secret string + var oauthData OAuth + var err error + + for _, extaccount := range settings.Externalaccounts { + if extaccount.Endpoint == endpoint { + use_auth = true + register_client(endpoint, &http_client) + + client_id, client_secret, err = register_client(endpoint, &http_client); + if err != nil { + log.Fatal("Unable to register client: ", err) + } + + oauthData, err = oauth_login(endpoint, extaccount.Username, extaccount.Password, client_id, client_secret) + if err != nil { + log.Print("Unable to login: ", err) + return + } + last_refresh = time.Now().Unix() + + } + } + for { ri_mutex.Lock() @@ -30,8 +58,26 @@ func PollMastodonPleroma(endpoint string, reportPostChan chan ReportPost) { ri_mutex.Unlock() api_timeline := "https://" + endpoint + "/api/v1/timelines/public?limit=40&since_id=" + min_id - resp, err := http_client.Get(api_timeline) + req, err := http.NewRequest("GET", api_timeline, nil) + if err != nil { + log.Print("Unable to create new request") + return + } + + if use_auth == true { + if time.Now().Unix() > last_refresh + oauthData.Expires_in { + oauthData, err = oauth_refresh(endpoint, client_id, client_secret, oauthData.Refresh_token) + if err != nil { + log.Print("Unable to refresh: ", err) + return + } + last_refresh = time.Now().Unix() + } + req.Header.Add("Authorization", oauthData.Access_token) + } + m.LastRun = time.Now().Format(time.RFC3339) + resp, err := http_client.Do(req) if err != nil { ri_mutex.Lock() m.Status = CLIENT_ISSUE