|
29 | 29 | from google.auth.credentials import Credentials |
30 | 30 | import google.auth.transport.requests |
31 | 31 | import OpenSSL |
| 32 | +import platform |
32 | 33 | import ssl |
33 | 34 | import socket |
34 | 35 | from tempfile import TemporaryDirectory |
@@ -108,6 +109,15 @@ def __init__(self, *args: Any) -> None: |
108 | 109 | super(CloudSQLIPTypeError, self).__init__(self, *args) |
109 | 110 |
|
110 | 111 |
|
| 112 | +class PlatformNotSupportedError(Exception): |
| 113 | + """ |
| 114 | + Raised when a feature is not supported on the current platform. |
| 115 | + """ |
| 116 | + |
| 117 | + def __init__(self, *args: Any) -> None: |
| 118 | + super(PlatformNotSupportedError, self).__init__(self, *args) |
| 119 | + |
| 120 | + |
111 | 121 | class InstanceMetadata: |
112 | 122 | ip_addrs: Dict[str, Any] |
113 | 123 | context: ssl.SSLContext |
@@ -564,15 +574,31 @@ def _connect_with_pytds( |
564 | 574 | raise ImportError( |
565 | 575 | 'Unable to import module "pytds." Please install and try again.' |
566 | 576 | ) |
567 | | - user = kwargs.pop("user") |
568 | | - db = kwargs.pop("db") |
569 | | - passwd = kwargs.pop("password") |
| 577 | + |
| 578 | + db = kwargs.pop("db", None) |
570 | 579 |
|
571 | 580 | # Create socket and wrap with context. |
572 | 581 | sock = ctx.wrap_socket( |
573 | 582 | socket.create_connection((ip_address, SERVER_PROXY_PORT)), |
574 | 583 | server_hostname=ip_address, |
575 | 584 | ) |
| 585 | + if kwargs.pop("active_directory_auth", False): |
| 586 | + if platform.system() == "Windows": |
| 587 | + # Ignore username and password if using active directory auth |
| 588 | + server_name = kwargs.pop("server_name") |
| 589 | + return pytds.connect( |
| 590 | + database=db, |
| 591 | + auth=pytds.login.SspiAuth(port=1433, server_name=server_name), |
| 592 | + sock=sock, |
| 593 | + **kwargs, |
| 594 | + ) |
| 595 | + else: |
| 596 | + raise PlatformNotSupportedError( |
| 597 | + "Active Directory authentication is currently only supported on Windows." |
| 598 | + ) |
| 599 | + |
| 600 | + user = kwargs.pop("user") |
| 601 | + passwd = kwargs.pop("password") |
576 | 602 | return pytds.connect( |
577 | 603 | ip_address, database=db, user=user, password=passwd, sock=sock, **kwargs |
578 | 604 | ) |
0 commit comments