nopaque/app/settings/json_routes.py

74 lines
2.2 KiB
Python
Raw Normal View History

from flask import abort, current_app, request
from flask_login import current_user, login_required, logout_user
from threading import Thread
import os
from app import db
from app.decorators import content_negotiation
from app.models import Avatar, User
from . import bp
@bp.route('/<hashid:user_id>', methods=['DELETE'])
@login_required
@content_negotiation(produces='application/json')
def delete_user(user_id):
def _delete_user(app, user_id):
with app.app_context():
user = User.query.get(user_id)
user.delete()
db.session.commit()
user = User.query.get_or_404(user_id)
if not (user == current_user or current_user.is_administrator()):
abort(403)
thread = Thread(
target=_delete_user,
args=(current_app._get_current_object(), user_id)
)
if user == current_user:
logout_user()
thread.start()
response_data = {
'message': f'User "{user.username}" marked for deletion'
}
return response_data, 202
@bp.route('/<hashid:user_id>/avatar', methods=['DELETE'])
@content_negotiation(produces='application/json')
def delete_profile_avatar(user_id):
def _delete_avatar(app, avatar_id):
with app.app_context():
avatar = Avatar.query.get(avatar_id)
avatar.delete()
db.session.commit()
user = User.query.get_or_404(user_id)
if user.avatar is None:
abort(404)
thread = Thread(
target=_delete_avatar,
args=(current_app._get_current_object(), user.avatar.id)
)
thread.start()
response_data = {
'message': f'Avatar marked for deletion'
}
return response_data, 202
@bp.route('/<hashid:user_id>/is_public', methods=['PUT'])
@login_required
@content_negotiation(consumes='application/json', produces='application/json')
def update_user_is_public(user_id):
is_public = request.json
if not isinstance(is_public, bool):
abort(400)
user = User.query.get_or_404(user_id)
user.is_public = is_public
db.session.commit()
response_data = {
'message': (
f'User "{user.username}" is now'
f' {"public" if is_public else "private"}'
),
'category': 'corpus'
}
return response_data, 200