Backend: renew auth token if expired (#808)

* Backend: Added logic to renew auth token if expired

* Added nil check for err

* Added case if the err is nil

* Removed the case where data source tries to login at every request
This commit is contained in:
vignesh-reddy
2019-12-12 01:41:53 -06:00
committed by Alexander Zobnin
parent e8c5c0c3b9
commit 24fd0ff9ec

View File

@@ -119,16 +119,25 @@ func (ds *ZabbixDatasource) BuildResponse(result *simplejson.Json) (*datasource.
func (ds *ZabbixDatasource) ZabbixRequest(ctx context.Context, dsInfo *datasource.DatasourceInfo, method string, params *simplejson.Json) (*simplejson.Json, error) {
zabbixUrl := dsInfo.GetUrl()
// Authenticate first
var result *simplejson.Json
var err error
for attempt := 0; attempt <= 3; attempt++ {
if zabbixAuth == "" {
auth, err := ds.loginWithDs(ctx, dsInfo)
// Authenticate
zabbixAuth, err = ds.loginWithDs(ctx, dsInfo)
if err != nil {
return nil, err
}
zabbixAuth = auth
}
return ds.zabbixAPIRequest(ctx, zabbixUrl, method, params, zabbixAuth)
result, err = ds.zabbixAPIRequest(ctx, zabbixUrl, method, params, zabbixAuth)
if err == nil || (err != nil && !isNotAuthorized(err.Error())) {
break
} else {
zabbixAuth = ""
}
}
return result, err
}
func (ds *ZabbixDatasource) loginWithDs(ctx context.Context, dsInfo *datasource.DatasourceInfo) (string, error) {
@@ -250,3 +259,9 @@ func makeHttpRequest(ctx context.Context, req *http.Request) ([]byte, error) {
}
return body, nil
}
func isNotAuthorized(message string) bool {
return message == "Session terminated, re-login, please." ||
message == "Not authorised." ||
message == "Not authorized."
}