Beispiel #1
0
def register():
    """Returns the registered user with token if success. """
    data = MultiDict(dict(**request.json))
    form = RegisterForm(data, csrf_enabled=False)
    if form.validate():
        # Check if email is used.
        if users.first(email=form.email.data):
            raise LadyMarryError(
                'Email %s is already registered.' % form.email.data)

        # TODO: Clean up this logic.
        if form.wedding_date.data:
            user = users.register_user(email=form.email.data,
                                       password=form.password.data,
                                       first_name=form.first_name.data,
                                       last_name=form.last_name.data,
                                       wedding_date=form.wedding_date.data)
            schedulers.schedule_tasks(user)
        else:
            user = users.register_user(email=form.email.data,
                                       password=form.password.data,
                                       first_name=form.first_name.data,
                                       last_name=form.last_name.data,
                                       wedding_date=form.wedding_date.data)

        # Generate JWT token for this user.
        user.token = generate_token(user)
        return user
    else:
        logger.info('Register fail: %s', form.errors)
        raise LadyMarryFormError(form.errors)
def test_create_model_test(testapp, db, user):
    headers = gen_auth_header(generate_token(user))

    model = create_test_mlmodel(
        user, {
            'duration': 549,
            'scatterplot': 'ridge_scatterplot.png',
            'weightmap': 'ridge_weightmap.nii.gz'
        })

    db.session.add(model)
    db.session.commit()

    put_weighmap_file(model.id, 'ridge_weightmap.nii.gz')

    payload = {
        'modelId': model.id,
        'name': 'Model Test',
        'selectedImages': {
            504: [7513, 7516, 7573]
        }
    }

    response = testapp.post_json('/api/tests', payload, headers=headers)
    assert response.status_code == 201
    modeltest = ModelTest.query.get(1)
    assert modeltest.state == ModelTest.STATE_SUCCESS
    assert modeltest.output_data['collections'] == {
        '504': {
            'id': 504,
            'name': 'Single Subject Thermal Pain'
        }
    }
def test_create_masked_mlmodel(testapp, user):
    name = 'Test %s' % uuid.uuid4()

    headers = gen_auth_header(generate_token(user))

    payload = {
        'algorithm': nv_test_data.ALGORITHM,
        'data': nv_test_data.TARGET_DATA_IMG_IDS,
        'collections': {
            504: {
                'name': 'Single Subject Thermal Pain'
            }
        },
        'cv': {
            'type': 'kfolds',
            'value': '10'
        },
        'label': {
            'name': 'PainLevel',
            'index': 13
        },
        'mask': {
            'id': 18650
        },
        'name': name
    }

    response = testapp.post_json('/api/models', payload, headers=headers)
    assert response.status_code == 201
    model = MLModel.query.filter_by(name=name).first()
    assert model.training_state == MLModel.STATE_SUCCESS
Beispiel #4
0
 def post(self, username):
     """Hello Users."""
     args = self.wanted.parse_args()
     user = User.query.filter(User.username == username).first()
     if user and user.check_password(args['password']):
         return {'status': 200, 'message': generate_token(user)}
     return {'status': 404, 'message': 'Not Found'}, 404
Beispiel #5
0
def test_create_masked_mlmodel(testapp, user):
    name = 'Test %s' % uuid.uuid4()

    headers = gen_auth_header(generate_token(user))

    payload = {
        'algorithm': nv_test_data.ALGORITHM,
        'data': nv_test_data.TARGET_DATA_IMG_IDS,
        'collections': {
            504: {
                'name': 'Single Subject Thermal Pain'
            }
        },
        'cv': {
            'type': 'kfolds',
            'value': '10'
        },
        'label': {
            'name': 'PainLevel',
            'index': 13
        },
        'mask': {
            'id': 18650
        },
        'name': name
    }

    response = testapp.post_json('/api/models',
                                 payload,
                                 headers=headers)
    assert response.status_code == 201
    model = MLModel.query.filter_by(name=name).first()
    assert model.training_state == MLModel.STATE_SUCCESS
Beispiel #6
0
def test_create_model_test(testapp, db, user):
    headers = gen_auth_header(generate_token(user))

    model = create_test_mlmodel(user, {
        'duration': 549,
        'scatterplot': 'ridge_scatterplot.png',
        'weightmap': 'ridge_weightmap.nii.gz'
    })

    db.session.add(model)
    db.session.commit()

    put_weighmap_file(model.id, 'ridge_weightmap.nii.gz')

    payload = {
        'modelId': model.id,
        'name': 'Model Test',
        'selectedImages': {
            504: [7513, 7516, 7573]
        }
    }

    response = testapp.post_json('/api/tests',
                                 payload,
                                 headers=headers)
    assert response.status_code == 201
    modeltest = ModelTest.query.get(1)
    assert modeltest.state == ModelTest.STATE_SUCCESS
    assert modeltest.output_data['collections'] == {
        '504': {'id': 504, 'name': 'Single Subject Thermal Pain'}}
