users.py 1.43 KB
Newer Older
Michal Pavlík's avatar
Michal Pavlík committed
1 2 3 4 5 6 7 8
from flask import request, escape
from errors import UserNotFound, RegistrationFailed, UnsupportedFileType
from werkzeug.utils import secure_filename
from models import User
from config import db, ALLOWED_IMAGE_FILES
import bcrypt
import os
import uuid
Michal Pavlík's avatar
Michal Pavlík committed
9 10

def get(id):
Michal Pavlík's avatar
Michal Pavlík committed
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
    user = User.query.get(id)

    if not user:
        raise UserNotFound(id)

    return user.json()


def upload_avatar(user=1):
    logged_user = User.query.get(user)

    avatar = request.files.get('avatar')
    ext = avatar.filename.split(".")[-1]

    if ext in ALLOWED_IMAGE_FILES:
        if "default" not in logged_user.avatarUrl:
            os.remove(logged_user.avatarUrl)

        url = f'./static/avatar_{uuid.uuid4()}.{ext}'
        avatar.save(url)

        logged_user.avatarUrl = url
        db.session.commit()
    else:
        raise UnsupportedFileType(ext)

    return logged_user.json()



Michal Pavlík's avatar
Michal Pavlík committed
41 42 43


def register():
Michal Pavlík's avatar
Michal Pavlík committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    data = request.json

    try:

        user = User.query.filter_by(username=data['username']).first()

        if user:
            raise RegistrationFailed("User with this name already exists.")

        salt = bcrypt.gensalt()
        pwd = bytes(data['password'], encoding='utf-8')
        user = User(
            username=escape(data['username']),
            password=bcrypt.hashpw(pwd, salt)
        )

        db.session.add(user)
        db.session.commit()

        return user.json()
    except Exception as e:
        raise RegistrationFailed(e)