Skip to content

Commit

Permalink
IAM: get_user() should return PasswordLastUsed-field if set
Browse files Browse the repository at this point in the history
  • Loading branch information
bblommers committed Feb 17, 2023
1 parent 418c69f commit 633ba22
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
7 changes: 7 additions & 0 deletions moto/iam/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,13 @@ def arn(self):
def created_iso_8601(self):
return iso_8601_datetime_with_milliseconds(self.create_date)

@property
def password_last_used_iso_8601(self):
if self.password_last_used is not None:
return iso_8601_datetime_with_milliseconds(self.password_last_used)
else:
return None

def get_policy(self, policy_name):
policy_json = None
try:
Expand Down
3 changes: 3 additions & 0 deletions moto/iam/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1805,6 +1805,9 @@ def get_service_linked_role_deletion_status(self):
<UserId>{{ user.id }}</UserId>
<CreateDate>{{ user.created_iso_8601 }}</CreateDate>
<Arn>{{ user.arn }}</Arn>
{% if user.password_last_used_iso_8601 %}
<PasswordLastUsed>{{ user.password_last_used_iso_8601 }}</PasswordLastUsed>
{% endif %}
{% if tags %}
<Tags>
{% for tag in tags %}
Expand Down
41 changes: 41 additions & 0 deletions tests/test_iam/test_iam_password_last_used.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import boto3
import pytz
from datetime import datetime, timedelta
from moto import mock_iam, settings
from moto.backends import get_backend
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from unittest import SkipTest


@mock_iam
def test_password_last_used():
if settings.TEST_SERVER_MODE:
raise SkipTest("Can't set password_last_used in ServerMode")
client = boto3.client("iam", "us-east-1")
current_time = pytz.timezone("UTC").localize(datetime.utcnow())
password_last_used_date = current_time - timedelta(days=100)

username = "test.user"
client.create_user(Path="/staff/", UserName=username)["User"]
client.create_login_profile(
UserName=username, Password="Password1", PasswordResetRequired=False
)

access_key = client.create_access_key(UserName=username)["AccessKey"]

as_new_user = boto3.resource(
"iam",
region_name="us-east-1",
aws_access_key_id=access_key["AccessKeyId"],
aws_secret_access_key=access_key["SecretAccessKey"],
)

# Username is set, but password not yet
assert as_new_user.CurrentUser().user_name == username
assert not as_new_user.CurrentUser().password_last_used

iam_backend = get_backend("iam")[ACCOUNT_ID]["global"]
iam_backend.users[username].password_last_used = password_last_used_date

# Password is returned now
assert as_new_user.CurrentUser().password_last_used

0 comments on commit 633ba22

Please sign in to comment.