def authorized():
    # Patch for proxy
    if current_app.debug:
        session['neurovault_oauthredir'] = 'http://localhost:3000/signin/authorized'
    else:
        session['neurovault_oauthredir'] = url_for('.authorized',
                                                   _external=True)

    oauth_client = oauth.remote_apps['neurovault']
    resp = oauth_client.authorized_response()

    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error'],
            request.args['error_description']
        )
    if isinstance(resp, OAuthException):
        return 'Access denied: reason=%s error=%s' % (
            resp.message,
            resp.data
        )

    session['neurovault_oauth_token'] = (resp['access_token'], '')

    user_data = get_external_user_data(oauth_client)

    try:
        connection = find_connection(Connection.NEUROVAULT,
                                     unicode(user_data['id']))
    except NoResultFound:
        user = create_user(user_data)
        db.session.add(user)
        db.session.commit()
        connection = create_connection(Connection.NEUROVAULT,
                                       user, user_data)

        db.session.add(connection)
        db.session.commit()

    connection.access_token = resp['access_token']
    connection.refresh_token = resp['refresh_token']
    db.session.commit()

    return render_template('authorized.html',
                           token=generate_token(connection.user))
Beispiel #8
0
def create_user():
    try:
        json = request.json
        if json is None:
            raise InvalidUsage('payload is empty or Mime is not JSON')

        username = json['username']
        password = json['password']
        email = json['email']

        if username in [None, ""] or email in [None, ""
                                               ] or password in [None, ""]:
            raise InvalidUsage('Empty required arguments', 400)

        if not isinstance(username, basestring) or \
           not isinstance(email,    basestring) or \
           not isinstance(password, basestring):
            raise InvalidUsage('username, email and password must be strings',
                               400)

        username = username.lower()
        email = email.lower()

        if User.query.filter_by(name=username).first() is not None:
            raise InvalidUsage('User already exists', 400)

        if User.query.filter_by(email=email).first() is not None:
            raise InvalidUsage('Email already exists', 400)

        user = User(name=username, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        return jsonify(
            {'token': generate_token(authenticate(email, password))}), 201

    except KeyError as e:
        raise InvalidUsage(
            'Missing required arguments ({0})'.format(e.message), 400)
    except werkzeug_exceptions.BadRequest as e:
        raise InvalidUsage('payload is not a valid JSON')
    except Exception as e:
        raise InvalidUsage(
            'Something bad happened. Please blame Kadi for this ({0})'.format(
                e.message), 500)
Beispiel #9
0
def test_create_neurovault_image_test(testapp, db, user):
    headers = gen_auth_header(generate_token(user))

    payload = {
        'neurovaultImageId': 43943,
        'name': 'Neurovault Image Test',
        'selectedImages': {
            504: [7513, 7516, 7573]
        }
    }

    response = testapp.post_json('/api/tests',
                                 payload,
                                 headers=headers)
    assert response.status_code == 201
    modeltest = ModelTest.query.get(1)
    assert modeltest.state == ModelTest.STATE_SUCCESS
    assert modeltest.output_data['collections'] == {
        '504': {'id': 504, 'name': 'Single Subject Thermal Pain'}}
def test_create_neurovault_image_test(testapp, db, user):
    headers = gen_auth_header(generate_token(user))

    payload = {
        'neurovaultImageId': 43943,
        'name': 'Neurovault Image Test',
        'selectedImages': {
            504: [7513, 7516, 7573]
        }
    }

    response = testapp.post_json('/api/tests', payload, headers=headers)
    assert response.status_code == 201
    modeltest = ModelTest.query.get(1)
    assert modeltest.state == ModelTest.STATE_SUCCESS
    assert modeltest.output_data['collections'] == {
        '504': {
            'id': 504,
            'name': 'Single Subject Thermal Pain'
        }
    }
Beispiel #11
0
def create_user():
    try:
        json = request.json
        if json is None:
            raise InvalidUsage("payload is empty or Mime is not JSON")

        username = json["username"]
        password = json["password"]
        email = json["email"]

        if username in [None, ""] or email in [None, ""] or password in [None, ""]:
            raise InvalidUsage("Empty required arguments", 400)

        if (
            not isinstance(username, basestring)
            or not isinstance(email, basestring)
            or not isinstance(password, basestring)
        ):
            raise InvalidUsage("username, email and password must be strings", 400)

        username = username.lower()
        email = email.lower()

        if User.query.filter_by(name=username).first() is not None:
            raise InvalidUsage("User already exists", 400)

        if User.query.filter_by(email=email).first() is not None:
            raise InvalidUsage("Email already exists", 400)

        user = User(name=username, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        return jsonify({"token": generate_token(authenticate(email, password))}), 201

    except KeyError as e:
        raise InvalidUsage("Missing required arguments ({0})".format(e.message), 400)
    except werkzeug_exceptions.BadRequest as e:
        raise InvalidUsage("payload is not a valid JSON")
    except Exception as e:
        raise InvalidUsage("Something bad happened. Please blame Kadi for this ({0})".format(e.message), 500)
Beispiel #12
0
def test_generate_token(user, jwt, app):
    with app.test_request_context():
        token = flask_jwt.generate_token(user)
        assert token == jwt.encode_callback(jwt.payload_callback(user))
Beispiel #13
0
def token(user):
    """Returns a JWT"""
    return generate_token(user)