Skip to content

Commit e57c480

Browse files
committed
Deprecate AuthMode and make default graph name empty
1 parent c19d78e commit e57c480

10 files changed

Lines changed: 58 additions & 180 deletions

pyTigerGraph/common/auth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def _prep_token_request(restppUrl: str,
8383
else:
8484
method = "POST"
8585
url = gsUrl + "/gsql/v1/tokens" # used for TG 4.x
86-
data = {"graph": graphname}
86+
data = {"graph": graphname} if graphname else {}
8787

8888
# alt_url and alt_data used to construct the method and url for functions run in TG version 3.x
8989
alt_url = restppUrl+"/requesttoken" # used for TG 3.x

pyTigerGraph/common/base.py

Lines changed: 25 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def excepthook(type, value, traceback):
3333

3434

3535
class PyTigerGraphCore(object):
36-
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
36+
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "",
3737
gsqlSecret: str = "", username: str = "tigergraph", password: str = "tigergraph",
3838
tgCloud: bool = False, restppPort: Union[int, str] = "9000",
3939
gsPort: Union[int, str] = "14240", gsqlVersion: str = "", version: str = "",
@@ -110,7 +110,8 @@ def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
110110
self.base64_credential = base64.b64encode(
111111
"{0}:{1}".format(self.username, self.password).encode("utf-8")).decode("utf-8")
112112

113-
self.authHeader = self._set_auth_header()
113+
# Detect auth mode automatically by checking if jwtToken or apiToken is provided
114+
self.authHeader, self.authMode = self._set_auth_header()
114115

115116
# TODO Eliminate version and use gsqlVersion only, meaning TigerGraph server version
116117
if gsqlVersion:
@@ -179,7 +180,7 @@ def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
179180
self.restppPort = restppPort
180181
self.restppUrl = self.host + ":" + self.restppPort
181182

182-
self.gsPort = ""
183+
self.gsPort = gsPort
183184
if self.tgCloud and (gsPort == "14240" or gsPort == "443"):
184185
self.gsPort = sslPort
185186
self.gsUrl = self.host + ":" + sslPort
@@ -216,11 +217,11 @@ def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
216217
def _set_auth_header(self):
217218
"""Set the authentication header based on available tokens or credentials."""
218219
if self.jwtToken:
219-
return {"Authorization": "Bearer " + self.jwtToken}
220+
return {"Authorization": "Bearer " + self.jwtToken}, "token"
220221
elif self.apiToken:
221-
return {"Authorization": "Bearer " + self.apiToken}
222+
return {"Authorization": "Bearer " + self.apiToken}, "token"
222223
else:
223-
return {"Authorization": "Basic {0}".format(self.base64_credential)}
224+
return {"Authorization": "Basic {0}".format(self.base64_credential)}, "pwd"
224225

225226
def _verify_jwt_token_support(self):
226227
try:
@@ -275,39 +276,32 @@ def _error_check(self, res: dict) -> bool:
275276
)
276277
return False
277278

278-
def _prep_req(self, authMode, headers, url, method, data):
279+
def _prep_req(self, headers, url, method, data):
279280
logger.info("entry: _req")
280281
if logger.level == logging.DEBUG:
281282
logger.debug("params: " + self._locals(locals()))
282283

283284
_headers = {}
284285

285286
# If JWT token is provided, always use jwtToken as token
286-
if authMode == "token":
287-
if isinstance(self.jwtToken, str) and self.jwtToken.strip() != "":
288-
token = self.jwtToken
289-
elif isinstance(self.apiToken, tuple):
290-
token = self.apiToken[0]
291-
elif isinstance(self.apiToken, str) and self.apiToken.strip() != "":
292-
token = self.apiToken
293-
else:
294-
token = None
287+
if isinstance(self.jwtToken, str) and self.jwtToken.strip() != "":
288+
token = self.jwtToken
289+
elif isinstance(self.apiToken, tuple):
290+
token = self.apiToken[0]
291+
elif isinstance(self.apiToken, str) and self.apiToken.strip() != "":
292+
token = self.apiToken
293+
else:
294+
token = None
295295

