Example #1
1
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client()
        self.basedir = os.path.abspath(os.path.dirname(__file__))
        db.create_all()
        test_password = '******'
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)

        # set the vars for the connection
        self.cmisUrl =  \
            'https://alfresco.oceanobservatories.org/alfresco/s/api/cmis'
        self.cmisUsername = '******'
        self.cmisPassword = '******'
        self.cmisId = 'c161bc66-4f7e-4a4f-b5f2-aac9fbf1d3cd'

        # cmis is tested elsewhere

        from cmislib.model import CmisClient
        client = CmisClient(self.cmisUrl, self.cmisUsername, self.cmisPassword)
        repo = client.getRepository(self.cmisId)
Example #2
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        from sqlalchemy.orm.mapper import configure_mappers
        configure_mappers()
        db.create_all()

        test_username = '******'
        test_password = '******'
        Organization.insert_org()
        User.insert_user(username=test_username,
                         password=test_password,
                         email='*****@*****.**')

        OperatorEventType.insert_operator_event_types()

        self.client = self.app.test_client(use_cookies=False)

        UserScope.insert_scopes()

        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)

        db.session.add(admin)
        db.session.commit()

        joe = User.insert_user(username='******',
                               password='******',
                               email='*****@*****.**')
        bob = User.insert_user(username='******',
                               password='******',
                               email='*****@*****.**')
Example #3
0
def deploy(password, bulkload):
    from flask.ext.migrate import upgrade
    from ooiservices.app.models import User, UserScope, UserScopeLink, Array
    from ooiservices.app.models import PlatformDeployment, InstrumentDeployment, Stream, StreamParameterLink
    from sh import psql
    #Create the local database
    app.logger.info('Creating DEV and TEST Databases')
    psql('-c', 'create database ooiuidev;', '-U', 'postgres')
    psql('ooiuidev', '-c', 'create schema ooiui')
    psql('ooiuidev', '-c', 'create extension postgis')
    #Create the local test database
    psql('-c', 'create database ooiuitest;', '-U', 'postgres')
    psql('ooiuitest', '-c', 'create schema ooiui')
    psql('ooiuitest', '-c', 'create extension postgis')
    db.create_all()
    if bulkload:
        with open('db/ooiui_schema_data.sql') as f:
            psql('ooiuidev', _in=f)
        app.logger.info('Bulk test data loaded.')

    # migrate database to latest revision
    #upgrade()
    UserScope.insert_scopes()
    app.logger.info('Insert default user, name: admin')
    User.insert_user(password=password)
    admin = User.query.first()
    admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
    db.session.add(admin)
    db.session.commit()
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        from sqlalchemy.orm.mapper import configure_mappers
        configure_mappers()
        db.create_all()

        test_username = '******'
        test_password = '******'
        Organization.insert_org()
        User.insert_user(username=test_username, password=test_password, email='*****@*****.**')


        OperatorEventType.insert_operator_event_types()

        self.client = self.app.test_client(use_cookies=False)

        UserScope.insert_scopes()

        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='asset_manager').first()
        admin.scopes.append(scope)

        db.session.add(admin)
        db.session.commit()

        joe = User.insert_user(username='******', password='******', email='*****@*****.**')
        bob = User.insert_user(username='******', password='******', email='*****@*****.**')
Example #5
0
 def setUp(self):
     self.app = create_app('TESTING_CONFIG')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client(use_cookies=False)
     User.insert_user(username=test_username, password=test_password)
     UserScope.insert_scopes()
Example #6
0
 def setUp(self):
     self.app = create_app('TESTING_CONFIG')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client(use_cookies=False)
     Organization.insert_org()
     User.insert_user(username=test_username, password=test_password)
     UserScope.insert_scopes()
Example #7
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = '******'
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)
    def setUp(self):
        self.app = create_app("TESTING_CONFIG")
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = "******"
        Organization.insert_org()
        User.insert_user(password=test_password, email="test@localhost")

        self.client = self.app.test_client(use_cookies=False)
Example #9
0
def add_admin_user(username, password, first_name, last_name, email, org_name):
    '''
    Creates a 'user_admin' scoped user using the supplied username and password
    :param username:
    :param password:
    :return:
    '''
    app.logger.info('Insert user, name: %s' % username)
    User.insert_user(username=username, password=password, first_name=first_name, last_name=last_name, email=email, org_name=org_name)
    admin = User.query.filter_by(user_name=username).first()
    admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
    db.session.add(admin)
    db.session.commit()
Example #10
0
def add_admin_user(username, password, first_name, last_name, email, org_name):
    '''
    Creates a 'user_admin' scoped user using the supplied username and password
    :param username:
    :param password:
    :return:
    '''
    app.logger.info('Insert user_name: %s' % username)
    User.insert_user(username=username, password=password, first_name=first_name, last_name=last_name, email=email, org_name=org_name)
    admin = User.query.filter_by(user_name=username).first()
    admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
    admin.scopes.append(UserScope.query.filter_by(scope_name='redmine').first())
    db.session.add(admin)
    db.session.commit()
def oauth_callback(provider):
    # rand_pass will be a new password every time a user logs in
    # with oauth.
    temp_pass = str(uuid.uuid4())

    # lets create the oauth object that will issue the request.
    oauth = OAuthSignIn.get_provider(provider)

    # assign the response
    email, first_name, last_name = oauth.callback()

    if email is None:
        return unauthorized('Invalid credentials')

    # see if this user already exists, and
    # and give the user a brand new password.
    user = User.query.filter_by(email=email).first()
    if user:
        user.password = temp_pass

    # if there is no user, create a new one and setup
    # it's defaults and give it a new password.
    else:
        user = User.insert_user(password=temp_pass,
                         username=email,
                         email=email,
                         first_name=first_name,
                         last_name=last_name)

    return jsonify({'uuid': temp_pass, 'username': email})
