Skip to content

Commit

Permalink
Merge pull request #113 from mozilla-it/feature-tz-aware-now
Browse files Browse the repository at this point in the history
Convert utcnow() to now(utc)
  • Loading branch information
jwhitlock authored Mar 23, 2021
2 parents cdb845c + 1b63bc1 commit c2ba23c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 11 deletions.
4 changes: 2 additions & 2 deletions ctms/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
the client POSTs to /token again.
"""
import warnings
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from typing import Dict, Optional

from fastapi.exceptions import HTTPException
Expand Down Expand Up @@ -46,7 +46,7 @@ def create_access_token(
) -> str:
"""Create a JWT string to act as an OAuth2 access token."""
to_encode = data.copy()
expire = (now or datetime.utcnow()) + expires_delta
expire = (now or datetime.now(timezone.utc)) + expires_delta
to_encode["exp"] = expire
encoded_jwt = jwt.encode(to_encode, secret_key, algorithm="HS256")
return encoded_jwt
Expand Down
14 changes: 5 additions & 9 deletions tests/unit/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,8 @@ def test_post_token_header(anon_client, test_token_settings, client_id_and_secre
)
assert payload["sub"] == f"api_client:{client_id}"
expected_expires = (
(datetime.utcnow() + test_token_settings["expires_delta"])
.replace(tzinfo=timezone.utc)
.timestamp()
)
datetime.now(timezone.utc) + test_token_settings["expires_delta"]
).timestamp()
assert -2.0 < (expected_expires - payload["exp"]) < 2.0


Expand All @@ -84,10 +82,8 @@ def test_post_token_form_data(anon_client, test_token_settings, client_id_and_se
)
assert payload["sub"] == f"api_client:{client_id}"
expected_expires = (
(datetime.utcnow() + test_token_settings["expires_delta"])
.replace(tzinfo=timezone.utc)
.timestamp()
)
datetime.now(timezone.utc) + test_token_settings["expires_delta"]
).timestamp()
assert -2.0 < (expected_expires - payload["exp"]) < 2.0


Expand Down Expand Up @@ -209,7 +205,7 @@ def test_get_ctms_with_expired_token_fails(
example_contact, anon_client, test_token_settings, client_id_and_secret
):
"""Calling an authenticated API with an expired token is an error"""
yesterday = datetime.utcnow() - timedelta(days=1)
yesterday = datetime.now(timezone.utc) - timedelta(days=1)
client_id, client_secret = client_id_and_secret
token = create_access_token(
{"sub": f"api_client:{client_id}"}, **test_token_settings, now=yesterday
Expand Down

0 comments on commit c2ba23c

Please sign in to comment.