Skip to content

Jwt#79

Merged
matin merged 24 commits intocuenca-mx:mainfrom
ricardo8990:jwt
Jan 13, 2021
Merged

Jwt#79
matin merged 24 commits intocuenca-mx:mainfrom
ricardo8990:jwt

Conversation

@ricardo8990
Copy link
Copy Markdown

Agrega la autenticación por JWT para usar en aplicaciones internas

closes #77

@ricardo8990 ricardo8990 self-assigned this Oct 21, 2020
@codecov
Copy link
Copy Markdown

codecov Bot commented Oct 21, 2020

Codecov Report

Merging #79 (aed0a32) into main (098522e) will not change coverage.
The diff coverage is 100.00%.

@@            Coverage Diff            @@
##              main       #79   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           16        17    +1     
  Lines          420       445   +25     
=========================================
+ Hits           420       445   +25     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
cuenca/exc.py 100.00% <100.00%> (ø)
cuenca/http/client.py 100.00% <100.00%> (ø)
cuenca/jwt.py 100.00% <100.00%> (ø)
cuenca/version.py 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 098522e...aed0a32. Read the comment docs.

Copy link
Copy Markdown
Contributor

@matin matin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also missing some form of docs on how to use JWT auth. At a minimum, it should be in README.md

Comment thread cuenca/http/client.py Outdated
Comment on lines +120 to +128
try:
payload_encoded = self.jwt_token.split('.')[1]
payload = json.loads(base64.b64decode(f'{payload_encoded}=='))
# Get a new token if there's less than 5 mins for the actual
# to be expired
if dt.datetime.utcfromtimestamp(
payload['exp']
) - dt.datetime.utcnow() <= dt.timedelta(minutes=5):
raise Exception('Expired token')
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try block should only include one line of code

Comment thread cuenca/http/client.py Outdated
Comment on lines +120 to +128
try:
payload_encoded = self.jwt_token.split('.')[1]
payload = json.loads(base64.b64decode(f'{payload_encoded}=='))
# Get a new token if there's less than 5 mins for the actual
# to be expired
if dt.datetime.utcfromtimestamp(
payload['exp']
) - dt.datetime.utcnow() <= dt.timedelta(minutes=5):
raise Exception('Expired token')
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

huh? why take this approach?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Payload in JWT tokens contain exp in base64 which indicates the datetime when the token will be invalid. So I'm extracting that part of the token to validate it before I send the request, this way I save one request saying that the token is expired.

Comment thread cuenca/http/client.py Outdated
payload['exp']
) - dt.datetime.utcnow() <= dt.timedelta(minutes=5):
raise Exception('Expired token')
except Exception:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are few cases in life where you should catch Exception. Why are you doing it in this case?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There're a few cases here where this part of the code can generate an Exception:

  • IndexError if the current token is malformed
  • binascii.Error if the token can't be decoded with base64
  • JSONDecodeError if the JSON is malformed
  • I added one if the token is expired

All of this exceptions can happen if authed responded with an invalid token or the current token is somehow manipulated (which there should not be a reason you would want to do it). In any case, the token should be generated again.

If I include only one line of code per try block, I'd ended up having something like:

        try:
            payload_encoded = self.jwt_token.split('.')[1]
        except IndexError:
             self.jwt_token = None
       else:
           try:
                 payload = json.loads(base64.b64decode(f'{payload_encoded}=='))
           except (binascii.Error, JSONDecodeError):
               self.jwt_token = None
           else:
                if dt.datetime.utcfromtimestamp(
                    payload['exp']
                ) - dt.datetime.utcnow() <= dt.timedelta(minutes=5):
                    self.jwt_token = None

Which I think is way more confusing. I didn't see it necessary to create a new Exception since it's only going to be used here but I could clean it up by specify all the possible exceptions:

        try:
            payload_encoded = self.jwt_token.split('.')[1]
            payload = json.loads(base64.b64decode(f'{payload_encoded}=='))
            # Get a new token if there's less than 5 mins for the actual
            # to be expired
            if dt.datetime.utcfromtimestamp(
                payload['exp']
            ) - dt.datetime.utcnow() <= dt.timedelta(minutes=5):
                raise CustomException('Expired token')
        except (IndexError, binascii.Error, JSONDecodeError, CustomException):
            self.jwt_token = None

Comment thread cuenca/http/client.py
Comment thread cuenca/http/client.py Outdated
Comment thread cuenca/http/client.py Outdated
Comment thread requirements-test.txt
Comment thread cuenca/jwt.py Outdated
Copy link
Copy Markdown
Contributor

@matin matin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only one minor change. Otherwise, looks good!

Comment thread cuenca/jwt.py Outdated
@matin
Copy link
Copy Markdown
Contributor

matin commented Jan 13, 2021

@ricardo8990 looks good. just need to rebase main

Copy link
Copy Markdown
Contributor

@matin matin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ricardo8990 can you release?

@matin matin merged commit 7c3b68f into cuenca-mx:main Jan 13, 2021
@ricardo8990 ricardo8990 deleted the jwt branch January 13, 2021 19:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Soportar autenticación por jwt

2 participants