Example #12
0
 def test_user(self):
     #Test the json in the object
     user = User()
     self.assertEquals(user.to_json(), {
         'email': None,
         'id': None,
         'user_id': None,
         'active':None,
         'first_name': None,
         'last_name' : None,
         'organization_id' : None,
         'phone_alternate' : None,
         'phone_primary' : None,
         'scopes' : [],
         'role' : None,
         'user_name': None})
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_username = '******'
        test_password = '******'
        Organization.insert_org()
        User.insert_user(username=test_username, password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()
Example #14
0
def create_user():
    """
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    """
    csrf_token = request.headers.get("X-Csrf-Token")
    if not csrf_token or csrf_token != current_app.config["UI_API_KEY"]:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization["username"], request.authorization["password"])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    # add user to db
    role_mapping = {
        1: ["annotate", "asset_manager", "user_admin", "redmine"],  # Administrator
        2: ["annotate", "asset_manager"],  # Marine Operator
        3: [],  # Science User
    }
    role_scopes = role_mapping[data["role_id"]]
    valid_scopes = UserScope.query.filter(UserScope.scope_name.in_(role_scopes)).all()

    try:
        new_user = User.from_json(data)
        new_user.scopes = valid_scopes
        new_user.active = True
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        return jsonify(error=e.message), 409

    try:
        redmine = redmine_login()
        organization = new_user.organization.organization_name
        tmp = dt.datetime.now() + dt.timedelta(days=1)
        due_date = dt.datetime.strftime(tmp, "%Y-%m-%d")
        issue = redmine.issue.new()
        issue.project_id = current_app.config["REDMINE_PROJECT_ID"]
        issue.subject = "New User Registration for OOI UI: %s, %s" % (new_user.first_name, new_user.last_name)
        issue.description = (
            "A new user has requested access to the OOI User Interface. Please review the application for %s, their role in the organization %s is %s and email address is %s"
            % (new_user.first_name, organization, new_user.role, new_user.email)
        )
        issue.priority_id = 1
        issue.due_date = due_date
        # Get the list of ticker Trackers
        trackers = list(redmine.tracker.all())
        # Find the REDMINE_TRACKER (like 'Support') and get the id
        # This make a difference for field validation and proper tracker assignment
        config_redmine_tracker = current_app.config["REDMINE_TRACKER"]
        tracker_id = [tracker.id for tracker in trackers if tracker.name == config_redmine_tracker][0]
        issue.tracker_id = tracker_id
        issue.save()
    except Exception as e:
        current_app.logger.exception("Failed to generate redmine issue for new user")
        return jsonify(error=e.message), 409

    return jsonify(new_user.to_json()), 201
Example #15
0
 def test_user(self):
     #Test the json in the object
     user = User()
     self.assertEquals(
         user.to_json(), {
             'email': None,
             'id': None,
             'user_id': None,
             'active': None,
             'first_name': None,
             'last_name': None,
             'organization_id': None,
             'phone_alternate': None,
             'phone_primary': None,
             'scopes': [],
             'role': None,
             'user_name': None
         })
Example #16
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = '******'
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        self.basedir = os.path.abspath(os.path.dirname(__file__))
        with open(self.basedir + '/mock_data/event_post.json', 'r') as f:
            doc = json.load(f)
        self.event_json_in = doc

        with open(self.basedir + '/mock_results/event_from.json', 'r') as f:
            doc = json.load(f)
        self.event_from_json = doc
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = '******'
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        self.basedir = os.path.abspath(os.path.dirname(__file__))
        with open(self.basedir + '/mock_data/event_post.json', 'r') as f:
            doc = json.load(f)
        self.event_json_in = doc

        with open(self.basedir + '/mock_results/event_from.json', 'r') as f:
            doc = json.load(f)
        self.event_from_json = doc
Example #18
0
def logged_in():
    '''
    Checks the TOKEN not the user identity to see if it's current and valid.
    '''
    auth = request.authorization
    if not auth:
        return jsonify(valid=False)
    token, password = auth.username, auth.password
    if token and not password:
        user = User.verify_auth_token(token)
        return jsonify(valid=(user is not None))
    return jsonify(valid=False)
Example #19
0
 def test_user(self):
     # Test the json in the object
     user = User()
     self.assertEquals(
         user.to_json(),
         {
             "email": None,
             "id": None,
             "user_id": None,
             "active": None,
             "first_name": None,
             "last_name": None,
             "organization_id": None,
             "phone_alternate": None,
             "phone_primary": None,
             "scopes": [],
             "role": None,
             "user_name": None,
             "email_opt_in": None,
         },
     )
def logged_in():
    '''
    Checks the TOKEN not the user identity to see if it's current and valid.
    '''
    auth = request.authorization
    if not auth:
        return jsonify(valid=False)
    token, password = auth.username, auth.password
    if token and not password:
        user = User.verify_auth_token(token)
        return jsonify(valid=(user is not None))
    return jsonify(valid=False)
