Esempio n. 1
0
def add_user():
    request_data = request.get_json()

    if not request_data:
        return bad_request("No input data provided")

    try:
        data = AuthSchema().load(request_data)

        email = data.get('email')
        password = data.get('password')
        name = data.get('name')
        username = data.get('username')

        # check for existing user
        user = User.query.filter((User.email == email)
                                 | (User.username == username)).first()

        if user is not None:
            return bad_request('That user already exists.')

        # add new user to db
        profile = Profile(name=name)
        user = User(password=password)
        user.email = email
        user.username = username
        user.is_active = data.get('is_active') or False
        user.is_admin = data.get('is_admin') or False
        user.profile = profile
        user.save()

        response = jsonify(UserSchema().dump(user))
        response.status_code = 201
        response.headers['Location'] = url_for('admin.get_user', id=user.id)
        return response

    # handle errors
    except ValidationError as err:
        return error_response(422, err.messages)
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
Esempio n. 2
0
def add_user(name,
             email,
             username='',
             avatar='',
             bio='',
             is_admin=False,
             is_active=True,
             permissions=[]):

    profile = Profile(name=name, bio=bio)
    profile.avatar = avatar or profile.set_avatar(email)

    user = User(password='******')
    user.email = email
    user.username = username
    user.is_admin = is_admin
    user.is_active = is_active
    user.add_permissions(permissions)
    user.profile = profile

    user.save()
    return user