pyceo/ceod/api/database.py

45 lines
1.8 KiB
Python

from flask import Blueprint, request
from zope import component
from ceod.api.utils import authz_restrict_to_staff, authz_restrict_to_syscom, \
user_is_in_group, requires_authentication_no_realm, \
create_streaming_response, development_only
from ceo_common.errors import UserNotFoundError, DatabaseConnectionError
from ceo_common.interfaces import IDatabaseService
bp = Blueprint('db', __name__)
# could combine create_mysql_db and create_postgresql_db into one function
# catch other less expected errors (mysql or psql error)
# handle if user somehow dropped their database
@bp.route('/mysql/<username>', methods=['POST'])
@requires_authentication_no_realm
def create_mysql_db(auth_user: str, username: str):
if not (auth_user == username or user_is_in_group(auth_user, 'syscom')):
return {'error': "not authorized to create databases for others"}, 403
try:
db_srv = component.getUtility(IDatabaseService, 'mysql')
password = db_srv.create_db(username)
return {'password': password}
except UserNotFoundError:
return {'error': 'user not found'}, 404
except DatabaseConnectionError:
return {'error': 'unable to connect to mysql server'}, 400
@bp.route('/postgresql/<username>', methods=['POST'])
@requires_authentication_no_realm
def create_postgresql_db(auth_user: str, username: str):
if not (auth_user == username or user_is_in_group(auth_user, 'syscom')):
return {'error': "not authorized to create databases for others"}, 403
try:
db_srv = component.getUtility(IDatabaseService, 'postgresql')
password = db_srv.create_db(username)
return {'password': password}
except UserNotFoundError:
return {'error': 'user not found'}, 404
except DatabaseConnectionError:
return {'error': 'unable to connect to postgresql server'}, 400