Example #21
0
def create_user():
    '''
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    '''
    csrf_token = request.headers.get('X-Csrf-Token')
    if not csrf_token or csrf_token != current_app.config['UI_API_KEY']:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization['username'],
                               request.authorization['password'])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    #add user to db
    try:
        new_user = User.from_json(data)
        db.session.add(new_user)
        db.session.commit()
    except ValidationError as e:
        return jsonify(error=e.message), 409

    #add redmine ticket
    key = current_app.config['REDMINE_KEY']
    redmine = Redmine(current_app.config['REDMINE_URL'],
                      key=key,
                      requests={'verify': False})
    issue = redmine.issue.new()
    issue.project_id = 'ooi-ui-api-testing'
    issue.subject = new_user.first_name + ' ' + new_user.last_name + ' is requesting access to Redmine.'
    issue.description = 'The user email is ' + new_user.email + '.  The new request is for the role ' + new_user.role + ' and for the ' + data[
        'organization'] + ' organization.  Please enable this OOI account.'
    issue.priority_id = 1
    issue.save()

    # rm = requests.post('/redmine/ticket',
    #     headers={
    #         'Authorization': 'Basic ' + b64encode(('admin:test').encode('utf-8')).decode('utf-8'),
    #         'Accept': 'application/json',
    #         'Content-Type': 'application/json'
    #     },
    #     data=json.dumps({'project_id': 'ooi-ui-api-testing',
    #                'subject': new_user.first_name+' ' + new_user.last_name + ' is requesting access to Redmine.',
    #                'description': 'The user email is '+ new_user.email + '.  The new request is for the role '+new_user.role +' and for the '+data['organization'] +' organization.',
    #                'priority_id': 1}))
    #                # 'assigned_to_id': 1}))
    # response_rm = rm.status_code

    #except:
    #   return "Redmine Error", 409

    return jsonify(new_user.to_json()), 201
def verify_auth(email_or_token, password):
    if email_or_token == '':
        return True
    if password == '':
        g.current_user = User.verify_auth_token(email_or_token)
        g.token_used = True
        return g.current_user is not None
    user = User.query.filter(User.user_name==email_or_token, User.active==True).first()
    if not user:
        return False
    g.current_user = user
    g.token_used = False
    return user.verify_password(password)
    def setUp(self):
        self.app = create_app("TESTING_CONFIG")
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_username = "******"
        test_password = "******"
        Organization.insert_org()

        User.insert_user(username=test_username, password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name="admin").first()
        scope = UserScope.query.filter_by(scope_name="user_admin").first()
        cc_scope = UserScope.query.filter_by(scope_name="command_control").first()
        admin.scopes.append(scope)
        admin.scopes.append(cc_scope)
        db.session.add(admin)
        db.session.commit()

        self.headers = self.get_api_headers("admin", "test")
Example #24
0
def deploy(password, bulkload):
    from flask.ext.migrate import upgrade
    from ooiservices.app.models import User, UserScope, UserScopeLink, Array, Organization
    from ooiservices.app.models import PlatformDeployment, InstrumentDeployment, Stream, StreamParameterLink
    from sh import psql
    #Create the local database
    app.logger.info('Creating DEV and TEST Databases')
    psql('-c', 'create database ooiuidev;', '-U', 'postgres')
    psql('ooiuidev', '-c', 'create schema ooiui')
    psql('ooiuidev', '-c', 'create extension postgis')
    #Create the local test database
    psql('-c', 'create database ooiuitest;', '-U', 'postgres')
    psql('ooiuitest', '-c', 'create schema ooiui')
    psql('ooiuitest', '-c', 'create extension postgis')
    from sqlalchemy.orm.mapper import configure_mappers
    configure_mappers()
    db.create_all()
    if bulkload:
        with open('db/ooiui_schema_data.sql') as f:
            psql('ooiuidev', _in=f)
        app.logger.info('Bulk test data loaded.')

    # migrate database to latest revision
    #upgrade()
    if not os.getenv('TRAVIS'):
        Organization.insert_org()
        UserScope.insert_scopes()
        app.logger.info('Insert default user, name: admin')
        User.insert_user(password=password)
        admin = User.query.first()
        admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='redmine').first())
        db.session.add(admin)
        db.session.commit()
        if bulkload:
            with open('db/ooiui_schema_data_notifications.sql') as f:
                psql('ooiuidev', _in=f)
            app.logger.info('Bulk test data loaded for notifications.')
Example #25
0
def verify_auth(email_or_token, password):
    if email_or_token == '':
        return True
    if password == '':
        g.current_user = User.verify_auth_token(email_or_token)
        g.token_used = True
        return g.current_user is not None
    user = User.query.filter(User.user_name == email_or_token,
                             User.active == True).first()
    if not user:
        return False
    g.current_user = user
    g.token_used = False
    return user.verify_password(password)
Example #26
0
def create_user():
    '''
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    '''
    csrf_token = request.headers.get('X-Csrf-Token')
    if not csrf_token or csrf_token != current_app.config['UI_API_KEY']:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization['username'],
                               request.authorization['password'])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    #add user to db
    role_mapping = {
        1: ['annotate', 'asset_manager', 'user_admin',
            'redmine'],  # Administrator
        2: ['annotate', 'asset_manager'],  # Marine Operator
        3: []  # Science User
    }
    role_scopes = role_mapping[data['role_id']]
    valid_scopes = UserScope.query.filter(
        UserScope.scope_name.in_(role_scopes)).all()

    try:
        new_user = User.from_json(data)
        new_user.scopes = valid_scopes
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        return jsonify(error=e.message), 409

    try:
        redmine = redmine_login()
        organization = new_user.organization.organization_name
        issue = redmine.issue.new()
        issue.project_id = current_app.config['REDMINE_PROJECT_ID']
        issue.subject = 'New User Registration for OOI UI: %s, %s' % (
            new_user.first_name, new_user.last_name)
        issue.description = 'A new user has requested access to the OOI User Interface. Please review the application for %s, their role in the organization %s is %s and email address is %s' % (
            new_user.first_name, organization, new_user.role, new_user.email)
        issue.priority_id = 1
        issue.save()
    except:
        current_app.logger.exception(
            "Failed to generate redmine issue for new user")

    return jsonify(new_user.to_json()), 201
