diff options
| author | jwijenbergh <jeroenwijenbergh@protonmail.com> | 2022-08-09 14:18:22 +0200 |
|---|---|---|
| committer | jwijenbergh <jeroenwijenbergh@protonmail.com> | 2022-08-09 14:18:22 +0200 |
| commit | 9c7d9958132bcea0aa5ff6ab4aaec67c73087408 (patch) | |
| tree | b3a85b1b340de7b8169542c32972a7f3dd2314aa | |
| parent | 0c6233ab691973859b6d636e6d9fdddd2a6acd5e (diff) | |
Refactor: Cleanup time calculations and usage
| -rw-r--r-- | internal/discovery/discovery.go | 15 | ||||
| -rw-r--r-- | internal/oauth/oauth.go | 15 | ||||
| -rw-r--r-- | internal/server/api.go | 19 | ||||
| -rw-r--r-- | internal/server/common.go | 24 | ||||
| -rw-r--r-- | internal/types/server.go | 5 | ||||
| -rw-r--r-- | internal/util/util.go | 5 |
6 files changed, 43 insertions, 40 deletions
diff --git a/internal/discovery/discovery.go b/internal/discovery/discovery.go index 24ed01c..d4cff41 100644 --- a/internal/discovery/discovery.go +++ b/internal/discovery/discovery.go @@ -3,6 +3,7 @@ package discovery import ( "encoding/json" "fmt" + "time" "github.com/jwijenbergh/eduvpn-common/internal/http" "github.com/jwijenbergh/eduvpn-common/internal/util" @@ -61,7 +62,7 @@ func getDiscoFile(jsonFile string, previousVersion uint64, structure interface{} // - [TODO] when the user tries to add new server AND the user did NOT yet choose an organization before; // - [TODO] when the authorization for the server associated with an already chosen organization is triggered, e.g. after expiry or revocation. func (discovery *Discovery) DetermineOrganizationsUpdate() bool { - return discovery.Organizations.Timestamp == 0 + return discovery.Organizations.Timestamp.IsZero() } func (discovery *Discovery) GetSecureLocationList() (string, error) { @@ -132,13 +133,13 @@ func (discovery *Discovery) GetSecureHomeArgs(orgID string) (*types.DiscoveryOrg // - The application MAY refresh the server_list.json periodically, e.g. once every hour. func (discovery *Discovery) DetermineServersUpdate() bool { // No servers, we should update - if discovery.Servers.Timestamp == 0 { + if discovery.Servers.Timestamp.IsZero() { return true } // 1 hour from the last update - should_update_time := discovery.Servers.Timestamp + 3600 - now := util.GenerateTimeSeconds() - if now >= should_update_time { + should_update_time := discovery.Servers.Timestamp.Add(1 * time.Hour) + now := util.GetCurrentTime() + if !now.Before(should_update_time) { return true } return false @@ -156,7 +157,7 @@ func (discovery *Discovery) GetOrganizationsList() (string, error) { return discovery.Organizations.RawString, &types.WrappedErrorMessage{Message: "failed getting organizations in Discovery", Err: bodyErr} } discovery.Organizations.RawString = body - discovery.Organizations.Timestamp = util.GenerateTimeSeconds() + discovery.Organizations.Timestamp = util.GetCurrentTime() return discovery.Organizations.RawString, nil } @@ -173,7 +174,7 @@ func (discovery *Discovery) GetServersList() (string, error) { } // Update servers timestamp discovery.Servers.RawString = body - discovery.Servers.Timestamp = util.GenerateTimeSeconds() + discovery.Servers.Timestamp = util.GetCurrentTime() return discovery.Servers.RawString, nil } diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index b1569e9..79f4ebf 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "net/url" + "time" "github.com/jwijenbergh/eduvpn-common/internal/fsm" httpw "github.com/jwijenbergh/eduvpn-common/internal/http" @@ -85,7 +86,7 @@ type OAuthToken struct { Refresh string `json:"refresh_token"` Type string `json:"token_type"` Expires int64 `json:"expires_in"` - ExpiredTimestamp int64 `json:"expires_in_timestamp"` + ExpiredTimestamp time.Time `json:"expires_in_timestamp"` } // Gets an authorized HTTP client by obtaining refresh and access tokens @@ -123,7 +124,7 @@ func (oauth *OAuth) getTokensWithAuthCode(authCode string) error { "content-type": {"application/x-www-form-urlencoded"}, } opts := &httpw.HTTPOptionalParams{Headers: headers, Body: data} - current_time := util.GenerateTimeSeconds() + current_time := util.GetCurrentTime() _, body, bodyErr := httpw.HTTPPostWithOpts(reqURL, opts) if bodyErr != nil { return &types.WrappedErrorMessage{Message: errorMessage, Err: bodyErr} @@ -137,15 +138,15 @@ func (oauth *OAuth) getTokensWithAuthCode(authCode string) error { return &types.WrappedErrorMessage{Message: errorMessage, Err: &httpw.HTTPParseJsonError{URL: reqURL, Body: string(body), Err: jsonErr}} } - tokenStructure.ExpiredTimestamp = current_time + tokenStructure.Expires + tokenStructure.ExpiredTimestamp = current_time.Add(time.Second * time.Duration(tokenStructure.Expires)) oauth.Token = tokenStructure return nil } func (oauth *OAuth) isTokensExpired() bool { expired_time := oauth.Token.ExpiredTimestamp - current_time := util.GenerateTimeSeconds() - return current_time >= expired_time + current_time := util.GetCurrentTime() + return !current_time.Before(expired_time) } // Get the access and refresh tokens with a previously received refresh token @@ -162,7 +163,7 @@ func (oauth *OAuth) getTokensWithRefresh() error { "content-type": {"application/x-www-form-urlencoded"}, } opts := &httpw.HTTPOptionalParams{Headers: headers, Body: data} - current_time := util.GenerateTimeSeconds() + current_time := util.GetCurrentTime() _, body, bodyErr := httpw.HTTPPostWithOpts(reqURL, opts) if bodyErr != nil { return &types.WrappedErrorMessage{Message: errorMessage, Err: bodyErr} @@ -175,7 +176,7 @@ func (oauth *OAuth) getTokensWithRefresh() error { return &types.WrappedErrorMessage{Message: errorMessage, Err: &httpw.HTTPParseJsonError{URL: reqURL, Body: string(body), Err: jsonErr}} } - tokenStructure.ExpiredTimestamp = current_time + tokenStructure.Expires + tokenStructure.ExpiredTimestamp = current_time.Add(time.Second * time.Duration(tokenStructure.Expires)) oauth.Token = tokenStructure return nil } diff --git a/internal/server/api.go b/internal/server/api.go index a3d8e31..9f4a9fb 100644 --- a/internal/server/api.go +++ b/internal/server/api.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "net/url" + "time" httpw "github.com/jwijenbergh/eduvpn-common/internal/http" "github.com/jwijenbergh/eduvpn-common/internal/types" @@ -76,7 +77,7 @@ func apiAuthorizedRetry(server Server, method string, endpoint string, opts *htt // Only retry authorized if we get a HTTP 401 if errors.As(bodyErr, &error) && error.Status == 401 { // Tell the method that the token is expired - server.GetOAuth().Token.ExpiredTimestamp = util.GenerateTimeSeconds() + server.GetOAuth().Token.ExpiredTimestamp = util.GetCurrentTime() retryHeader, retryBody, retryErr := apiAuthorized(server, method, endpoint, opts) if retryErr != nil { return nil, nil, &types.WrappedErrorMessage{Message: errorMessage, Err: retryErr} @@ -115,7 +116,7 @@ func APIInfo(server Server) error { return nil } -func APIConnectWireguard(server Server, profile_id string, pubkey string, supportsOpenVPN bool) (string, string, int64, error) { +func APIConnectWireguard(server Server, profile_id string, pubkey string, supportsOpenVPN bool) (string, string, time.Time, error) { errorMessage := "failed obtaining a WireGuard configuration" headers := http.Header{ "content-type": {"application/x-www-form-urlencoded"}, @@ -132,14 +133,14 @@ func APIConnectWireguard(server Server, profile_id string, pubkey string, suppor } header, connectBody, connectErr := apiAuthorizedRetry(server, http.MethodPost, "/connect", &httpw.HTTPOptionalParams{Headers: headers, Body: urlForm}) if connectErr != nil { - return "", "", 0, &types.WrappedErrorMessage{Message: errorMessage, Err: connectErr} + return "", "", time.Time{}, &types.WrappedErrorMessage{Message: errorMessage, Err: connectErr} } expires := header.Get("expires") pTime, pTimeErr := http.ParseTime(expires) if pTimeErr != nil { - return "", "", 0, &types.WrappedErrorMessage{Message: errorMessage, Err: pTimeErr} + return "", "", time.Time{}, &types.WrappedErrorMessage{Message: errorMessage, Err: pTimeErr} } contentType := header.Get("content-type") @@ -148,10 +149,10 @@ func APIConnectWireguard(server Server, profile_id string, pubkey string, suppor if contentType == "application/x-wireguard-profile" { content = "wireguard" } - return string(connectBody), content, pTime.Unix(), nil + return string(connectBody), content, pTime, nil } -func APIConnectOpenVPN(server Server, profile_id string) (string, int64, error) { +func APIConnectOpenVPN(server Server, profile_id string) (string, time.Time, error) { errorMessage := "failed obtaining an OpenVPN configuration" headers := http.Header{ "content-type": {"application/x-www-form-urlencoded"}, @@ -164,15 +165,15 @@ func APIConnectOpenVPN(server Server, profile_id string) (string, int64, error) header, connectBody, connectErr := apiAuthorizedRetry(server, http.MethodPost, "/connect", &httpw.HTTPOptionalParams{Headers: headers, Body: urlForm}) if connectErr != nil { - return "", 0, &types.WrappedErrorMessage{Message: errorMessage, Err: connectErr} + return "", time.Time{}, &types.WrappedErrorMessage{Message: errorMessage, Err: connectErr} } expires := header.Get("expires") pTime, pTimeErr := http.ParseTime(expires) if pTimeErr != nil { - return "", 0, &types.WrappedErrorMessage{Message: errorMessage, Err: pTimeErr} + return "", time.Time{}, &types.WrappedErrorMessage{Message: errorMessage, Err: pTimeErr} } - return string(connectBody), pTime.Unix(), nil + return string(connectBody), pTime, nil } // This needs no further return value as it's best effort diff --git a/internal/server/common.go b/internal/server/common.go index 5340b39..be6ed46 100644 --- a/internal/server/common.go +++ b/internal/server/common.go @@ -3,6 +3,7 @@ package server import ( "encoding/json" "fmt" + "time" "github.com/jwijenbergh/eduvpn-common/internal/fsm" "github.com/jwijenbergh/eduvpn-common/internal/oauth" @@ -19,8 +20,8 @@ type ServerBase struct { Endpoints ServerEndpoints `json:"endpoints"` Profiles ServerProfileInfo `json:"profiles"` ProfilesRaw string `json:"profiles_raw"` - StartTime int64 `json:"start_time"` - EndTime int64 `json:"expire_time"` + StartTime time.Time `json:"start_time"` + EndTime time.Time `json:"expire_time"` Type string `json:"server_type"` FSM *fsm.FSM `json:"-"` } @@ -133,7 +134,7 @@ func getServerInfoScreen(base ServerBase) (ServerInfoScreen) { serverInfoScreen.DisplayName = base.DisplayName serverInfoScreen.SupportContact = base.SupportContact serverInfoScreen.Profiles = base.Profiles - serverInfoScreen.ExpireTime = base.EndTime + serverInfoScreen.ExpireTime = base.EndTime.Unix() serverInfoScreen.Type = base.Type return serverInfoScreen @@ -287,23 +288,22 @@ func ShouldRenewButton(server Server) bool { } // Get current time - current := util.GenerateTimeSeconds() + current := util.GetCurrentTime() // 30 minutes have not passed - if current <= (base.StartTime + 30*60) { + if !current.After(base.StartTime.Add(30 * time.Minute)) { return false } // Session will not expire today - if current <= (base.EndTime - 24*60*60) { + if !current.Add(24 * time.Hour).After(base.EndTime) { return false } // Session duration is less than 24 hours but not 75% has passed - duration := base.EndTime - base.StartTime - - // TODO: Is converting to float64 okay here? - if duration < 24*60*60 && float64(current) <= (float64(base.StartTime)+0.75*float64(duration)) { + duration := base.EndTime.Sub(base.StartTime) + percentTime := base.StartTime.Add((duration/4)*3) + if duration < time.Duration(24 * time.Hour) && !current.After(percentTime) { return false } @@ -391,7 +391,7 @@ func wireguardGetConfig(server Server, supportsOpenVPN bool) (string, string, er } // Store start and end time - base.StartTime = util.GenerateTimeSeconds() + base.StartTime = util.GetCurrentTime() base.EndTime = expires if content == "wireguard" { @@ -416,7 +416,7 @@ func openVPNGetConfig(server Server) (string, string, error) { configOpenVPN, expires, configErr := APIConnectOpenVPN(server, profile_id) // Store start and end time - base.StartTime = util.GenerateTimeSeconds() + base.StartTime = util.GetCurrentTime() base.EndTime = expires if configErr != nil { diff --git a/internal/types/server.go b/internal/types/server.go index 9e68a5c..e626183 100644 --- a/internal/types/server.go +++ b/internal/types/server.go @@ -2,6 +2,7 @@ package types import ( "encoding/json" + "time" ) // Shared server types @@ -11,7 +12,7 @@ import ( type DiscoveryOrganizations struct { Version uint64 `json:"v"` List []DiscoveryOrganization `json:"organization_list"` - Timestamp int64 `json:"-"` + Timestamp time.Time `json:"-"` RawString string `json:"-"` } @@ -29,7 +30,7 @@ type DiscoveryOrganization struct { type DiscoveryServers struct { Version uint64 `json:"v"` List []DiscoveryServer `json:"server_list"` - Timestamp int64 `json:"-"` + Timestamp time.Time `json:"-"` RawString string `json:"-"` } diff --git a/internal/util/util.go b/internal/util/util.go index 81bd53b..b86e4cb 100644 --- a/internal/util/util.go +++ b/internal/util/util.go @@ -21,9 +21,8 @@ func MakeRandomByteSlice(size int) ([]byte, error) { return byteSlice, nil } -func GenerateTimeSeconds() int64 { - current := time.Now() - return current.Unix() +func GetCurrentTime() time.Time { + return time.Now() } func EnsureDirectory(directory string) error { |
