From 34d26d44b0b06de00190b2302af9c7e331f7549a Mon Sep 17 00:00:00 2001 From: bcmmbaga Date: Fri, 3 Jan 2025 17:55:02 +0300 Subject: [PATCH] Refactor and fix sonar lint Signed-off-by: bcmmbaga --- management/server/account.go | 2 +- management/server/account_test.go | 2 +- .../server/http/handlers/peers/peers_handler.go | 4 ++-- .../handlers/setup_keys/setupkeys_handler.go | 4 ++-- .../server/http/handlers/users/pat_handler.go | 2 +- .../http/handlers/users/pat_handler_test.go | 2 +- .../server/http/middleware/auth_middleware.go | 2 +- management/server/peer.go | 4 ++-- management/server/peer/peer.go | 6 +++--- management/server/peer_test.go | 4 ++-- management/server/setupkey_test.go | 8 ++++---- management/server/store/file_store.go | 2 +- management/server/testutil/store.go | 16 ++++++++-------- management/server/types/personal_access_token.go | 8 ++++---- management/server/types/setupkey.go | 12 ++++++------ management/server/types/user.go | 10 +++++----- management/server/user.go | 2 +- 17 files changed, 45 insertions(+), 45 deletions(-) diff --git a/management/server/account.go b/management/server/account.go index 0a41303c4..41da7f079 100644 --- a/management/server/account.go +++ b/management/server/account.go @@ -789,7 +789,7 @@ func (am *DefaultAccountManager) lookupUserInCache(ctx context.Context, userID s if user.Issued == types.UserIssuedIntegration { continue } - users[user.Id] = userLoggedInOnce(!user.LastLoginTime().IsZero()) + users[user.Id] = userLoggedInOnce(!user.GetLastLogin().IsZero()) } log.WithContext(ctx).Debugf("looking up user %s of account %s in cache", userID, account.Id) userData, err := am.lookupCache(ctx, users, account.Id) diff --git a/management/server/account_test.go b/management/server/account_test.go index 54b692a5a..29e8ddb6d 100644 --- a/management/server/account_test.go +++ b/management/server/account_test.go @@ -793,7 +793,7 @@ func TestDefaultAccountManager_MarkPATUsed(t *testing.T) { if err != nil { t.Fatalf("Error when getting account: %s", err) } - assert.True(t, !account.Users["someUser"].PATs["tokenId"].LastUsed.IsZero()) + assert.True(t, !account.Users["someUser"].PATs["tokenId"].GetLastUsed().IsZero()) } func TestAccountManager_PrivateAccount(t *testing.T) { diff --git a/management/server/http/handlers/peers/peers_handler.go b/management/server/http/handlers/peers/peers_handler.go index e81f0d983..7eb8e2153 100644 --- a/management/server/http/handlers/peers/peers_handler.go +++ b/management/server/http/handlers/peers/peers_handler.go @@ -349,7 +349,7 @@ func toSinglePeerResponse(peer *nbpeer.Peer, groupsInfo []api.GroupMinimum, dnsD UiVersion: peer.Meta.UIVersion, DnsLabel: fqdn(peer, dnsDomain), LoginExpirationEnabled: peer.LoginExpirationEnabled, - LastLogin: peer.LastLoginTime(), + LastLogin: peer.GetLastLogin(), LoginExpired: peer.Status.LoginExpired, ApprovalRequired: !approved, CountryCode: peer.Location.CountryCode, @@ -383,7 +383,7 @@ func toPeerListItemResponse(peer *nbpeer.Peer, groupsInfo []api.GroupMinimum, dn UiVersion: peer.Meta.UIVersion, DnsLabel: fqdn(peer, dnsDomain), LoginExpirationEnabled: peer.LoginExpirationEnabled, - LastLogin: peer.LastLoginTime(), + LastLogin: peer.GetLastLogin(), LoginExpired: peer.Status.LoginExpired, AccessiblePeersCount: accessiblePeersCount, CountryCode: peer.Location.CountryCode, diff --git a/management/server/http/handlers/setup_keys/setupkeys_handler.go b/management/server/http/handlers/setup_keys/setupkeys_handler.go index 7623e3083..67e296901 100644 --- a/management/server/http/handlers/setup_keys/setupkeys_handler.go +++ b/management/server/http/handlers/setup_keys/setupkeys_handler.go @@ -240,12 +240,12 @@ func ToResponseBody(key *types.SetupKey) *api.SetupKey { Id: key.Id, Key: key.KeySecret, Name: key.Name, - Expires: key.ExpirationTime(), + Expires: key.GetExpiresAt(), Type: string(key.Type), Valid: key.IsValid(), Revoked: key.Revoked, UsedTimes: key.UsedTimes, - LastUsed: key.LastUsedTime(), + LastUsed: key.GetLastUsed(), State: state, AutoGroups: key.AutoGroups, UpdatedAt: key.UpdatedAt, diff --git a/management/server/http/handlers/users/pat_handler.go b/management/server/http/handlers/users/pat_handler.go index a73b83a37..7b93d2ae1 100644 --- a/management/server/http/handlers/users/pat_handler.go +++ b/management/server/http/handlers/users/pat_handler.go @@ -169,7 +169,7 @@ func toPATResponse(pat *types.PersonalAccessToken) *api.PersonalAccessToken { CreatedAt: pat.CreatedAt, CreatedBy: pat.CreatedBy, Name: pat.Name, - ExpirationDate: pat.ExpirationTime(), + ExpirationDate: pat.GetExpirationDate(), Id: pat.ID, LastUsed: pat.LastUsed, } diff --git a/management/server/http/handlers/users/pat_handler_test.go b/management/server/http/handlers/users/pat_handler_test.go index 866d744ac..9388067a4 100644 --- a/management/server/http/handlers/users/pat_handler_test.go +++ b/management/server/http/handlers/users/pat_handler_test.go @@ -251,6 +251,6 @@ func toTokenResponse(serverToken types.PersonalAccessToken) api.PersonalAccessTo CreatedAt: serverToken.CreatedAt, LastUsed: serverToken.LastUsed, CreatedBy: serverToken.CreatedBy, - ExpirationDate: serverToken.ExpirationTime(), + ExpirationDate: serverToken.GetExpirationDate(), } } diff --git a/management/server/http/middleware/auth_middleware.go b/management/server/http/middleware/auth_middleware.go index 953b55483..182c30cf6 100644 --- a/management/server/http/middleware/auth_middleware.go +++ b/management/server/http/middleware/auth_middleware.go @@ -161,7 +161,7 @@ func (m *AuthMiddleware) checkPATFromRequest(w http.ResponseWriter, r *http.Requ if err != nil { return fmt.Errorf("invalid Token: %w", err) } - if time.Now().After(pat.ExpirationTime()) { + if time.Now().After(pat.GetExpirationDate()) { return fmt.Errorf("token expired") } diff --git a/management/server/peer.go b/management/server/peer.go index 0a32361ae..6c4c2d100 100644 --- a/management/server/peer.go +++ b/management/server/peer.go @@ -567,7 +567,7 @@ func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID s } if addedByUser { - err := transaction.SaveUserLastLogin(ctx, accountID, userID, *newPeer.LastLogin) + err := transaction.SaveUserLastLogin(ctx, accountID, userID, newPeer.GetLastLogin()) if err != nil { return fmt.Errorf("failed to update user last login: %w", err) } @@ -912,7 +912,7 @@ func (am *DefaultAccountManager) handleExpiredPeer(ctx context.Context, user *ty return err } - err = am.Store.SaveUserLastLogin(ctx, user.AccountID, user.Id, peer.LastLoginTime()) + err = am.Store.SaveUserLastLogin(ctx, user.AccountID, user.Id, peer.GetLastLogin()) if err != nil { return err } diff --git a/management/server/peer/peer.go b/management/server/peer/peer.go index 4f412e5c2..355d78ce0 100644 --- a/management/server/peer/peer.go +++ b/management/server/peer/peer.go @@ -224,8 +224,8 @@ func (p *Peer) UpdateMetaIfNew(meta PeerSystemMeta) bool { return true } -// LastLoginTime returns the last login time of the peer. -func (p *Peer) LastLoginTime() time.Time { +// GetLastLogin returns the last login time of the peer. +func (p *Peer) GetLastLogin() time.Time { if p.LastLogin != nil { return *p.LastLogin } @@ -269,7 +269,7 @@ func (p *Peer) LoginExpired(expiresIn time.Duration) (bool, time.Duration) { if !p.AddedWithSSOLogin() || !p.LoginExpirationEnabled { return false, 0 } - expiresAt := p.LastLogin.Add(expiresIn) + expiresAt := p.GetLastLogin().Add(expiresIn) now := time.Now() timeLeft := expiresAt.Sub(now) return timeLeft <= 0, timeLeft diff --git a/management/server/peer_test.go b/management/server/peer_test.go index f95e3ce38..e31f4e184 100644 --- a/management/server/peer_test.go +++ b/management/server/peer_test.go @@ -1232,7 +1232,7 @@ func Test_RegisterPeerByUser(t *testing.T) { lastLogin, err := time.Parse("2006-01-02T15:04:05Z", "0001-01-01T00:00:00Z") assert.NoError(t, err) - assert.NotEqual(t, lastLogin, account.Users[existingUserID].LastLogin) + assert.NotEqual(t, lastLogin, account.Users[existingUserID].GetLastLogin()) } func Test_RegisterPeerBySetupKey(t *testing.T) { @@ -1362,7 +1362,7 @@ func Test_RegisterPeerRollbackOnFailure(t *testing.T) { hashedKey := sha256.Sum256([]byte(faultyKey)) encodedHashedKey := b64.StdEncoding.EncodeToString(hashedKey[:]) - assert.Equal(t, lastUsed, account.SetupKeys[encodedHashedKey].LastUsedTime().UTC()) + assert.Equal(t, lastUsed, account.SetupKeys[encodedHashedKey].GetLastUsed().UTC()) assert.Equal(t, 0, account.SetupKeys[encodedHashedKey].UsedTimes) } diff --git a/management/server/setupkey_test.go b/management/server/setupkey_test.go index 8632fed3b..e225ec54b 100644 --- a/management/server/setupkey_test.go +++ b/management/server/setupkey_test.go @@ -66,7 +66,7 @@ func TestDefaultAccountManager_SaveSetupKey(t *testing.T) { t.Fatal(err) } - assertKey(t, newKey, keyName, revoked, "reusable", 0, key.CreatedAt, key.ExpirationTime(), + assertKey(t, newKey, keyName, revoked, "reusable", 0, key.CreatedAt, key.GetExpiresAt(), key.Id, time.Now().UTC(), autoGroups, true) // check the corresponding events that should have been generated @@ -336,8 +336,8 @@ func assertKey(t *testing.T, key *types.SetupKey, expectedName string, expectedR t.Errorf("expected setup key to have UsedTimes = %v, got %v", expectedUsedTimes, key.UsedTimes) } - if key.ExpiresAt.Sub(expectedExpiresAt).Round(time.Hour) != 0 { - t.Errorf("expected setup key to have ExpiresAt ~ %v, got %v", expectedExpiresAt, key.ExpiresAt) + if key.GetExpiresAt().Sub(expectedExpiresAt).Round(time.Hour) != 0 { + t.Errorf("expected setup key to have ExpiresAt ~ %v, got %v", expectedExpiresAt, key.GetExpiresAt()) } if key.UpdatedAt.Sub(expectedUpdatedAt).Round(time.Hour) != 0 { @@ -391,7 +391,7 @@ func TestSetupKey_Copy(t *testing.T) { key, _ := types.GenerateSetupKey("key name", types.SetupKeyOneOff, time.Hour, []string{}, types.SetupKeyUnlimitedUsage, false) keyCopy := key.Copy() - assertKey(t, keyCopy, key.Name, key.Revoked, string(key.Type), key.UsedTimes, key.CreatedAt, key.ExpirationTime(), key.Id, + assertKey(t, keyCopy, key.Name, key.Revoked, string(key.Type), key.UsedTimes, key.CreatedAt, key.GetExpiresAt(), key.Id, key.UpdatedAt, key.AutoGroups, true) } diff --git a/management/server/store/file_store.go b/management/server/store/file_store.go index 5c06600ad..4c9134e41 100644 --- a/management/server/store/file_store.go +++ b/management/server/store/file_store.go @@ -176,7 +176,7 @@ func restore(ctx context.Context, file string) (*FileStore, error) { migrationPeers := make(map[string]*nbpeer.Peer) // key to Peer for key, peer := range account.Peers { // set LastLogin for the peers that were onboarded before the peer login expiration feature - if peer.LastLogin.IsZero() { + if peer.GetLastLogin().IsZero() { peer.LastLogin = nbutil.ToPtr(time.Now().UTC()) } if peer.ID != "" { diff --git a/management/server/testutil/store.go b/management/server/testutil/store.go index d4abc8bd4..16438cab8 100644 --- a/management/server/testutil/store.go +++ b/management/server/testutil/store.go @@ -19,7 +19,7 @@ import ( func CreateMysqlTestContainer() (func(), error) { ctx := context.Background() - container, err := mysql.RunContainer(ctx, + myContainer, err := mysql.RunContainer(ctx, testcontainers.WithImage("mlsmaycon/warmed-mysql:8"), mysql.WithDatabase("testing"), mysql.WithUsername("testing"), @@ -36,12 +36,12 @@ func CreateMysqlTestContainer() (func(), error) { cleanup := func() { timeoutCtx, cancelFunc := context.WithTimeout(ctx, 1*time.Second) defer cancelFunc() - if err = container.Terminate(timeoutCtx); err != nil { - log.WithContext(ctx).Warnf("failed to stop container: %s", err) + if err = myContainer.Terminate(timeoutCtx); err != nil { + log.WithContext(ctx).Warnf("failed to stop mysql container %s: %s", myContainer.GetContainerID(), err) } } - talksConn, err := container.ConnectionString(ctx) + talksConn, err := myContainer.ConnectionString(ctx) if err != nil { return nil, err } @@ -53,7 +53,7 @@ func CreateMysqlTestContainer() (func(), error) { func CreatePostgresTestContainer() (func(), error) { ctx := context.Background() - container, err := postgres.RunContainer(ctx, + pgContainer, err := postgres.RunContainer(ctx, testcontainers.WithImage("postgres:16-alpine"), postgres.WithDatabase("netbird"), postgres.WithUsername("root"), @@ -70,12 +70,12 @@ func CreatePostgresTestContainer() (func(), error) { cleanup := func() { timeoutCtx, cancelFunc := context.WithTimeout(ctx, 1*time.Second) defer cancelFunc() - if err = container.Terminate(timeoutCtx); err != nil { - log.WithContext(ctx).Warnf("failed to stop container: %s", err) + if err = pgContainer.Terminate(timeoutCtx); err != nil { + log.WithContext(ctx).Warnf("failed to stop postgres container %s: %s", pgContainer.GetContainerID(), err) } } - talksConn, err := container.ConnectionString(ctx) + talksConn, err := pgContainer.ConnectionString(ctx) if err != nil { return nil, err } diff --git a/management/server/types/personal_access_token.go b/management/server/types/personal_access_token.go index d30735a77..ff157fcc6 100644 --- a/management/server/types/personal_access_token.go +++ b/management/server/types/personal_access_token.go @@ -51,16 +51,16 @@ func (t *PersonalAccessToken) Copy() *PersonalAccessToken { } } -// ExpirationTime returns the expiration time of the token. -func (t *PersonalAccessToken) ExpirationTime() time.Time { +// GetExpirationDate returns the expiration time of the token. +func (t *PersonalAccessToken) GetExpirationDate() time.Time { if t.ExpirationDate != nil { return *t.ExpirationDate } return time.Time{} } -// LastUsedTime returns the last time the token was used. -func (t *PersonalAccessToken) LastUsedTime() time.Time { +// GetLastUsed returns the last time the token was used. +func (t *PersonalAccessToken) GetLastUsed() time.Time { if t.LastUsed != nil { return *t.LastUsed } diff --git a/management/server/types/setupkey.go b/management/server/types/setupkey.go index e2415bae5..2cd835289 100644 --- a/management/server/types/setupkey.go +++ b/management/server/types/setupkey.go @@ -87,16 +87,16 @@ func (key *SetupKey) EventMeta() map[string]any { return map[string]any{"name": key.Name, "type": key.Type, "key": key.KeySecret} } -// LastUsedTime returns the last used time of the setup key. -func (key *SetupKey) LastUsedTime() time.Time { +// GetLastUsed returns the last used time of the setup key. +func (key *SetupKey) GetLastUsed() time.Time { if key.LastUsed != nil { return *key.LastUsed } return time.Time{} } -// ExpirationTime returns the expiration time of the setup key. -func (key *SetupKey) ExpirationTime() time.Time { +// GetExpiresAt returns the expiration time of the setup key. +func (key *SetupKey) GetExpiresAt() time.Time { if key.ExpiresAt != nil { return *key.ExpiresAt } @@ -133,10 +133,10 @@ func (key *SetupKey) IsRevoked() bool { // IsExpired if key was expired func (key *SetupKey) IsExpired() bool { - if key.ExpirationTime().IsZero() { + if key.GetExpiresAt().IsZero() { return false } - return time.Now().After(key.ExpirationTime()) + return time.Now().After(key.GetExpiresAt()) } // IsOverUsed if the key was used too many times. SetupKey.UsageLimit == 0 indicates the unlimited usage. diff --git a/management/server/types/user.go b/management/server/types/user.go index 20be53167..348fbfb22 100644 --- a/management/server/types/user.go +++ b/management/server/types/user.go @@ -100,11 +100,11 @@ func (u *User) IsBlocked() bool { } func (u *User) LastDashboardLoginChanged(lastLogin time.Time) bool { - return lastLogin.After(u.LastLoginTime()) && !u.LastLoginTime().IsZero() + return lastLogin.After(u.GetLastLogin()) && !u.GetLastLogin().IsZero() } -// LastLoginTime returns the last login time of the user. -func (u *User) LastLoginTime() time.Time { +// GetLastLogin returns the last login time of the user. +func (u *User) GetLastLogin() time.Time { if u.LastLogin != nil { return *u.LastLogin } @@ -151,7 +151,7 @@ func (u *User) ToUserInfo(userData *idp.UserData, settings *Settings) (*UserInfo Status: string(UserStatusActive), IsServiceUser: u.IsServiceUser, IsBlocked: u.Blocked, - LastLogin: u.LastLoginTime(), + LastLogin: u.GetLastLogin(), Issued: u.Issued, Permissions: UserPermissions{ DashboardView: dashboardViewPermissions, @@ -176,7 +176,7 @@ func (u *User) ToUserInfo(userData *idp.UserData, settings *Settings) (*UserInfo Status: string(userStatus), IsServiceUser: u.IsServiceUser, IsBlocked: u.Blocked, - LastLogin: u.LastLoginTime(), + LastLogin: u.GetLastLogin(), Issued: u.Issued, Permissions: UserPermissions{ DashboardView: dashboardViewPermissions, diff --git a/management/server/user.go b/management/server/user.go index 3af8b1d0d..fcf3d34ff 100644 --- a/management/server/user.go +++ b/management/server/user.go @@ -880,7 +880,7 @@ func (am *DefaultAccountManager) GetUsersFromAccount(ctx context.Context, accoun continue } if !user.IsServiceUser { - users[user.Id] = userLoggedInOnce(!user.LastLoginTime().IsZero()) + users[user.Id] = userLoggedInOnce(!user.GetLastLogin().IsZero()) } } queriedUsers, err = am.lookupCache(ctx, users, accountID)