Example #27
0
def create_user():
    '''
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    '''
    csrf_token = request.headers.get('X-Csrf-Token')
    if not csrf_token or csrf_token != current_app.config['UI_API_KEY']:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization['username'], request.authorization['password'])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    #add user to db
    role_mapping = {
        1: ['annotate', 'asset_manager', 'user_admin', 'redmine'], # Administrator
        2: ['annotate', 'asset_manager'],                          # Marine Operator
        3: []                                                      # Science User
    }
    role_scopes = role_mapping[data['role_id']]
    valid_scopes = UserScope.query.filter(UserScope.scope_name.in_(role_scopes)).all()

    try:
        new_user = User.from_json(data)
        new_user.scopes = valid_scopes
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        return jsonify(error=e.message), 409

    try:
        redmine = redmine_login()
        organization = new_user.organization.organization_name
        issue = redmine.issue.new()
        issue.project_id = current_app.config['REDMINE_PROJECT_ID']
        issue.subject = 'New User Registration for OOI UI: %s, %s' % (new_user.first_name, new_user.last_name)
        issue.description = 'A new user has requested access to the OOI User Interface. Please review the application for %s, their role in the organization %s is %s and email address is %s' % (new_user.first_name, organization, new_user.role, new_user.email)
        issue.priority_id = 1
        issue.save()
    except:
        current_app.logger.exception("Failed to generate redmine issue for new user")

    return jsonify(new_user.to_json()), 201
 def test_password_verification(self):
     u = User(password="******")
     self.assertTrue(u.verify_password("dog"))
     self.assertFalse(u.verify_password("cat"))
Example #29
0
def deploy(password, production, psqluser):
    from flask.ext.migrate import upgrade
    from ooiservices.app.models import User, UserScope, UserScopeLink, Array, Organization
    from ooiservices.app.models import PlatformDeployment, InstrumentDeployment, Stream, StreamParameterLink
    from sh import psql
    if production:
        app.logger.info('Creating PRODUCTION Database')
        try:
            psql('-c', 'CREATE ROLE postgres LOGIN SUPERUSER')
        except:
            pass
        psql('-c', 'create database ooiuiprod;', '-U', psqluser)
        psql('ooiuiprod', '-c', 'create schema ooiui', '-U', psqluser)
        psql('ooiuiprod', '-c', 'create extension postgis', '-U', psqluser)
    else:
        try:
            psql('-c', 'CREATE ROLE postgres LOGIN SUPERUSER')
        except:
            pass
        #Create the local database
        app.logger.info('Creating DEV and TEST Databases')
        psql('-c', 'create database ooiuidev;', '-U', psqluser)
        psql('ooiuidev', '-c', 'create schema ooiui', '-U', psqluser)
        psql('ooiuidev', '-c', 'create extension postgis', '-U', psqluser)
        #Create the local test database
        psql('-c', 'create database ooiuitest;', '-U', psqluser)
        psql('ooiuitest', '-c', 'create schema ooiui', '-U', psqluser)
        psql('ooiuitest', '-c', 'create extension postgis', '-U', psqluser)

    from sqlalchemy.orm.mapper import configure_mappers
    configure_mappers()
    db.create_all()

    if production:
        app.logger.info('Populating Production Database . . .')
        with open('db/ooiui_schema_data.sql') as f:
            psql('-U', psqluser, 'ooiuiprod', _in=f)
        with open('db/ooiui_params_streams_data.sql') as h:
            psql('-U', psqluser, 'ooiuiprod', _in=h)
        # with open('db/ooiui_vocab.sql') as i:
        #     psql('-U', psqluser, 'ooiuiprod', _in=i)
        app.logger.info('Production Database loaded.')
    else:
        app.logger.info('Populating Dev Database . . .')
        with open('db/ooiui_schema_data.sql') as f:
            psql('-U', psqluser, 'ooiuidev', _in=f)
        with open('db/ooiui_params_streams_data.sql') as h:
            psql('-U', psqluser, 'ooiuidev', _in=h)
        # with open('db/ooiui_vocab.sql') as i:
        #     psql('-U', psqluser, 'ooiuidev', _in=i)
        app.logger.info('Dev Database loaded.')

    # migrate database to latest revision
    #upgrade()
    if not os.getenv('TRAVIS'):
        UserScope.insert_scopes()
        app.logger.info('Insert default user, name: admin')
        User.insert_user(password=password)
        admin = User.query.first()
        admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='sys_admin').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='data_manager').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='redmine').first())
        db.session.add(admin)
        db.session.commit()
