aboutsummaryrefslogtreecommitdiff
path: root/api/user/avatar.py
blob: d3c86b87c0395afd3fe649e3171a4afbbfddf7ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from flask import Blueprint, request, Response
from db import cursor
from auth.login_token import token_login
from user.info import valid_user_id
from os.path import exists
from codecs import decode

default_avatar = open("database/avatars/default.png", "rb").read()

avatar = Blueprint('avatar', __name__)

@avatar.route('/avatar', methods = ["GET"])
def get_avatar():
    token = request.cookies.get("token") or ""
    login = token_login(token) or ""

    user_id = request.args.get("id") or login
    if not user_id: return "", 400
    if not valid_user_id(user_id): return "", 403

    avatar_path = f"database/avatars/{user_id}.png"
    avatar = ""
    if exists(avatar_path):
        avatar = open(avatar_path, "rb").read()
    return Response(avatar or default_avatar, 200, mimetype="image/png")

@avatar.route('/avatar', methods = ["POST"]) #TODO: pillow image size validation (client side resize)
def update_avatar():
    token = request.cookies.get("token") or ""
    if not token: return "", 401
    if not request.data: return "", 400

    login = token_login(token) or ""
    if not login: return "", 403

    open(f"database/avatars/{login}.png", "wb").write(decode(request.data, "base64"))

    return "", 200

dynamic_route = ["/user", avatar]