pyceo/ceo/cli/postgresql.py

93 lines
2.6 KiB
Python

import click
import os
from zope import component
from ceo_common.interfaces import IConfig
from ..utils import http_post, http_get, http_delete
from .utils import handle_sync_response, check_file_path, check_if_in_development
def psql_cli_response(file, username, password):
cfg_srv = component.getUtility(IConfig)
psql_host = cfg_srv.get('postgresql_host')
info = f"""PostgreSQL Database Information for {username}
Your new PostgreSQL database was created. To connect, use the following options:
Database: {username}
Username: {username}
Password: {password}
Host: {psql_host}
On {psql_host} to connect using the PostgreSQL command-line client use
psql -d {username} -U {username} -W
From other CSC machines you can connect using
psql -d {username} -h {psql_host} -U {username} -W
"""
with click.open_file(file, "w") as f:
f.write(info)
os.chown(file, username, username)
os.chmod(file, 0o640)
click.echo(f"""PostgreSQL database created
Connection Information:
Database: {username}
Username: {username}
Password: {password}
Host: {psql_host}
Settings and more info has been written to {file}""")
@click.group(short_help='Perform operations on PostgreSQL')
def postgresql():
pass
@postgresql.command(short_help='Create a PostgreSQL database for a user')
@click.argument('username')
def create(username):
resp = http_get(f'/api/members/{username}')
result = handle_sync_response(resp)
info_file_path = os.path.join(result['home_directory'], "ceo-psql-info")
check_file_path(info_file_path)
resp = http_post(f'/api/db/postgresql/{username}')
result = handle_sync_response(resp)
password = result['password']
psql_cli_response(info_file_path, username, password)
@postgresql.command(short_help='Reset the password of a PostgreSQL user')
@click.argument('username')
def pwreset(username):
resp = http_get(f'/api/members/{username}')
result = handle_sync_response(resp)
info_file_path = os.path.join(result['home_directory'], "ceo-psql-info")
check_file_path(info_file_path)
resp = http_post(f'/api/db/postgresql/{username}/pwreset')
result = handle_sync_response(resp)
password = result['password']
psql_cli_response(info_file_path, username, password)
@postgresql.command(short_help="Delete the database of a PostgreSQL user")
@click.argument('username')
def delete(username):
check_if_in_development()
click.confirm("Are you sure?", abort=True)
resp = http_delete(f'/api/db/postgresql/{username}')
handle_sync_response(resp)