Example #30
0
def rebuild_schema(schema, schema_owner, save_users, admin_username,
                   admin_password, first_name, last_name, email, org_name):
    """
    Creates the OOI UI Services schema based on models.py
    :usage: python manage.py rebuild_schema --schema ooiui --schema_owner postgres --save_users False --admin_username admin --admin_password password --first_name Default --last_name Admin --email [email protected] --org_name Rutgers
    :param schema:
    :param schema_owner:
    :return:
    """
    # Check if schema exists
    timestamp = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())
    sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}'".format(
        schema)
    sql_result = db.engine.execute(sql).first()
    if sql_result != None:
        # Move current schema to _timestamp
        app.logger.info('Backing up schema container {0} to {0}_{1}'.format(
            schema, timestamp))
        db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}'.format(
            schema, timestamp))

    app.logger.info('Creating schema container: {0}'.format(schema))
    db.engine.execute(
        'CREATE SCHEMA IF NOT EXISTS {0} AUTHORIZATION {1}'.format(
            schema, schema_owner))

    app.logger.info('Building schema objects')
    db.create_all()

    app.logger.info('Adding base user_scopes')
    UserScope.insert_scopes()

    app.logger.info('Loading default data into database')
    load_data('ooiui_schema_data.sql')
    db.session.commit()

    if save_users == 'True':
        app.logger.info('Re-populating users from backup schema')
        users_sql = 'SELECT * FROM {0}_{1}.users'.format(schema, timestamp)
        sql_result = db.engine.execute(users_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            new_user = User()
            new_user.id = sresult.id
            new_user.user_id = sresult.user_id
            new_user.pass_hash = sresult.pass_hash
            new_user.email = sresult.email
            new_user.user_name = sresult.user_name
            new_user.active = sresult.active
            new_user.confirmed_at = sresult.confirmed_at
            new_user.first_name = sresult.first_name
            new_user.last_name = sresult.last_name
            new_user.phone_primary = sresult.phone_primary
            new_user.phone_alternate = sresult.phone_alternate
            new_user.role = sresult.role
            new_user.organization_id = sresult.organization_id
            db.session.add(new_user)
            db.engine.execute("SELECT nextval('ooiui.users_id_seq')")
            db.session.commit()

        user_scope_link_sql = 'SELECT * FROM {0}_{1}.user_scope_link'.format(
            schema, timestamp)
        sql_resultc = db.engine.execute(user_scope_link_sql)
        fac = sql_resultc.fetchall()
        for scresult in fac:
            new_user_scope_link = UserScopeLink()
            new_user_scope_link.id = scresult.id
            new_user_scope_link.user_id = scresult.user_id
            new_user_scope_link.scope_id = scresult.scope_id
            db.session.add(new_user_scope_link)
            db.engine.execute("SELECT nextval('ooiui.user_scope_link_id_seq')")
            db.session.commit()

        # db.engine.execute('INSERT INTO {0}.users SELECT * FROM {0}_{1}.users'.format(schema, timestamp))
        # db.engine.execute('INSERT INTO {0}.user_scope_link SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp))

    else:
        app.logger.info('Adding the default admin user')
        if admin_username is None:
            app.logger.info('Admin username set to: admin')
            admin_username = '******'
        if admin_password is None:
            app.logger.info('Admin password set to: password')
            admin_password = '******'
        if first_name is None:
            app.logger.info('Admin first_name set to: Default')
            first_name = 'Default'
        if last_name is None:
            app.logger.info('Admin last_name set to: Admin')
            last_name = 'Admin'
        if email is None:
            app.logger.info('Admin email set to: [email protected]')
            email = '*****@*****.**'
        if org_name is None:
            app.logger.info('Admin org_name set to: Rutgers')
            org_name = 'Rutgers'
        add_admin_user(username=admin_username,
                       password=admin_password,
                       first_name=first_name,
                       last_name=last_name,
                       email=email,
                       org_name=org_name)
    load_data(sql_file='ooiui_schema_data_notifications.sql')
    app.logger.info('Database reloaded successfully')
Example #31
0
 def test_password_verification(self):
     u = User(password='******')
     self.assertTrue(u.verify_password('dog'))
     self.assertFalse(u.verify_password('cat'))
Example #32
0
 def test_password_salts(self):
     u = User(password='******')
     u2 = User(password='******')
     self.assertTrue(u.pass_hash != u2.pass_hash)
Example #33
0
 def test_password_hashing(self):
     u = User(password='******')
     self.assertTrue(u.pass_hash is not None)
Example #34
0
 def test_password_tampering(self):
     u = User(password='******')
     with self.assertRaises(AttributeError):
         u.password
Example #35
0
    def test_update_user_event_notification(self):
        verbose = False  #self.verbose
        root = self.root

        if verbose: print '\n'
        content_type = 'application/json'
        headers = self.get_api_headers('admin', 'test')

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Add a second user ('foo', password 'test')
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test_username = '******'
        test_password = '******'
        test_email = '*****@*****.**'
        Organization.insert_org()
        User.insert_user(username=test_username,
                         password=test_password,
                         email=test_email)
        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        foo = User.query.filter_by(user_name='foo').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        foo.scopes.append(scope)
        scope = UserScope.query.filter_by(
            scope_name='redmine').first()  # added
        foo.scopes.append(scope)
        db.session.add(foo)
        db.session.commit()

        response = self.client.get(url_for('main.get_user', id=1),
                                   headers=headers)
        self.assertTrue(response.status_code == 200)

        response = self.client.get(url_for('main.get_user', id=2),
                                   headers=headers)
        self.assertTrue(response.status_code == 200)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # # Create alert and an alarm
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ref_def = "CE01ISSP-XX099-01-CTDPFJ999"
        # Create an alarm with user_event_notification - uses definition 1 and user_id 1
        test_alarm = self.create_alert_alarm_definition(ref_def,
                                                        event_type='alarm',
                                                        uframe_id=2,
                                                        severity=1)

        # Create an alarm without user_event_notification - uses definition 1 and user_id 1
        bad_alarm = self.create_alert_alarm_definition_wo_notification(
            ref_def, event_type='alarm', uframe_filter_id=2, severity=1)

        notification = self.create_user_event_notification(bad_alarm.id, 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # GET alarm definition by SystemEventDefinition id
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(url_for('main.get_alert_alarm_def',
                                           id=test_alarm.id),
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        alarm_definition = json.loads(response.data)
        self.assertTrue(alarm_definition is not None)

        response = self.client.get(url_for('main.get_alert_alarm_def',
                                           id=bad_alarm.id),
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_alarm_definition = json.loads(response.data)
        self.assertTrue(bad_alarm_definition is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notifications (1)
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(
            url_for('main.get_user_event_notifications'), headers=headers)
        self.assertEquals(response.status_code, 200)
        data = json.loads(response.data)
        self.assertTrue(data is not None)
        notifications = data['notifications']
        self.assertTrue(notifications is not None)
        self.assertEquals(len(notifications), 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notification by id=1
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=1)
        response = self.client.get(url,
                                   content_type=content_type,
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        notification = json.loads(response.data)
        self.assertTrue(len(notification) > 0)
        self.assertEquals(len(notification), 8)
        """
        Error messages for the following tests:

            1. bad_notification:  {}

            2. 'Invalid ID, user_event_notification record not found.'

            3. 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'

            4. 'Inconsistent User ID, user_id provided in data does not match id.'

            5. 'IntegrityError creating user_event_notification.'

            6. (no error)

            7. 'Insufficient data, or bad data format.'
        """

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (1) Get user_event_notification by id=5 (doesn't exist) response: {}
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=5)
        response = self.client.get(url,
                                   content_type=content_type,
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_notification = json.loads(response.data)
        self.assertTrue(bad_notification is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (2) (Negative) Update event_event_notification;
        # error: 'Invalid ID, user_event_notification record not found.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 1,
            'system_event_definition_id': test_alarm.id,
            'use_email': False,
            'use_log': False,
            'use_phone': False,
            'use_redmine': False,
            'use_sms': False,
            'id': 50
        }
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=50),
                                   headers=headers,
                                   data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (3) (Negative) Update event_event_notification
        # error: 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 999,
            'system_event_definition_id': 1,
            'use_email': True,
            'use_log': True,
            'use_phone': True,
            'use_redmine': True,
            'use_sms': True,
            'id': 1
        }
        good_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=800),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (4) (Negative) Update user_event_notification, with invalid user_id
        # error: 'Inconsistent User ID, user_id provided in data does not match id.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 1,
            'system_event_definition_id': 2,
            'use_email': True,
            'use_log': True,
            'use_phone': True,
            'use_redmine': True,
            'use_sms': True,
            'id': 2
        }
        good_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=2),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (5) # (Negative) Update event_event_notification
        # error: 'IntegrityError creating user_event_notification.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 2,
            'system_event_definition_id': bad_alarm.id,
            'use_email': False,
            'use_log': 'log',
            'use_phone': False,
            'use_redmine': False,
            'use_sms': False,
            'id': 2
        }
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=2),
                                   headers=headers,
                                   data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (6) (Positive) Update event_event_notification
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 1,
            'system_event_definition_id': 1,
            'use_email': True,
            'use_log': True,
            'use_phone': True,
            'use_redmine': True,
            'use_sms': True,
            'id': 1
        }
        good_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=1),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 201)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue(len(notify_data) > 0)
        notify = UserEventNotification.query.get(1)

        for attribute in UserEventNotification.__table__.columns._data:
            self.assertTrue(attribute in notify_data)
            if attribute != 'user_id' or attribute != 'id':
                self.assertEquals(getattr(notify, attribute), True)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (Negative) Update event_event_notification - expect failure, invalid user_id
        # error 'Insufficient data, or bad data format.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        data = {'user_id': 10}
        good_stuff = json.dumps(data)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=1),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 409)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        if verbose: print '\n'
