Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User: Check user exists or not before creating #7

Merged
merged 1 commit into from
Aug 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions lambda/index.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import boto3
import json
import random
import string
import os
import logging
Expand Down Expand Up @@ -76,13 +75,12 @@ def provision_db_and_user(master_secrets_json, secret_json):
pass

# Create user
sql = "CREATE USER {} WITH PASSWORD '{}' CREATEDB;".format(
username, password)
cursor.execute(sql)

# Create database
query = "CREATE DATABASE {};".format(database_name)
cursor.execute(query)
usernames = get_pg_usernames(cursor)
if username in usernames:
print("User already exists - skipping creation of user")
else:
sql = "CREATE USER {} WITH PASSWORD '{}' CREATEDB;".format(username, password)
cursor.execute(sql)

# Grant privileges
grant_sql = "GRANT CONNECT ON DATABASE {} TO {};".format(
Expand All @@ -102,6 +100,14 @@ def provision_db_and_user(master_secrets_json, secret_json):
raise e
# end def

def get_pg_usernames(cursor):
query = "SELECT u.usename AS username FROM pg_catalog.pg_user u;"
rows = []
cursor.execute(query)
for row in cursor:
rows.append(row[0])
return rows

def test_db_connection(username, password, database_name, rds_host, rds_port):
'''Test if the database can be connected using the new password'''

Expand Down