Skip to content

Commit

Permalink
fix: make a request to check if auth token is valid before enqueue
Browse files Browse the repository at this point in the history
(cherry picked from commit 7e1c4af)

# Conflicts:
#	india_compliance/__init__.py
  • Loading branch information
vorasmit authored and mergify[bot] committed Sep 11, 2024
1 parent fcb8ae5 commit 959a1ef
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 6 deletions.
3 changes: 3 additions & 0 deletions india_compliance/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
<<<<<<< HEAD
<<<<<<< HEAD
__version__ = "15.0.2"
=======
from .exceptions import *

=======
>>>>>>> 7e1c4af5 (fix: make a request to check if auth token is valid before enqueue)
__version__ = "16.0.0-dev"
>>>>>>> 7afa94c7 (fix: enhanced otp handeling taxpayer apis)
5 changes: 5 additions & 0 deletions india_compliance/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,8 @@ class InvalidOTPError(Exception):
def __init__(self, message="Invalid OTP", *args, **kwargs):
self.response = kwargs.pop("response", None)
super().__init__(message, *args, **kwargs)


class InvalidAuthTokenError(Exception):
def __init__(self, message="Invalid Auth Token", *args, **kwargs):
super().__init__(message, *args, **kwargs)
81 changes: 75 additions & 6 deletions india_compliance/gst_india/api_classes/taxpayer_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
from cryptography.hazmat.backends import default_backend

import frappe
import frappe.utils
from frappe import _
from frappe.utils import add_to_date, cint, now_datetime

import india_compliance
from india_compliance.exceptions import (
InvalidAuthTokenError,
InvalidOTPError,
OTPRequestedError,
)
from india_compliance.gst_india.api_classes.base import BaseAPI, get_public_ip
from india_compliance.gst_india.utils import merge_dicts, tar_gz_bytes_to_data
from india_compliance.gst_india.utils.cryptography import (
Expand All @@ -28,10 +33,10 @@ def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)

except india_compliance.OTPRequestedError as e:
except OTPRequestedError as e:
return e.response

except india_compliance.InvalidOTPError as e:
except InvalidOTPError as e:
return e.response

except Exception as e:
Expand Down Expand Up @@ -127,7 +132,7 @@ def request_otp(self):

response.update({"error_type": "otp_requested", "gstin": self.company_gstin})

raise india_compliance.OTPRequestedError(response=response)
raise OTPRequestedError(response=response)

def autheticate_with_otp(self, otp=None):
if not otp:
Expand Down Expand Up @@ -248,10 +253,31 @@ def get_auth_token(self):

return self.auth_token

def reset_auth_token(self):
"""
Reset after job to clear the auth token
"""
frappe.db.set_value(
"GST Credential",
{
"gstin": self.company_gstin,
"username": self.username,
"service": "Returns",
},
{"auth_token": None},
)

frappe.db.commit()


class TaxpayerBaseAPI(TaxpayerAuthenticate):
BASE_PATH = "standard/gstn"

IGNORED_ERROR_CODES = {
**TaxpayerAuthenticate.IGNORED_ERROR_CODES,
"RT-R1R3BAV-1007": "authorization_failed", # Either auth-token or username is invalid. Raised in get_filing_preference
}

def setup(self, company_gstin):
if self.sandbox_mode:
frappe.throw(_("Sandbox mode not supported for Returns API"))
Expand Down Expand Up @@ -291,6 +317,12 @@ def _request(
if response.error_type in ["otp_requested", "invalid_otp"]:
return response

frappe.cache.set_value(
f"authenticated_gstin:{self.company_gstin}",
True,
expires_in_sec=60 * 15,
)

headers = {"auth-token": auth_token}
if return_period:
headers["ret_period"] = return_period
Expand Down Expand Up @@ -370,10 +402,17 @@ def is_ignored_error(self, response):
response.gstin = self.company_gstin

if response.error_type == "otp_requested":
raise india_compliance.OTPRequestedError(response=response)
raise OTPRequestedError(response=response)

if response.error_type == "invalid_otp":
raise india_compliance.InvalidOTPError(response=response)
raise InvalidOTPError(response=response)

if response.error_type == "authorization_failed" and getattr(
frappe.local, "job", None
):
frappe.local.job.after_job.add(self.reset_auth_token)

raise InvalidAuthTokenError

return True

Expand Down Expand Up @@ -404,3 +443,33 @@ def get_files(self, return_period, token, action, endpoint, otp=None):
return response

return FilesAPI().get_all(response)

def validate_auth_token(self):
"""
Try refreshing the auth token without error
to check if the auth token is valid
Generates a new OTP if the auth token is invalid
"""
if frappe.cache.get_value(f"authenticated_gstin:{self.company_gstin}"):
return

# Dummy request
self.get_filing_preference()

return

def get_filing_preference(self):
return self.get(
action="GETPREF", params={"fy": self.get_fy()}, endpoint="returns"
)

@staticmethod
def get_fy():
date = frappe.utils.getdate()

# Standard for India as per GST
if date.month < 4:
return f"{date.year - 1}-{str(date.year)[2:]}"

return f"{date.year}-{str(date.year + 1)[2:]}"

0 comments on commit 959a1ef

Please sign in to comment.