Example #36
0
def rebuild_schema(schema, schema_owner, save_users, admin_username, admin_password, first_name, last_name, email, org_name):
    """
    Creates the OOI UI Services schema based on models.py
    :usage: python manage.py rebuild_schema --schema ooiui --schema_owner postgres --save_users False --admin_username admin --admin_password password --first_name Default --last_name Admin --email [email protected] --org_name Rutgers
    :param schema:
    :param schema_owner:
    :return:
    """
    # Check if schema exists
    timestamp = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())
    sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}'".format(schema)
    sql_result = db.engine.execute(sql).first()
    if sql_result != None:
        # Move current schema to _timestamp
        app.logger.info('Backing up schema container {0} to {0}_{1}'.format(schema, timestamp))
        db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}'.format(schema, timestamp))

    app.logger.info('Creating schema container: {0}'.format(schema))
    db.engine.execute('CREATE SCHEMA IF NOT EXISTS {0} AUTHORIZATION {1}'.format(schema, schema_owner))

    app.logger.info('Building schema objects')
    db.create_all()

    app.logger.info('Adding base user_scopes')
    UserScope.insert_scopes()

    app.logger.info('Loading default data into database')
    load_data('ooiui_schema_data.sql')
    db.session.commit()

    if save_users == 'True':
        app.logger.info('Re-populating users from backup schema')
        users_sql = 'SELECT * FROM {0}_{1}.users'.format(schema, timestamp)
        sql_result = db.engine.execute(users_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            new_user = User()
            new_user.id = sresult.id
            new_user.user_id = sresult.user_id
            new_user.pass_hash = sresult.pass_hash
            new_user.email = sresult.email
            new_user.user_name = sresult.user_name
            new_user.active = sresult.active
            new_user.confirmed_at = sresult.confirmed_at
            new_user.first_name = sresult.first_name
            new_user.last_name = sresult.last_name
            new_user.phone_primary = sresult.phone_primary
            new_user.phone_alternate = sresult.phone_alternate
            new_user.role = sresult.role
            new_user.organization_id = sresult.organization_id
            db.session.add(new_user)
            db.engine.execute("SELECT nextval('ooiui.users_id_seq')")
            db.session.commit()

        user_scope_link_sql = 'SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp)
        sql_resultc = db.engine.execute(user_scope_link_sql)
        fac = sql_resultc.fetchall()
        for scresult in fac:
            new_user_scope_link = UserScopeLink()
            new_user_scope_link.id = scresult.id
            new_user_scope_link.user_id = scresult.user_id
            new_user_scope_link.scope_id = scresult.scope_id
            db.session.add(new_user_scope_link)
            db.engine.execute("SELECT nextval('ooiui.user_scope_link_id_seq')")
            db.session.commit()

        # db.engine.execute('INSERT INTO {0}.users SELECT * FROM {0}_{1}.users'.format(schema, timestamp))
        # db.engine.execute('INSERT INTO {0}.user_scope_link SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp))

    else:
        app.logger.info('Adding the default admin user')
        if admin_username is None:
            app.logger.info('Admin username set to: admin')
            admin_username = '******'
        if admin_password is None:
            app.logger.info('Admin password set to: password')
            admin_password = '******'
        if first_name is None:
            app.logger.info('Admin first_name set to: Default')
            first_name = 'Default'
        if last_name is None:
            app.logger.info('Admin last_name set to: Admin')
            last_name = 'Admin'
        if email is None:
            app.logger.info('Admin email set to: [email protected]')
            email = '*****@*****.**'
        if org_name is None:
            app.logger.info('Admin org_name set to: Rutgers')
            org_name = 'Rutgers'
        add_admin_user(username=admin_username, password=admin_password, first_name=first_name, last_name=last_name, email=email, org_name=org_name)
    load_data(sql_file='ooiui_schema_data_notifications.sql')
    app.logger.info('Database reloaded successfully')
Example #37
0
def rebuild_schema(schema, schema_owner, save_users, save_disabled_streams, admin_username, admin_password, first_name, last_name, email, org_name):
    """
    Creates the OOI UI Services schema based on models.py
    :usage: python manage.py rebuild_schema --schema ooiui --schema_owner postgres --save_users False --save_disabled_streams True --admin_username admin --admin_password password --first_name Default --last_name Admin --email [email protected] --org_name Rutgers
    :param schema:
    :param schema_owner:
    :return:
    """
    # Check if schema exists
    timestamp = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())
    sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}'".format(schema)
    sql_result = db.engine.execute(sql).first()
    if sql_result != None:
        # Move current schema to _timestamp
        app.logger.info('Backing up schema container {0} to {0}_{1}'.format(schema, timestamp))
        db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}'.format(schema, timestamp))

    app.logger.info('Creating schema container: {0}'.format(schema))
    db.engine.execute('CREATE SCHEMA IF NOT EXISTS {0} AUTHORIZATION {1}'.format(schema, schema_owner))

    app.logger.info('Building schema objects')
    db.create_all()

    app.logger.info('Adding base user_scopes')
    UserScope.insert_scopes()
    db.session.commit()

    app.logger.info('Loading default data into database')
    load_data('ooiui_schema_data.sql')
    db.session.commit()

    app.logger.info('Loading params data into database')
    load_data(sql_file='ooiui_params_streams_data.sql')
    db.session.commit()

    # app.logger.info('Loading new vocab data into database')
    # load_data(sql_file='ooiui_vocab.sql')
    db.session.commit()

    if save_disabled_streams == 'True':
        app.logger.info('Re-populating disabledstreams table from backup schema')
        ds_sql = 'SELECT * FROM {0}_{1}.disabledstreams'.format(schema, timestamp)
        sql_result = db.engine.execute(ds_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            ds_record = DisabledStreams()
            ds_record.id = sresult.id
            ds_record.ref_des = getattr(sresult, 'ref_des', '')
            ds_record.stream_name = getattr(sresult, 'stream_name', '')
            ds_record.disabled_by = getattr(sresult, 'disabled_by', '')
            ds_record.timestamp = getattr(sresult, 'timestamp', '')
            db.session.add(ds_record)
            db.engine.execute("SELECT nextval('ooiui.disabledstreams_id_seq')")
            db.session.commit()

    if save_users == 'True':
        app.logger.info('Re-populating users from backup schema')
        users_sql = 'SELECT * FROM {0}_{1}.users'.format(schema, timestamp)
        sql_result = db.engine.execute(users_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            try:
                new_user = User()
                new_user.id = sresult.id
                new_user.user_id = getattr(sresult, 'user_id', '')
                if hasattr(sresult, 'pass_hash'):
                    new_user._password = getattr(sresult, 'pass_hash', '')
                else:
                    new_user._password = getattr(sresult, '_password', '')
                new_user.email = getattr(sresult, 'email', '')
                new_user.user_name = getattr(sresult, 'user_name', '')
                new_user.active = getattr(sresult, 'active', '')
                new_user.confirmed_at = getattr(sresult, 'confirmed_at', '')
                new_user.first_name = getattr(sresult, 'first_name', '')
                new_user.last_name = getattr(sresult, 'last_name', '')
                new_user.phone_primary = getattr(sresult, 'phone_primary', '')
                new_user.phone_alternate = getattr(sresult, 'phone_alternate', '')
                new_user.role = getattr(sresult, 'role', '')
                new_user.email_opt_in = getattr(sresult, 'email_opt_in', '')
                new_user.organization_id = getattr(sresult, 'organization_id', '')
                new_user.other_organization = getattr(sresult, 'other_organization', '')
                new_user.vocation = getattr(sresult, 'vocation', '')
                new_user.country = getattr(sresult, 'country', '')
                new_user.state = getattr(sresult, 'state', '')
                db.session.add(new_user)
                db.engine.execute("SELECT nextval('ooiui.users_id_seq')")
                db.session.commit()
            except sqlalchemy.exc.IntegrityError, exc:
                app.logger.info('Failure: rebuild_schema failed: ')
                reason = exc.message
                app.logger.info('Cause: ' + reason)
                app.logger.info('Restoring to previous version')
                app.logger.info('Restoring schema container {0}_{1} to {0}'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}_failed'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0}_{1} RENAME TO {0}'.format(schema, timestamp))


        user_scope_link_sql = 'SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp)
        sql_resultc = db.engine.execute(user_scope_link_sql)
        fac = sql_resultc.fetchall()
        for scresult in fac:
            try:
                new_user_scope_link = UserScopeLink()
                new_user_scope_link.id = scresult.id
                new_user_scope_link.user_id = scresult.user_id
                new_user_scope_link.scope_id = scresult.scope_id
                db.session.add(new_user_scope_link)
                db.engine.execute("SELECT nextval('ooiui.user_scope_link_id_seq')")
                db.session.commit()
            except sqlalchemy.exc.IntegrityError, exc:
                app.logger.info('Failure: rebuild_schema failed: ')
                reason = exc.message
                app.logger.info('Cause: ' + reason)
                app.logger.info('Restoring to previous version')
                app.logger.info('Restoring schema container {0}_{1} to {0}'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}_failed'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0}_{1} RENAME TO {0}'.format(schema, timestamp))
