|
1 | 1 | from azure_credential_utils import get_azure_credential |
2 | 2 | import psycopg2 |
| 3 | +from psycopg2 import sql |
3 | 4 |
|
| 5 | +principalId = "principalId" |
4 | 6 | user = "managedIdentityName" |
5 | 7 | host = "serverName" |
6 | 8 | dbname = "postgres" |
7 | 9 |
|
8 | 10 |
|
| 11 | +def grant_permissions(cursor, dbname, schema_name, principal_id): |
| 12 | + """ |
| 13 | + Grants database and schema-level permissions to a specified principal. |
| 14 | +
|
| 15 | + Parameters: |
| 16 | + - cursor: psycopg2 cursor object for database operations. |
| 17 | + - dbname: Name of the database to grant CONNECT permission. |
| 18 | + - schema_name: Name of the schema to grant table-level permissions. |
| 19 | + - principal_id: ID of the principal (role or user) to grant permissions. |
| 20 | + """ |
| 21 | + |
| 22 | + # Check if the principal exists in the database |
| 23 | + cursor.execute( |
| 24 | + sql.SQL("SELECT 1 FROM pg_roles WHERE rolname = {principal}").format( |
| 25 | + principal=sql.Literal(principal_id) |
| 26 | + ) |
| 27 | + ) |
| 28 | + if cursor.fetchone() is None: |
| 29 | + add_principal_user_query = sql.SQL( |
| 30 | + "SELECT * FROM pgaadauth_create_principal({principal}, false, false)" |
| 31 | + ) |
| 32 | + cursor.execute( |
| 33 | + add_principal_user_query.format( |
| 34 | + principal=sql.Literal(principal_id), |
| 35 | + ) |
| 36 | + ) |
| 37 | + |
| 38 | + # Grant CONNECT on database |
| 39 | + grant_connect_query = sql.SQL("GRANT CONNECT ON DATABASE {database} TO {principal}") |
| 40 | + cursor.execute( |
| 41 | + grant_connect_query.format( |
| 42 | + database=sql.Identifier(dbname), |
| 43 | + principal=sql.Identifier(principal_id), |
| 44 | + ) |
| 45 | + ) |
| 46 | + print(f"Granted CONNECT on database '{dbname}' to '{principal_id}'") |
| 47 | + |
| 48 | + # Grant SELECT, INSERT, UPDATE, DELETE on schema tables |
| 49 | + grant_permissions_query = sql.SQL( |
| 50 | + "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA {schema} TO {principal}" |
| 51 | + ) |
| 52 | + cursor.execute( |
| 53 | + grant_permissions_query.format( |
| 54 | + schema=sql.Identifier(schema_name), |
| 55 | + principal=sql.Identifier(principal_id), |
| 56 | + ) |
| 57 | + ) |
| 58 | + |
| 59 | + |
9 | 60 | # Acquire the access token |
10 | 61 | cred = get_azure_credential() |
11 | 62 | access_token = cred.get_token("https://ossrdbms-aad.database.windows.net/.default") |
|
81 | 132 | ) |
82 | 133 | conn.commit() |
83 | 134 |
|
| 135 | +if principalId and principalId.strip(): |
| 136 | + grant_permissions(cursor, dbname, "public", principalId) |
| 137 | + conn.commit() |
84 | 138 |
|
85 | 139 | cursor.execute("ALTER TABLE public.conversations OWNER TO azure_pg_admin;") |
86 | 140 | cursor.execute("ALTER TABLE public.messages OWNER TO azure_pg_admin;") |
|
0 commit comments