296-
if token:
297-
self.authHeader = {'Authorization': "Bearer " + token}
298-
_headers = self.authHeader
299-
else:
300-
self.authHeader = {
301-
'Authorization': 'Basic {0}'.format(self.base64_credential)}
302-
_headers = self.authHeader
303-
authMode = 'pwd'
304-
305-
if authMode == "pwd":
306-
if self.jwtToken:
307-
_headers = {'Authorization': "Bearer " + self.jwtToken}
308-
else:
309-
_headers = {'Authorization': 'Basic {0}'.format(
310-
self.base64_credential)}
296+
if token:
297+
self.authHeader = {'Authorization': "Bearer " + token}
298+
_headers = self.authHeader
299+
self.authMode = "token"
300+
else:
301+
self.authHeader = {
302+
'Authorization': 'Basic {0}'.format(self.base64_credential)}
303+
_headers = self.authHeader
304+
self.authMode = 'pwd'
311305

312306
if headers:
313307
_headers.update(headers)

pyTigerGraph/pyTigerGraph.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class TigerGraphConnection(pyTigerGraphVertex, pyTigerGraphEdge, pyTigerGraphUDT
2626
pyTigerGraphLoading, pyTigerGraphPath, pyTigerGraphDataset, object):
2727
"""Python wrapper for TigerGraph's REST++ and GSQL APIs"""
2828

29-
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
29+
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "",
3030
gsqlSecret: str = "", username: str = "tigergraph", password: str = "tigergraph",
3131
tgCloud: bool = False, restppPort: Union[int, str] = "9000",
3232
gsPort: Union[int, str] = "14240", gsqlVersion: str = "", version: str = "",

pyTigerGraph/pyTigerGraphAuth.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ def getToken(self,
239239
)
240240
self.apiToken = token
241241
self.authHeader = auth_header
242+
self.authMode = "token"
242243

243244
logger.info("exit: getToken")
244245
return token

pyTigerGraph/pyTigerGraphBase.py