Example #38
0
 def test_password_verification(self):
     u = User(password='******')
     self.assertTrue(u.verify_password('dog'))
     self.assertFalse(u.verify_password('cat'))
    def test_update_user_event_notification(self):
        verbose = False #self.verbose
        root = self.root

        if verbose: print '\n'
        content_type =  'application/json'
        headers = self.get_api_headers('admin', 'test')

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Add a second user ('foo', password 'test')
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test_username = '******'
        test_password = '******'
        test_email = '*****@*****.**'
        Organization.insert_org()
        User.insert_user(username=test_username, password=test_password, email=test_email)
        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        foo = User.query.filter_by(user_name='foo').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        foo.scopes.append(scope)
        scope = UserScope.query.filter_by(scope_name='redmine').first()     # added
        foo.scopes.append(scope)
        db.session.add(foo)
        db.session.commit()

        response = self.client.get(url_for('main.get_user',id=1), headers=headers)
        self.assertTrue(response.status_code == 200)

        response = self.client.get(url_for('main.get_user',id=2), headers=headers)
        self.assertTrue(response.status_code == 200)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # # Create alert and an alarm
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ref_def = "CE01ISSP-XX099-01-CTDPFJ999"
        # Create an alarm with user_event_notification - uses definition 1 and user_id 1
        test_alarm = self.create_alert_alarm_definition(ref_def, event_type='alarm', uframe_id=2, severity=1)

        # Create an alarm without user_event_notification - uses definition 1 and user_id 1
        bad_alarm = self.create_alert_alarm_definition_wo_notification(ref_def, event_type='alarm',
                                                                       uframe_filter_id=2, severity=1)

        notification = self.create_user_event_notification(bad_alarm.id, 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # GET alarm definition by SystemEventDefinition id
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(url_for('main.get_alert_alarm_def', id=test_alarm.id), headers=headers)
        self.assertEquals(response.status_code, 200)
        alarm_definition = json.loads(response.data)
        self.assertTrue(alarm_definition is not None)

        response = self.client.get(url_for('main.get_alert_alarm_def', id=bad_alarm.id), headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_alarm_definition = json.loads(response.data)
        self.assertTrue(bad_alarm_definition is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notifications (1)
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(url_for('main.get_user_event_notifications'), headers=headers)
        self.assertEquals(response.status_code, 200)
        data = json.loads(response.data)
        self.assertTrue(data is not None)
        notifications = data['notifications']
        self.assertTrue(notifications is not None)
        self.assertEquals(len(notifications), 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notification by id=1
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=1)
        response = self.client.get(url, content_type=content_type, headers=headers)
        self.assertEquals(response.status_code, 200)
        notification = json.loads(response.data)
        self.assertTrue(len(notification) > 0)
        self.assertEquals(len(notification), 8)

        """
        Error messages for the following tests:

            1. bad_notification:  {}

            2. 'Invalid ID, user_event_notification record not found.'

            3. 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'

            4. 'Inconsistent User ID, user_id provided in data does not match id.'

            5. 'IntegrityError creating user_event_notification.'

            6. (no error)

            7. 'Insufficient data, or bad data format.'
        """

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (1) Get user_event_notification by id=5 (doesn't exist) response: {}
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=5)
        response = self.client.get(url, content_type=content_type, headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_notification = json.loads(response.data)
        self.assertTrue(bad_notification is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (2) (Negative) Update event_event_notification;
        # error: 'Invalid ID, user_event_notification record not found.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 1,
                'system_event_definition_id': test_alarm.id,
                'use_email': False,
                'use_log': False,
                'use_phone': False,
                'use_redmine': False,
                'use_sms': False,
                'id': 50}
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=50), headers=headers, data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (3) (Negative) Update event_event_notification
        # error: 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 999,
                'system_event_definition_id': 1,
                'use_email': True,
                'use_log': True,
                'use_phone': True,
                'use_redmine': True,
                'use_sms': True,
                'id': 1}
        good_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=800), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (4) (Negative) Update user_event_notification, with invalid user_id
        # error: 'Inconsistent User ID, user_id provided in data does not match id.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 1,
                'system_event_definition_id': 2,
                'use_email': True,
                'use_log': True,
                'use_phone': True,
                'use_redmine': True,
                'use_sms': True,
                'id': 2}
        good_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=2), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (5) # (Negative) Update event_event_notification
        # error: 'IntegrityError creating user_event_notification.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 2,
                'system_event_definition_id': bad_alarm.id,
                'use_email': False,
                'use_log': 'log',
                'use_phone': False,
                'use_redmine': False,
                'use_sms': False,
                'id': 2}
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=2), headers=headers, data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (6) (Positive) Update event_event_notification
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 1,
                'system_event_definition_id': 1,
                'use_email': True,
                'use_log': True,
                'use_phone': True,
                'use_redmine': True,
                'use_sms': True,
                'id': 1}
        good_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=1), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 201)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue(len(notify_data) > 0)
        notify = UserEventNotification.query.get(1)

        for attribute in UserEventNotification.__table__.columns._data:
            self.assertTrue(attribute in notify_data)
            if attribute != 'user_id' or attribute != 'id':
                self.assertEquals(getattr(notify,attribute), True)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (Negative) Update event_event_notification - expect failure, invalid user_id
        # error 'Insufficient data, or bad data format.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        data = {'user_id': 10}
        good_stuff = json.dumps(data)
        response = self.client.put(url_for('main.update_user_event_notification', id=1), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 409)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        if verbose: print '\n'