Refactor and fix sonar lint

Signed-off-by: bcmmbaga <bethuelmbaga12@gmail.com>
This commit is contained in:
bcmmbaga 2025-01-03 17:55:02 +03:00
parent 7a6102f865
commit 34d26d44b0
No known key found for this signature in database
GPG Key ID: 511EED5C928AD547
17 changed files with 45 additions and 45 deletions

View File

@ -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)

View File

@ -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) {

View File

@ -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,

View File

@ -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,

View File

@ -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,
}

View File

@ -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(),
}
}

View File

@ -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")
}

View File

@ -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
}

View File

@ -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

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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 != "" {

View File

@ -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
}

View File

@ -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
}

View File

@ -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.

View File

@ -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,

View File

@ -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)