Skip to content

Commit 201bbc2

Browse files
Merge pull request #256 from tigergraph/GML-1889-fix-getToken
fix getToken
2 parents 7ecfad8 + c8d5556 commit 201bbc2

File tree

5 files changed

+76
-62
lines changed

5 files changed

+76
-62
lines changed

pyTigerGraph/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from pyTigerGraph.pyTigerGraph import TigerGraphConnection
22

3-
__version__ = "1.7.2"
3+
__version__ = "1.7.3"
44

55
__license__ = "Apache 2"

pyTigerGraph/pyTigerGraphAuth.py

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -222,52 +222,35 @@ def getToken(self, secret: str = None, setToken: bool = True, lifetime: int = No
222222
if self.version:
223223
s, m, i = self.version.split(".")
224224
success = False
225-
226-
if secret and (int(s) < 3 or (int(s) == 3 and int(m) < 5)):
225+
226+
if not(secret) or self.graphname:
227+
if self.graphname:
228+
_json = {"graph": self.graphname}
227229
try:
228-
# /gsql/v1/tokens endpoint only supported on version >=4.1 and replaced /requesttoken
229-
_json = {"secret": secret, "graph": self.graphname}
230-
if lifetime:
231-
_json["lifetime"] = str(lifetime)
232-
res = requests.request("POST", self.gsUrl +
233-
"/gsql/v1/tokens", verify=False, json=_json, headers={"X-User-Agent": "pyTigerGraph"})
230+
res = self._post(self.restppUrl+"/requesttoken", authMode="pwd", data=str(_json), resKey="results")
231+
mainVer = 3
234232

235-
# if /gsql/v1/tokens endpoint doesn't exist then try old endpoint
236-
if res.status_code == 404:
237-
res = requests.request("GET", self.restppUrl +
238-
"/requesttoken?secret=" + secret +
239-
("&lifetime=" + str(lifetime) if lifetime else ""), verify=False)
240-
mainVer = 3 # Can't use _verGreaterThan4_0 to check version since you need to set a token for that
241-
else:
242-
mainVer = 4
243-
res = json.loads(res.text)
244-
245-
if not res["error"]:
246-
success = True
233+
# The old endpoint doesn't exist (since on TigerGraph Ver >=4.1). Use new endpoint
234+
# have to handle it in this order since _req changes the url to the new url path if first request fails
247235
except Exception as e:
248-
raise e
249-
elif not(success) and not(secret):
250-
_json = {"graph": self.graphname}
251-
try:
252-
res = self._post(self.gsUrl +
253-
"/gsql/v1/tokens", data=_json, authMode="pwd", jsonData=True, resKey=None)
254-
mainVer = 4
255-
256-
# The new endpoint doesn't exist (since on TigerGraph Ver <4.1). Use old endpoint
257-
except requests.exceptions.HTTPError as e:
258-
if e.response.status_code == 404:
259-
res = self._post(self.restppUrl+"/requesttoken", authMode="pwd", data=str({"graph": self.graphname}), resKey="results")
260-
mainVer = 3
261-
if e.response.status_code == 400:
262-
raise TigerGraphException("Error requesting token. Check if the connection's graphname is correct.", 400)
263-
else:
264-
raise e
236+
try:
237+
res = self._post(self.gsUrl + "/gsql/v1/tokens",
238+
data=_json,
239+
authMode="pwd",
240+
jsonData=True,
241+
resKey=None)
242+
mainVer = 4
243+
except requests.exceptions.HTTPError as e:
244+
if e.response.status_code == 404:
245+
raise TigerGraphException(
246+
"Error requesting token. Check if the connection's graphname is correct and that REST authentication is enabled.",
247+
404
248+
)
249+
else:
250+
raise e
251+
pass
265252
success = True
266-
elif not(success) and (int(s) < 3 or (int(s) == 3 and int(m) < 5)):
267-
raise TigerGraphException("Cannot request a token with username/password for versions < 3.5.")
268-
269-
270-
if not success and mainVer == 3:
253+
elif secret:
271254
try:
272255
data = {"secret": secret}
273256

@@ -276,8 +259,24 @@ def getToken(self, secret: str = None, setToken: bool = True, lifetime: int = No
276259

277260
res = json.loads(requests.post(self.restppUrl + "/requesttoken",
278261
data=json.dumps(data), verify=False).text)
279-
except Exception as e:
280-
raise e
262+
success = True
263+
mainVer = 3
264+
except Exception as e: # case of less than version 3.5
265+
try:
266+
res = requests.request("GET", self.restppUrl +
267+
"/requesttoken?secret=" + secret +
268+
("&lifetime=" + str(lifetime) if lifetime else ""), verify=False)
269+
mainVer = 3 # Can't use _verGreaterThan4_0 to check version since you need to set a token for that
270+
271+
res = json.loads(res.text)
272+
273+
if not res["error"]:
274+
success = True
275+
except:
276+
raise e
277+
else:
278+
raise TigerGraphException("Cannot request a token with username/password for versions < 3.5.")
279+
281280

282281

283282
if not res.get("error"):
@@ -511,4 +510,5 @@ def deleteToken(self, secret, token=None, skipNA=True) -> bool:
511510

512511
return True
513512

513+
514514
raise TigerGraphException(res["message"], (res["code"] if "code" in res else None))

pyTigerGraph/pyTigerGraphBase.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -218,21 +218,24 @@ def _verify_jwt_token_support(self):
218218
logger.debug(f"Using auth header: {self.authHeader}")
219219
version = self.getVer()
220220
logger.info(f"Database version: {version}")
221-
221+
'''
222222
# Check JWT support for GSQL server
223223
if self._versionGreaterThan4_0():
224-
logger.debug(f"Attempting to get auth info with URL: {self.gsUrl + '/gsql/v1/auth/simple'}")
225-
self._get(f"{self.gsUrl}/gsql/v1/auth/simple", authMode="token", resKey=None)
224+
logger.debug(f"Attempting to get auth info with URL: {self.gsUrl + '/gsql/v1/tokens/check'}")
225+
res = self._post(f"{self.gsUrl}/gsql/v1/tokens/check", authMode="token", resKey=None, data={"token": self.jwtToken}, jsonData=True)
226+
if "error" in res and res["error"]:
227+
raise TigerGraphException(res["message"], (res["code"] if "code" in res else None))
226228
else:
227229
logger.debug(f"Attempting to get auth info with URL: {self.gsUrl + '/gsqlserver/gsql/simpleauth'}")
228230
self._get(f"{self.gsUrl}/gsqlserver/gsql/simpleauth", authMode="token", resKey=None)
231+
'''
229232
except requests.exceptions.ConnectionError as e:
230233
logger.error(f"Connection error: {e}.")
231-
raise RuntimeError(f"Connection error: {e}.") from e
234+
raise TigerGraphException("Connection error: "+str(e))
232235
except Exception as e:
233-
message = "The JWT token might be invalid or expired or DB version doesn't support JWT token. Please generate new JWT token or switch to API token or username/password."
236+
message = "The JWT token might be invalid or expired or DB version doesn't support JWT token. Please generate new JWT token or switch to API token or username/password. Error: "+str(e)
234237
logger.error(f"Error occurred: {e}. {message}")
235-
raise RuntimeError(message) from e
238+
raise TigerGraphException(message)
236239

237240
def _locals(self, _locals: dict) -> str:
238241
del _locals["self"]
@@ -345,7 +348,7 @@ def _req(self, method: str, url: str, authMode: str = "token", headers: dict = N
345348
# This block should only be called once. When using 4.x, using port 9000 should fail so self.restppurl will change to host:14240/restpp
346349
# ----
347350
# Changes port to gsql port, adds /restpp to end to url, tries again, saves changes if successful
348-
if "/restpp" not in url or self.tgCloud:
351+
if self.restppPort in url and "/gsql" not in url and ("/restpp" not in url or self.tgCloud):
349352
newRestppUrl = self.host + ":"+self.gsPort+"/restpp"
350353
# In tgcloud /restpp can already be in the restpp url. We want to extract everything after the port or /restpp
351354
if self.tgCloud:

tests/test_jwtAuth.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from pyTigerGraphUnitTest import make_connection
66
from pyTigerGraph import TigerGraphConnection
7+
from pyTigerGraph.pyTigerGraphException import TigerGraphException
78

89

910
class TestJWTTokenAuth(unittest.TestCase):
@@ -43,7 +44,7 @@ def _requestJWTToken(self):
4344

4445

4546
def _test_jwtauth_3_9(self):
46-
with self.assertRaises(RuntimeError) as context:
47+
with self.assertRaises(TigerGraphException) as context:
4748
TigerGraphConnection(
4849
host=self.conn.host,
4950
jwtToken="fake.JWT.Token"
@@ -79,7 +80,7 @@ def _test_jwtauth_4_1_success(self):
7980

8081

8182
def _test_jwtauth_4_1_fail(self):
82-
with self.assertRaises(RuntimeError) as context:
83+
with self.assertRaises(TigerGraphException) as context:
8384
TigerGraphConnection(
8485
host=self.conn.host,
8586
jwtToken="invalid.JWT.Token"

tests/test_pyTigerGraphAuth.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from pyTigerGraph.pyTigerGraphException import TigerGraphException
66

77

8-
class test_pyTigerGraphPath(unittest.TestCase):
8+
class test_pyTigerGraphAuth(unittest.TestCase):
99
@classmethod
1010
def setUpClass(cls):
1111
cls.conn = make_connection()
@@ -61,27 +61,37 @@ def test_04_dropSecret(self):
6161
def test_05_getToken(self):
6262
res = self.conn.createSecret("secret5", True)
6363
token = self.conn.getToken(res["secret5"])
64-
self.assertIsInstance(token, tuple)
64+
if isinstance(token, str): # handle plaintext tokens from TG 3.x
65+
self.assertIsInstance(token, str)
66+
else:
67+
self.assertIsInstance(token, tuple)
6568
self.conn.dropSecret("secret5")
6669

70+
'''
6771
def test_06_refreshToken(self):
6872
# TG 4.x does not allow refreshing tokens
69-
self.conn.getToken(self.conn.createSecret())
7073
if self.conn._versionGreaterThan4_0():
7174
with self.assertRaises(TigerGraphException) as tge:
7275
self.conn.refreshToken("secret1")
7376
self.assertEqual("Refreshing tokens is only supported on versions of TigerGraph <= 4.0.0.", tge.exception.message)
7477
else:
7578
res = self.conn.createSecret("secret6", True)
7679
token = self.conn.getToken(res["secret6"])
77-
refreshed = self.conn.refreshToken(res["secret6"], token[0])
78-
self.assertIsInstance(refreshed, tuple)
79-
self.conn.dropSecret("secret6")
80-
80+
if isinstance(token, str): # handle plaintext tokens from TG 3.x
81+
refreshed = self.conn.refreshToken(res["secret6"], token)
82+
self.assertIsInstance(refreshed, str)
83+
else:
84+
refreshed = self.conn.refreshToken(res["secret6"], token[0])
85+
self.assertIsInstance(refreshed, tuple)
86+
self.conn.dropSecret("secret6")
87+
'''
8188
def test_07_deleteToken(self):
8289
res = self.conn.createSecret("secret7", True)
8390
token = self.conn.getToken(res["secret7"])
84-
self.assertTrue(self.conn.deleteToken(res["secret7"], token[0]))
91+
if isinstance(token, str): # handle plaintext tokens from TG 3.x
92+
self.assertTrue(self.conn.deleteToken(res["secret7"], token))
93+
else:
94+
self.assertTrue(self.conn.deleteToken(res["secret7"], token[0]))
8595
self.conn.dropSecret("secret7")
8696

8797
if __name__ == '__main__':

0 commit comments

Comments
 (0)