Skip to content

Commit 016bd4d

Browse files
authored
Merge pull request #517 from deepgram/feat/auth
feat: support short-lived tokens endpoint
2 parents b9561e4 + ffbf356 commit 016bd4d

File tree

10 files changed

+255
-0
lines changed

10 files changed

+255
-0
lines changed

deepgram/client.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,14 @@
248248
# ErrorResponse,
249249
)
250250

251+
# auth client classes
252+
from .clients import AuthRESTClient, AsyncAuthRESTClient
253+
254+
# auth client responses
255+
from .clients import (
256+
GrantTokenResponse,
257+
)
258+
251259
# manage client classes/input
252260
from .clients import ManageClient, AsyncManageClient
253261
from .clients import (
@@ -495,6 +503,20 @@ def asyncmanage(self):
495503
"""
496504
return self.Version(self._config, "asyncmanage")
497505

506+
@property
507+
def auth(self):
508+
"""
509+
Returns an AuthRESTClient instance for managing short-lived tokens.
510+
"""
511+
return self.Version(self._config, "auth")
512+
513+
@property
514+
def asyncauth(self):
515+
"""
516+
Returns an AsyncAuthRESTClient instance for managing short-lived tokens.
517+
"""
518+
return self.Version(self._config, "asyncauth")
519+
498520
@property
499521
@deprecation.deprecated(
500522
deprecated_in="3.4.0",
@@ -606,6 +628,14 @@ def v(self, version: str = ""):
606628
parent = "selfhosted"
607629
filename = "async_client"
608630
classname = "AsyncSelfHostedClient"
631+
case "auth":
632+
parent = "auth"
633+
filename = "client"
634+
classname = "AuthRESTClient"
635+
case "asyncauth":
636+
parent = "auth"
637+
filename = "async_client"
638+
classname = "AsyncAuthRESTClient"
609639
case _:
610640
self._logger.error("parent unknown: %s", self._parent)
611641
self._logger.debug("Version.v LEAVE")

deepgram/clients/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,12 @@
312312
Balance,
313313
)
314314

315+
# auth
316+
from .auth import AuthRESTClient, AsyncAuthRESTClient
317+
from .auth import (
318+
GrantTokenResponse,
319+
)
320+
315321
# selfhosted
316322
from .selfhosted import (
317323
OnPremClient,

deepgram/clients/auth/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
from .client import AuthRESTClient
6+
from .client import AsyncAuthRESTClient
7+
from .client import (
8+
GrantTokenResponse,
9+
)

deepgram/clients/auth/client.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
from .v1.client import AuthRESTClient as AuthRESTClientLatest
6+
from .v1.async_client import AsyncAuthRESTClient as AsyncAuthRESTClientLatest
7+
from .v1.response import GrantTokenResponse as GrantTokenResponseLatest
8+
9+
AuthRESTClient = AuthRESTClientLatest
10+
AsyncAuthRESTClient = AsyncAuthRESTClientLatest
11+
GrantTokenResponse = GrantTokenResponseLatest

deepgram/clients/auth/v1/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Copyright 2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
from .client import AuthRESTClient
5+
from .async_client import AsyncAuthRESTClient
6+
from .response import (
7+
GrantTokenResponse,
8+
)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Copyright 2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
import logging
6+
7+
from ....utils import verboselogs
8+
from ....options import DeepgramClientOptions
9+
from ...common import AbstractAsyncRestClient
10+
from .response import GrantTokenResponse
11+
12+
13+
class AsyncAuthRESTClient(AbstractAsyncRestClient):
14+
"""
15+
A client class for handling authentication endpoints.
16+
Provides method for generating a temporary JWT token.
17+
"""
18+
19+
_logger: verboselogs.VerboseLogger
20+
_config: DeepgramClientOptions
21+
_endpoint: str
22+
23+
def __init__(self, config: DeepgramClientOptions):
24+
self._logger = verboselogs.VerboseLogger(__name__)
25+
self._logger.addHandler(logging.StreamHandler())
26+
self._logger.setLevel(config.verbose)
27+
self._config = config
28+
self._endpoint = "v1/auth/grant"
29+
super().__init__(config)
30+
31+
async def grant_token(self):
32+
"""
33+
Generates a temporary JWT with a 30 second TTL.
34+
35+
Returns:
36+
GrantTokenResponse: An object containing the authentication token and its expiration time.
37+
38+
Raises:
39+
DeepgramTypeError: Raised for known API errors.
40+
"""
41+
self._logger.debug("AuthRestClient.grant_token ENTER")
42+
43+
url = f"{self._config.url}/{self._endpoint}"
44+
self._logger.info("url: %s", url)
45+
result = await self.post(url, headers={"Authorization": f"Token {self._config.api_key}"})
46+
self._logger.info("json: %s", result)
47+
res = GrantTokenResponse.from_json(result)
48+
self._logger.verbose("result: %s", res)
49+
self._logger.notice("grant_token succeeded")
50+
self._logger.debug("AuthRestClient.grant_token LEAVE")
51+
return res

deepgram/clients/auth/v1/client.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Copyright 2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
import logging
6+
7+
from ....utils import verboselogs
8+
from ....options import DeepgramClientOptions
9+
from ...common import AbstractSyncRestClient
10+
from .response import GrantTokenResponse
11+
12+
13+
class AuthRESTClient(AbstractSyncRestClient):
14+
"""
15+
A client class for handling authentication endpoints.
16+
Provides method for generating a temporary JWT token.
17+
"""
18+
19+
_logger: verboselogs.VerboseLogger
20+
_config: DeepgramClientOptions
21+
_endpoint: str
22+
23+
def __init__(self, config: DeepgramClientOptions):
24+
self._logger = verboselogs.VerboseLogger(__name__)
25+
self._logger.addHandler(logging.StreamHandler())
26+
self._logger.setLevel(config.verbose)
27+
self._config = config
28+
self._endpoint = "v1/auth/grant"
29+
super().__init__(config)
30+
31+
def grant_token(self):
32+
"""
33+
Generates a temporary JWT with a 30 second TTL.
34+
35+
Returns:
36+
GrantTokenResponse: An object containing the authentication token and its expiration time.
37+
38+
Raises:
39+
DeepgramTypeError: Raised for known API errors.
40+
"""
41+
self._logger.debug("AuthRestClient.grant_token ENTER")
42+
43+
url = f"{self._config.url}/{self._endpoint}"
44+
self._logger.info("url: %s", url)
45+
result = self.post(url, headers={"Authorization": f"Token {self._config.api_key}"})
46+
self._logger.info("json: %s", result)
47+
res = GrantTokenResponse.from_json(result)
48+
self._logger.verbose("result: %s", res)
49+
self._logger.notice("grant_token succeeded")
50+
self._logger.debug("AuthRestClient.grant_token LEAVE")
51+
return res

deepgram/clients/auth/v1/response.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
from dataclasses import dataclass, field
6+
from dataclasses_json import config as dataclass_config
7+
8+
from ...common import (
9+
BaseResponse,
10+
)
11+
12+
@dataclass
13+
class GrantTokenResponse(BaseResponse):
14+
"""
15+
The response object for the authentication grant token endpoint.
16+
"""
17+
access_token: str = field(
18+
metadata=dataclass_config(field_name='access_token'),
19+
default="",
20+
)
21+
expires_in: int = field(
22+
metadata=dataclass_config(field_name='expires_in'),
23+
default=30,
24+
)

examples/auth/async_token/main.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
import asyncio
6+
import os
7+
from dotenv import load_dotenv
8+
from deepgram.utils import verboselogs
9+
10+
from deepgram import (
11+
DeepgramClient,
12+
DeepgramClientOptions
13+
)
14+
15+
load_dotenv()
16+
17+
async def main():
18+
try:
19+
# STEP 1 Create a Deepgram client using the DEEPGRAM_API_KEY from your environment variables
20+
config = DeepgramClientOptions(
21+
verbose=verboselogs.SPAM,
22+
)
23+
deepgram: DeepgramClient = DeepgramClient(os.getenv("DEEPGRAM_API_KEY", ""), config)
24+
25+
# STEP 2 Call the grant_token method on the auth rest class
26+
response = await deepgram.asyncauth.v("1").grant_token()
27+
print(f"response: {response}\n\n")
28+
except Exception as e:
29+
print(f"Exception: {e}")
30+
31+
32+
if __name__ == "__main__":
33+
asyncio.run(main())

examples/auth/token/main.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
import os
6+
from dotenv import load_dotenv
7+
from deepgram.utils import verboselogs
8+
9+
from deepgram import (
10+
DeepgramClient,
11+
DeepgramClientOptions
12+
)
13+
14+
load_dotenv()
15+
16+
def main():
17+
try:
18+
# STEP 1 Create a Deepgram client using the DEEPGRAM_API_KEY from your environment variables
19+
config = DeepgramClientOptions(
20+
verbose=verboselogs.SPAM,
21+
)
22+
deepgram: DeepgramClient = DeepgramClient(os.getenv("DEEPGRAM_API_KEY", ""), config)
23+
24+
# STEP 2 Call the grant_token method on the auth rest class
25+
response = deepgram.auth.v("1").grant_token()
26+
print(f"response: {response}\n\n")
27+
except Exception as e:
28+
print(f"Exception: {e}")
29+
30+
31+
if __name__ == "__main__":
32+
main()

0 commit comments

Comments
 (0)