Lines changed: 22 additions & 140 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
1414
conn = TigerGraphConnection(
1515
host="http://localhost",
16-
graphname="MyGraph",
16+
graphname="your_graph_name",
1717
username="tigergraph",
1818
password="tigergraph")
1919
@@ -64,7 +64,7 @@ def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
6464
protocol (http:// or https://). If `certPath` is `None` and the protocol is https,
6565
a self-signed certificate will be used.
6666
graphname:
67-
The default graph for running queries.
67+
The graph name for running queries. **Required** - must be specified.
6868
gsqlSecret:
6969
The secret key for GSQL. See https://docs.tigergraph.com/tigergraph-server/current/user-access/managing-credentials#_secrets.
7070
username:
@@ -102,144 +102,17 @@ def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
102102
TigerGraphException: In case on invalid URL scheme.
103103
104104
"""
105-
logger.info("entry: __init__")
106-
if logger.level == logging.DEBUG:
107-
logger.debug("params: " + self._locals(locals()))
105+
super().__init__(host=host, graphname=graphname, gsqlSecret=gsqlSecret,
106+
username=username, password=password, tgCloud=tgCloud,
107+
restppPort=restppPort, gsPort=gsPort, gsqlVersion=gsqlVersion,
108+
version=version, apiToken=apiToken, useCert=useCert, certPath=certPath,
109+
debug=debug, sslPort=sslPort, gcp=gcp, jwtToken=jwtToken)
108110

109-
inputHost = urlparse(host)
110-
if inputHost.scheme not in ["http", "https"]:
111-
raise TigerGraphException("Invalid URL scheme. Supported schemes are http and https.",
112-
"E-0003")
113-
self.netloc = inputHost.netloc
114-
self.host = "{0}://{1}".format(inputHost.scheme, self.netloc)
115-
if gsqlSecret != "":
116-
self.username = "__GSQL__secret"
117-
self.password = gsqlSecret
118-
else:
119-
self.username = username
120-
self.password = password
121-
self.graphname = graphname
122-
self.responseConfigHeader = {}
123-
self.awsIamHeaders = {}
124-
125-
self.jwtToken = jwtToken
126-
self.apiToken = apiToken
127-
self.base64_credential = base64.b64encode(
128-
"{0}:{1}".format(self.username, self.password).encode("utf-8")).decode("utf-8")
129-
130-
self.authHeader = self._set_auth_header()
131-
132-
# TODO Eliminate version and use gsqlVersion only, meaning TigerGraph server version
133-
if gsqlVersion:
134-
self.version = gsqlVersion
135-
elif version:
111+
if graphname == "MyGraph":
136112
warnings.warn(
137-
"The `version` parameter is deprecated; use the `gsqlVersion` parameter instead.",
138-
DeprecationWarning)
139-
self.version = version
140-
else:
141-
self.version = ""
142-
143-
if debug is not None:
144-
warnings.warn(
145-
"The `debug` parameter is deprecated; configure standard logging in your app.",
146-
DeprecationWarning)
147-
if not debug:
148-
sys.excepthook = excepthook # TODO Why was this necessary? Can it be removed?
149-
sys.tracebacklimit = None
150-
151-
self.schema = None
152-
153-
# TODO Remove useCert parameter
154-
if useCert is not None:
155-
warnings.warn(
156-
"The `useCert` parameter is deprecated; the need for a CA certificate is now determined by URL scheme.",
157-
DeprecationWarning)
158-
if inputHost.scheme == "http":
159-
self.downloadCert = False
160-
self.useCert = False
161-
self.certPath = ""
162-
elif inputHost.scheme == "https":
163-
if not certPath:
164-
self.downloadCert = True
165-
else:
166-
self.downloadCert = False
167-
self.useCert = True
168-
self.certPath = certPath
169-
self.sslPort = str(sslPort)
170-
171-
# TODO Remove gcp parameter
172-
if gcp:
173-
warnings.warn("The `gcp` parameter is deprecated.",
174-
DeprecationWarning)
175-
self.tgCloud = tgCloud or gcp
176-
if "tgcloud" in self.netloc.lower():
177-
try: # If get request succeeds, using TG Cloud instance provisioned after 6/20/2022
178-
self._get(self.host + "/api/ping", resKey="message")
179-
self.tgCloud = True
180-
# If get request fails, using TG Cloud instance provisioned before 6/20/2022, before new firewall config
181-
except requests.exceptions.RequestException:
182-
self.tgCloud = False
183-
except TigerGraphException:
184-
raise (TigerGraphException("Incorrect graphname."))
185-
186-
restppPort = str(restppPort)
187-
gsPort = str(gsPort)
188-
sslPort = str(sslPort)
189-
if restppPort == gsPort:
190-
self.restppPort = restppPort
191-
self.restppUrl = self.host + ":" + restppPort + "/restpp"
192-
elif (self.tgCloud and (restppPort == "9000" or restppPort == "443")):
193-
if restppPort == gsPort:
194-
sslPort = gsPort
195-
self.restppPort = sslPort
196-
self.restppUrl = self.host + ":" + sslPort + "/restpp"
197-
else:
198-
self.restppPort = restppPort
199-
self.restppUrl = self.host + ":" + self.restppPort
200-
201-
self.gsPort = gsPort
202-
if self.tgCloud and (gsPort == "14240" or gsPort == "443"):
203-
self.gsPort = sslPort
204-
self.gsUrl = self.host + ":" + sslPort
205-
else:
206-
self.gsPort = gsPort
207-
self.gsUrl = self.host + ":" + self.gsPort
208-
self.url = ""
209-
210-
if self.username.startswith("arn:aws:iam::"):
211-
import boto3
212-
from botocore.awsrequest import AWSRequest
213-
from botocore.auth import SigV4Auth
214-
# Prepare a GetCallerIdentity request.
215-
request = AWSRequest(
216-
method="POST",
217-
url="https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15",
218-
headers={
219-
'Host': 'sts.amazonaws.com'
220-
})
221-
# Get headers
222-
SigV4Auth(boto3.Session().get_credentials(),
223-
"sts", "us-east-1").add_auth(request)
224-
self.awsIamHeaders["X-Amz-Date"] = request.headers["X-Amz-Date"]
225-
self.awsIamHeaders["X-Amz-Security-Token"] = request.headers["X-Amz-Security-Token"]
226-
self.awsIamHeaders["Authorization"] = request.headers["Authorization"]
227-
228-
if self.jwtToken:
229-
self._verify_jwt_token_support()
230-
231-
self.asynchronous = False
232-
233-
logger.info("exit: __init__")
234-
235-
def _set_auth_header(self):
236-
"""Set the authentication header based on available tokens or credentials."""
237-
if self.jwtToken:
238-
return {"Authorization": "Bearer " + self.jwtToken}
239-
elif self.apiToken:
240-
return {"Authorization": "Bearer " + self.apiToken}
241-
else:
242-
return {"Authorization": "Basic {0}".format(self.base64_credential)}
113+
"The default graphname 'MyGraph' is deprecated. Please explicitly specify your graph name.",
114+
DeprecationWarning
115+
)
243116

244117
def _verify_jwt_token_support(self):
245118
try:
@@ -305,8 +178,8 @@ def _req(self, method: str, url: str, authMode: str = "token", headers: dict = N
305178
Returns:
306179
The (relevant part of the) response from the request (as a dictionary).
307180
"""
308-
_headers, _data, verify = self._prep_req(
309-
authMode, headers, url, method, data)
181+
# Deprecated: authMode
182+
_headers, _data, verify = self._prep_req(headers, url, method, data)
310183

311184
if "GSQL-TIMEOUT" in _headers:
312185
http_timeout = (10, int(int(_headers["GSQL-TIMEOUT"])/1000) + 10)
@@ -361,6 +234,7 @@ def _req(self, method: str, url: str, authMode: str = "token", headers: dict = N
361234
self.restppUrl = newRestppUrl
362235
self.restppPort = self.gsPort
363236
else:
237+
e.add_note(f"headers: {_headers}")
364238
raise e
365239

366240
return self._parse_req(res, jsonResponse, strictJson, skipCheck, resKey)
@@ -569,3 +443,11 @@ def _version_greater_than_4_0(self) -> bool:
569443
if version[0] >= "4" and version[1] > "0":
570444
return True
571445
return False
446+
447+
def _validate_graphname(self, operation_name=""):
448+
"""Validate that graphname is set for operations that require it."""
449+
if not self.graphname:
450+
raise TigerGraphException(
451+
f"Graph name is required for {operation_name}. Please specify graphname when creating the connection.",
452+
"E-0004"
453+
)

pyTigerGraph/pyTigerGraphSchema.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def upsertData(self, data: Union[str, object], atomic: bool = False, ackAll: boo
222222

223223
if logger.level == logging.DEBUG:
224224
logger.debug("return: " + str(res))
225-
logger.info("exit: getSchema")
225+
logger.info("exit: upsertData")
226226

227227
return res
228228

pyTigerGraph/pytgasync/pyTigerGraph.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class AsyncTigerGraphConnection(AsyncPyTigerGraphVertex, AsyncPyTigerGraphEdge,
2626
AsyncPyTigerGraphLoading, AsyncPyTigerGraphPath, AsyncPyTigerGraphDataset, object):
2727
"""Python wrapper for TigerGraph's REST++ and GSQL APIs"""
2828

29-
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
29+
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "",
3030
gsqlSecret: str = "", username: str = "tigergraph", password: str = "tigergraph",
3131
tgCloud: bool = False, restppPort: Union[int, str] = "9000",
3232
gsPort: Union[int, str] = "14240", gsqlVersion: str = "", version: str = "",

pyTigerGraph/pytgasync/pyTigerGraphAuth.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ async def getToken(self, secret: str = None, setToken: bool = True, lifetime: in
192192

193193
self.apiToken = token
194194
self.authHeader = auth_header
195+
self.authMode = "token"
195196

196197
logger.info("exit: getToken")
197198
return token

pyTigerGraph/pytgasync/pyTigerGraphBase.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
1717
conn = AsyncTigerGraphConnection(
1818
host="http://localhost",
19-
graphname="MyGraph",
19+
graphname="",
2020
username="tigergraph",
2121
password="tigergraph")
2222
@@ -39,7 +39,7 @@
3939

4040

4141
class AsyncPyTigerGraphBase(PyTigerGraphCore):
42-
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "MyGraph",
42+
def __init__(self, host: str = "http://127.0.0.1", graphname: str = "",
4343
gsqlSecret: str = "", username: str = "tigergraph", password: str = "tigergraph",
4444
tgCloud: bool = False, restppPort: Union[int, str] = "9000",
4545
gsPort: Union[int, str] = "14240", gsqlVersion: str = "", version: str = "",
@@ -130,8 +130,8 @@ async def _req(self, method: str, url: str, authMode: str = "token", headers: di
130130
Returns:
131131
The (relevant part of the) response from the request (as a dictionary).
132132
"""
133-
_headers, _data, verify = self._prep_req(
134-
authMode, headers, url, method, data)
133+
# Deprecated: authMode
134+
_headers, _data, verify = self._prep_req(headers, url, method, data)
135135

136136
if "GSQL-TIMEOUT" in _headers:
137137
http_timeout = (10, int(int(_headers["GSQL-TIMEOUT"])/1000) + 10)

pyTigerGraph/pytgasync/pyTigerGraphSchema.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ async def upsertData(self, data: Union[str, object], atomic: bool = False, ackAl
223223

224224
if logger.level == logging.DEBUG:
225225
logger.debug("return: " + str(res))
226-
logger.info("exit: getSchema")
226+
logger.info("exit: upsertData")
227227

228228
return res
229229

0 commit comments

Comments
 (0)