Пример #1
0
def register():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    errors = defaultdict(list)
    if not username:
        errors['username'].append("Missing username parameter")
    else:
        if len(username) < 5:
            errors['username'].append("Username too short")
    if not password:
        errors['username'].append("Missing password parameter")
    else:
        if len(password) < 5:
            errors['password'].append("Password too short")

    if errors:
        return jsonify({"errors": errors}), 400

    user = User.query.filter_by(username=username).first()
    if user:
        errors['username'].append("User already exists")
        return jsonify({"errors": errors}), 409

    user = User(username=username, password=generate_password_hash(password))
    user.save()
    return jsonify(dict(msg="User created", user=serialize_user(user))), 200