Skip to content
This repository has been archived by the owner on Jul 12, 2023. It is now read-only.

Commit

Permalink
Make sure password change time is something (#661)
Browse files Browse the repository at this point in the history
  • Loading branch information
whaught authored Sep 23, 2020
1 parent 9345a7f commit f7400f7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pkg/controller/middleware/realm.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ func checkRealmPasswordAge(user *database.User, realm *database.Realm) error {
}

now := time.Now().UTC()
nextPasswordChange := user.LastPasswordChange.Add(
nextPasswordChange := user.PasswordChanged().Add(
time.Hour * 24 * time.Duration(realm.PasswordRotationPeriodDays))

if now.After(nextPasswordChange) {
Expand Down
19 changes: 18 additions & 1 deletion pkg/database/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ import (
"github.com/sethvargo/go-password/password"
)

const minDuration = -1 << 63

// They probably didn't make an account before this project existed.
var launched time.Time = time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC)

// User represents a user of the system
type User struct {
gorm.Model
Expand All @@ -41,6 +46,14 @@ type User struct {
LastPasswordChange time.Time
}

// PasswordChanged returns password change time or account creation time if unset.
func (u *User) PasswordChanged() time.Time {
if u.LastPasswordChange.Before(launched) {
return u.CreatedAt
}
return u.LastPasswordChange
}

// AfterFind runs after the record is found.
func (u *User) AfterFind(tx *gorm.DB) error {
// Sort Realms and Admin realms. Unfortunately gorm provides no way to do this
Expand All @@ -57,7 +70,11 @@ func (u *User) AfterFind(tx *gorm.DB) error {

// PasswordAgeString displays the age of the password in friendly text.
func (u *User) PasswordAgeString() string {
ago := time.Since(u.LastPasswordChange)
ago := time.Since(u.PasswordChanged())
if ago == minDuration {
return "unknown"
}

h := ago.Hours()
if h > 48 {
return fmt.Sprintf("%v days", int(h/24))
Expand Down
2 changes: 1 addition & 1 deletion pkg/database/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func TestUserLifecycle(t *testing.T) {
t.Errorf("expected %#v to be %#v", got, want)
}

if got, want := got.LastPasswordChange, now; got != want {
if got, want := got.PasswordChanged(), now; got != want {
t.Errorf("expected %#v to be %#v", got.String(), want.String())
}
}
Expand Down

0 comments on commit f7400f7

Please sign in to comment.