def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("connectionMethod", type=str)
        args = parser.parse_args()

        logger.debug("Attempting to get all users for connection method: {}".format(args.get("connectionMethod")))
        if transactions == "false":
            identity_vault = user.Profile(dynamodb_table, dynamodb_client, transactions=False)

        if transactions == "true":
            identity_vault = user.Profile(dynamodb_table, dynamodb_client, transactions=True)

        logger.info("Getting all users for connection method: {}".format(args.get("connectionMethod")))
        all_users = identity_vault.all_filtered(args.get("connectionMethod"))
        # Convert vault data to cis-profile-like data format
        all_users_cis = []
        for cuser in all_users:
            all_users_cis.append(
                {
                    "uuid": cuser["user_uuid"]["S"],
                    "user_id": cuser["id"]["S"],
                    "primary_email": cuser["primary_email"]["S"],
                }
            )

        logger.info("Returning {} users".format(len(all_users_cis)))
        return all_users_cis
    def get(self):
        """Return a single user with id `user_id`."""
        parser = reqparse.RequestParser()
        parser.add_argument("Authorization", location="headers")
        parser.add_argument("nextPage", type=str)
        parser.add_argument("primaryEmail", type=str)
        parser.add_argument("filterDisplay", type=str)
        args = parser.parse_args()

        filter_display = args.get("filterDisplay", None)
        primary_email = args.get("primaryEmail", None)
        next_page = args.get("nextPage", None)
        scopes = get_scopes(args.get("Authorization"))

        if next_page is not None:
            nextPage = load_dirty_json(next_page)
        else:
            nextPage = None

        if transactions == "false":
            identity_vault = user.Profile(dynamodb_table, dynamodb_client, transactions=False)

        if transactions == "true":
            identity_vault = user.Profile(dynamodb_table, dynamodb_client, transactions=True)

        next_page_token = None
        if primary_email is None:
            result = identity_vault.all_by_page(next_page=nextPage, limit=25)
            next_page_token = result.get("LastEvaluatedKey")
        else:
            result = identity_vault.find_by_email(primary_email)
        v2_profiles = []

        for profile in result.get("Items"):
            vault_profile = json.loads(profile.get("profile"))
            v2_profile = User(user_structure_json=vault_profile)
            if "read:fullprofile" in scopes:
                # Assume someone has asked for all the data.
                logger.info(
                    "The provided token has access to all of the data.", extra={"query_args": args, "scopes": scopes}
                )
                pass
            else:
                # Assume the we are filtering falls back to public with no scopes
                logger.info("This is a limited scoped query.", extra={"query_args": args, "scopes": scopes})
                v2_profile.filter_scopes(scope_to_mozilla_data_classification(scopes))

            if "display:all" in scopes:
                logger.info("display:all in token not filtering profile.", extra={"query_args": args, "scopes": scopes})
            else:
                logger.info("display filtering engaged for query.", extra={"query_args": args, "scopes": scopes})
                v2_profile.filter_display(scope_to_display_level(scopes))

            if filter_display is not None:
                v2_profile.filter_display(DisplayLevelParms.map(filter_display))

            v2_profiles.append(v2_profile.as_dict())

        response = {"Items": v2_profiles, "nextPage": next_page_token}
        return jsonify(response)
예제 #3
0
    def test_find_user(self):
        from cis_identity_vault.models import user

        primary_email = "*****@*****.**"
        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = primary_email
        modified_profile["active"]["value"] = True
        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure)

        profile = user.Profile(self.table)
        user_id = self.user_profile.get("user_id").get("value")
        result_for_user_id = profile.find_by_id(user_id)
        result_for_email = profile.find_by_email(primary_email)
        assert result_for_user_id is not None
        assert result_for_email is not None
예제 #4
0
파일: v2_api.py 프로젝트: romanom/cis
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("connectionMethod", type=str)
        parser.add_argument("active", type=str)
        parser.add_argument("nextPage", type=str)

        args = parser.parse_args()

        logger.debug("Arguments received: {}".format(args))

        logger.info(
            "Attempting to get all users for connection method: {}".format(
                args.get("connectionMethod")))
        next_page = args.get("nextPage")
        if next_page is not None:
            next_page = urllib.parse.unquote(next_page)

        if transactions == "false":
            identity_vault = user.Profile(dynamodb_table,
                                          dynamodb_client,
                                          transactions=False)
        elif transactions == "true":
            identity_vault = user.Profile(dynamodb_table,
                                          dynamodb_client,
                                          transactions=True)

        logger.debug("Getting all users for connection method: {}".format(
            args.get("connectionMethod")))
        if args.get("active") is not None and args.get(
                "active").lower() == "false":
            active = False
        else:
            active = True  # Support returning only active users by default.

        all_users = identity_vault.all_filtered(
            connection_method=args.get("connectionMethod"),
            active=active,
            next_page=next_page)

        while len(
                all_users["users"]) == 0 and all_users["nextPage"] is not None:
            # If our result set is zero go get the next page.
            all_users = identity_vault.all_filtered(
                connection_method=args.get("connectionMethod"),
                active=active,
                next_page=all_users["nextPage"])

        # Convert vault data to cis-profile-like data format
        all_users_cis = []
        for cuser in all_users["users"]:
            all_users_cis.append({
                "uuid": cuser["user_uuid"]["S"],
                "user_id": cuser["id"]["S"],
                "primary_email": cuser["primary_email"]["S"],
                "active": cuser["active"]["BOOL"],
            })

        logger.debug("Returning {} users".format(len(all_users_cis)))
        return dict(users=all_users_cis, nextPage=all_users.get("nextPage"))
예제 #5
0
파일: v2_api.py 프로젝트: mozilla-iam/cis
def getUser(id, find_by):
    """Return a single user with identifier using find_by."""
    id = urllib.parse.unquote(id)
    parser = reqparse.RequestParser()
    parser.add_argument("Authorization", location="headers")
    parser.add_argument("filterDisplay", type=str)
    parser.add_argument("active", type=str)
    args = parser.parse_args()
    scopes = get_scopes(args.get("Authorization"))
    filter_display = args.get("filterDisplay", None)

    if args.get("active") is not None and args.get("active").lower() == "false":
        active = False
    elif args.get("active") is not None and args.get("active").lower() == "any":
        active = None
    else:
        active = True

    if transactions == "false":
        identity_vault = user.Profile(dynamodb_table, dynamodb_client, transactions=False)

    if transactions == "true":
        identity_vault = user.Profile(dynamodb_table, dynamodb_client, transactions=True)

    result = find_by(identity_vault, id)

    if len(result["Items"]) > 0:
        vault_profile = result["Items"][0]["profile"]
        v2_profile = User(user_structure_json=json.loads(vault_profile))

        if v2_profile.active.value == active or active is None:
            if "read:fullprofile" in scopes:
                logger.debug(
                    "read:fullprofile in token not filtering based on scopes.",
                    extra={"query_args": args, "scopes": scopes},
                )
            else:
                v2_profile.filter_scopes(scope_to_mozilla_data_classification(scopes))

            if "display:all" in scopes:
                logger.debug(
                    "display:all in token not filtering profile based on display.",
                    extra={"query_args": args, "scopes": scopes},
                )
            else:
                v2_profile.filter_display(scope_to_display_level(scopes))

            if filter_display is not None:
                logger.debug(
                    "filter_display argument is passed, applying display level filter.", extra={"query_args": args}
                )
                v2_profile.filter_display(DisplayLevelParms.map(filter_display))

            return jsonify(v2_profile.as_dict())

    logger.debug("No user was found for the query", extra={"query_args": args, "scopes": scopes})
    return jsonify({})
예제 #6
0
파일: profile.py 프로젝트: mozilla-iam/cis
    def delete_profile(self, profile_json):
        # XXX This method should be refactored to look like put_profiles() / put_profile()
        self.condition = "delete"

        try:
            user_profile = dict(
                id=profile_json["user_id"]["value"],
                primary_email=profile_json["primary_email"]["value"],
                user_uuid=profile_json["uuid"]["value"],
                primary_username=profile_json["primary_username"]["value"],
                sequence_number=self.sequence_number,
                profile=json.dumps(profile_json),
            )

            if self.config("dynamodb_transactions", namespace="cis") == "true":
                logger.debug(
                    "Attempting to put batch of profiles using transactions.")
                vault = user.Profile(self.identity_vault_client.get("table"),
                                     self.identity_vault_client.get("client"),
                                     transactions=True)
            else:
                logger.info(
                    "Attempting to put batch of profiles without transactions."
                )
                vault = user.Profile(
                    self.identity_vault_client.get("table"),
                    self.identity_vault_client.get("client"),
                    transactions=False,
                )

            vault.delete(user_profile)
        except ClientError as e:
            logger.error(
                "An error occured removing this profile from dynamodb",
                extra={
                    "profile": profile_json,
                    "error": e,
                    "trace": format_exc()
                },
            )
            logger.error(e)
            raise IntegrationError(
                {
                    "code": "integration_exception",
                    "description": "{}".format(e)
                }, 500)
        return {
            "status":
            200,
            "message":
            "user profile deleted for user: {}".format(
                profile_json["user_id"]["value"]),
            "condition":
            self.condition,
        }
예제 #7
0
    def test_find_user_multi_id_for_username(self):
        from cis_identity_vault.models import user

        primary_username = "******"
        modified_profile = self.user_profile
        modified_profile["primary_username"]["value"] = primary_username
        modified_profile["active"]["value"] = False
        vault_json_datastructure_first_id = {
            "id":
            modified_profile.get("user_id").get("value"),
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        profile.update(vault_json_datastructure_first_id)

        vault_json_datastructure_second_id = {
            "id":
            "foo|mcbar",
            "user_uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
            "active":
            True,
        }

        profile.update(vault_json_datastructure_second_id)

        profile = user.Profile(self.table)
        self.user_profile.get("user_id").get("value")
        result_for_username = profile.find_by_username(primary_username)
        assert result_for_username is not None
        assert len(result_for_username.get("Items")) == 2
예제 #8
0
파일: profile.py 프로젝트: romanom/cis
    def _store_in_vault(self, profiles):
        """
        Actually store profiles in the vault
        All profiles must have been merged and verified correctly before calling this method

        @profiles list of cis_profiles.User

        Returns dict {"creates": result_of_users_created, "updates": result_of_users_updates}
        """

        # Vault profiles (not cis_profile.User objects)
        vault_profiles = []

        try:
            self._connect()

            if self.config("dynamodb_transactions", namespace="cis") == "true":
                logger.debug("Attempting to put batch of profiles ({}) using transactions.".format(len(profiles)))
                vault = user.Profile(
                    self.identity_vault_client.get("table"), self.identity_vault_client.get("client"), transactions=True
                )
            else:
                logger.debug(
                    "Attempting to put batch of profiles ({}) without using transactions.".format(len(profiles))
                )
                vault = user.Profile(
                    self.identity_vault_client.get("table"),
                    self.identity_vault_client.get("client"),
                    transactions=False,
                )

            # transform cis_profiles.User profiles to vault profiles
            for user_profile in profiles:
                vault_profile = dict(
                    id=user_profile.user_id.value,
                    primary_email=user_profile.primary_email.value,
                    user_uuid=user_profile.uuid.value,
                    primary_username=user_profile.primary_username.value,
                    sequence_number=self.sequence_number,
                    profile=user_profile.as_json(),
                )
                vault_profiles.append(vault_profile)

            result = vault.find_or_create_batch(vault_profiles)
        except ClientError as e:
            logger.error(
                "An error occured writing these profiles to dynamodb",
                extra={"profiles": profiles, "error": e, "trace": format_exc()},
            )
            raise IntegrationError({"code": "integration_exception", "description": "{}".format(e)}, 500)
        # The result looks something like this:
        # result = {'creates': {'status': '200',
        # 'sequence_numbers': ['285229813155718975995433494324446866394']}, 'updates': None, 'status': 200}"}
        return {"creates": result[0], "updates": result[1], "status": 200}
예제 #9
0
def get_identity_vault():
    if transactions == "false":
        identity_vault = user.Profile(dynamodb_table,
                                      dynamodb_client,
                                      transactions=False)
    elif transactions == "true":
        identity_vault = user.Profile(dynamodb_table,
                                      dynamodb_client,
                                      transactions=True)
    else:
        identity_vault = user.Profile(dynamodb_table,
                                      dynamodb_client,
                                      transactions=False)
    return identity_vault
예제 #10
0
def get_all_by_any():
    setup_environment()
    u = user.Profile(dynamodb_table_resource=dynamodb_table,
                     dynamodb_client=dynamodb_client,
                     transactions=True)
    results = []
    pages = []

    result = u.find_by_any(attr="staff_information.director",
                           comparator=True,
                           full_profiles=False)

    results.extend(result["users"])

    while result.get('nextPage'):
        if result.get('nextPage') in pages:
            break

        pages.append(result.get('nextPage'))
        logger.info("Trying to follow the page.")
        logger.info("Next page currently is: {}".format(
            result.get("nextPage")))
        result = u.find_by_any(attr="staff_information.staff",
                               comparator=True,
                               next_page=result.get("nextPage"))
        results.extend(result["users"])
        logger.info("Total records retrieved: {}".format(len(results)))
    logger.info("Total records retrieved: {}".format(len(results)))
예제 #11
0
def seed(number_of_fake_users=100):
    seed_data = config("seed_api_data", namespace="cis", default="false")
    if seed_data.lower() == "true":
        table = get_table_resource()
        user_profile = user.Profile(table, None, False)

        if len(user_profile.all) > 0:
            pass
        else:
            identities = batch_create_fake_profiles(1337, number_of_fake_users)

            for identity in identities:
                identity_vault_data_structure = {
                    "id":
                    identity.get("user_id").get("value"),
                    "primary_email":
                    identity.get("primary_email").get("value"),
                    "uuid":
                    identity.get("uuid").get("value"),
                    "primary_username":
                    identity.get("primary_username").get("value"),
                    "sequence_number":
                    "1234567890",
                    "profile":
                    dumps(identity),
                }

                user_profile.create(identity_vault_data_structure)
예제 #12
0
    def test_that_we_seeded_the_table(self):
        os.environ["CIS_CONFIG_INI"] = "tests/mozilla-cis.ini"
        from cis_identity_vault.models import user

        profile = user.Profile(self.table)
        profiles = profile.all
        assert len(profiles) >= 54
예제 #13
0
    def test_base_operation_object_it_should_succeed(self, verify_sigs, verify_pubs):
        verify_sigs.return_value = True
        verify_pubs.return_value = True
        os.environ["CIS_PROCESSOR_VERIFY_SIGNATURES"] = "False"
        patched_profile = self.mr_mozilla_profile
        patched_profile["last_name"]["value"] = "anupdatedlastname"
        kinesis_event = kinesis_event_generate(patched_profile)

        from cis_processor import operation

        for kinesis_record in kinesis_event["Records"]:
            base_operation = operation.BaseProcessor(
                event_record=kinesis_record, dynamodb_client=self.dynamodb_client, dynamodb_table=self.table
            )
            base_operation._load_profiles()
            needs_integration = base_operation.needs_integration(
                base_operation.profiles["new_profile"], base_operation.profiles["old_profile"]
            )
            assert needs_integration is True
            assert (
                base_operation.profiles["new_profile"].verify_all_publishers(base_operation.profiles["old_profile"])
                is True
            )
            assert base_operation.process() is True

        from cis_identity_vault.models import user

        p = user.Profile(self.table, self.dynamodb_client, False)
        p.find_by_id(id=base_operation.profiles["new_profile"].as_dict()["user_id"]["value"])
예제 #14
0
    def setup(self):
        os.environ["CIS_CONFIG_INI"] = "tests/fixture/mozilla-cis.ini"
        self.config = get_config()
        from cis_profile import WellKnown
        from cis_identity_vault import vault

        os.environ["CIS_CONFIG_INI"] = "tests/fixture/mozilla-cis.ini"
        well_known = WellKnown()
        self.well_known_json = well_known.get_well_known()

        self.dynamodb_client = boto3.client(
            "dynamodb", region_name="us-west-2", aws_access_key_id="ak", aws_secret_access_key="sk"
        )

        self.dynamodb_resource = boto3.resource(
            "dynamodb", region_name="us-west-2", aws_access_key_id="ak", aws_secret_access_key="sk"
        )

        self.vault_client = vault.IdentityVault()
        self.vault_client.boto_session = Stubber(boto3.session.Session(region_name="us-west-2")).client
        self.vault_client.dynamodb_client = self.dynamodb_client
        self.vault_client.find_or_create()
        self.table = self.dynamodb_resource.Table("testing-identity-vault")
        self.mr_mozilla_profile = fake_profile.FakeUser(seed=1337).as_dict()

        from cis_identity_vault.models import user

        vault_interface = user.Profile(self.table, self.dynamodb_client, False)
        vault_interface.create(profile_to_vault_structure(user_profile=self.mr_mozilla_profile))
        self.mr_mozilla_change_event = kinesis_event_generate(self.mr_mozilla_profile)
예제 #15
0
def filtered_scan_wrapper():
    setup_environment()
    u = user.Profile(dynamodb_table_resource=dynamodb_table,
                     dynamodb_client=dynamodb_client,
                     transactions=True)
    connection_methods = ["github", "ad", "email", "oauth2", "google-oauth2"]
    results = []

    for conn_method in connection_methods:
        result = u.all_filtered(connection_method=conn_method,
                                active=True,
                                next_page=None)

        results.extend(result["users"])

        while result.get("nextPage"):
            logger.info("Trying to follow the page.")
            logger.info("Next page currently is: {}".format(
                result.get("nextPage")))
            result = u.all_filtered(connection_method=conn_method,
                                    active=True,
                                    next_page=result.get("nextPage"))
            results.extend(result["users"])
            logger.debug("Total records retrieved: {}".format(len(results)))

    logger.debug("Total records retrieved: {}".format(len(results)))
예제 #16
0
    def test_update_method(self):
        from cis_identity_vault.models import user

        modified_profile = self.user_profile
        modified_profile["primary_email"]["value"] = "*****@*****.**"

        vault_json_datastructure = {
            "id":
            modified_profile.get("user_id").get("value"),
            "uuid":
            str(uuid.uuid4()),
            "primary_email":
            modified_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(modified_profile),
        }
        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.update(vault_json_datastructure)
        assert result is not None
예제 #17
0
파일: profile.py 프로젝트: viorelaioia/cis
    def put_profiles(self, profile_list):
        """Write profile to the identity vault."""
        self._connect()

        if self.config("dynamodb_transactions", namespace="cis") == "true":
            logger.info(
                "Attempting to put batch of profiles using transacations.")
            vault = user.Profile(self.identity_vault_client.get("table"),
                                 self.identity_vault_client.get("client"),
                                 transactions=True)
        else:
            logger.info(
                "Attempting to put batch of profiles without transactions.")
            vault = user.Profile(self.identity_vault_client.get("table"),
                                 self.identity_vault_client.get("client"),
                                 transactions=False)

        user_profiles = []

        for profile_json in profile_list:
            if isinstance(profile_json, str):
                profile_json = json.loads(profile_json)

            # Run some code that updates attrs and metadata for attributes cis is trusted to assert
            self._update_attr_owned_by_cis(profile_json)
            verified = self._verify(profile_json)
            if verified:
                logger.info(
                    "Profiles have been verified. Constructing dictionary for storage."
                )
                user_profile = dict(
                    id=profile_json["user_id"]["value"],
                    primary_email=profile_json["primary_email"]["value"],
                    uuid=profile_json["uuid"]["value"],
                    primary_username=profile_json["primary_username"]["value"],
                    sequence_number=self.sequence_number,
                    profile=json.dumps(profile_json),
                )
                user_profiles.append(user_profile)
            else:
                # XXX TBD Do something else
                pass
        logger.info(
            "Attempting to send batch of {} profiles as a transaction.".format(
                len(user_profiles)))
        return vault.find_or_create_batch(user_profiles)
예제 #18
0
    def test_create_method(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.create(self.vault_json_datastructure)
        assert result is not None
예제 #19
0
    def setup(self):
        os.environ["CIS_ENVIRONMENT"] = "purple"
        os.environ["CIS_REGION_NAME"] = "us-east-1"
        os.environ["DEFAULT_AWS_REGION"] = "us-east-1"
        self.vault_client = vault.IdentityVault()
        self.vault_client.connect()
        self.vault_client.find_or_create()
        self.boto_session = boto3.session.Session(region_name="us-east-1")
        self.dynamodb_resource = self.boto_session.resource("dynamodb")
        self.dynamodb_client = self.boto_session.client("dynamodb")
        self.table = self.dynamodb_resource.Table("purple-identity-vault")

        for x in range(0, 50):  # Must generate 50 users to test paginator
            user_profile = FakeUser().as_dict()
            user_profile["active"]["value"] = True
            uuid = user_profile["uuid"]["value"]
            vault_json_datastructure = {
                "id":
                user_profile.get("user_id").get("value"),
                "user_uuid":
                uuid,
                "primary_email":
                user_profile.get("primary_email").get("value"),
                "primary_username":
                user_profile.get("primary_username").get("value"),
                "sequence_number":
                "12345678",
                "profile":
                json.dumps(user_profile),
                "active":
                True,
            }
            from cis_identity_vault.models import user

            profile = user.Profile(self.table,
                                   self.dynamodb_client,
                                   transactions=False)
            profile.create(vault_json_datastructure)

        self.user_profile = FakeUser().as_dict()
        self.user_profile["active"]["value"] = True
        self.uuid = self.user_profile["uuid"]["value"]
        self.vault_json_datastructure = {
            "id":
            self.user_profile.get("user_id").get("value"),
            "user_uuid":
            self.uuid,
            "primary_email":
            self.user_profile.get("primary_email").get("value"),
            "primary_username":
            self.user_profile.get("primary_username").get("value"),
            "sequence_number":
            "12345678",
            "profile":
            json.dumps(self.user_profile),
            "active":
            True,
        }
예제 #20
0
    def test_namespace_generator(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)

        result = profile._namespace_generator("access_information.ldap", "foo")
        assert result == "flat_profile.access_information.ldap.foo"
예제 #21
0
    def test_find_by_username(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table, self.dynamodb_client, transactions=False)

        user = json.loads(profile.all[0].get("profile"))

        result_for_username = profile.find_by_username(user["primary_username"]["value"])
        assert len(result_for_username.get("Items")) > 0
예제 #22
0
    def setup(self):
        self.helper_configuration = helpers.Configuration()
        cis_environment = os.getenv("CIS_ENVIRONMENT", "development")
        os.environ["CIS_ENVIRONMENT"] = cis_environment
        os.environ["CIS_ASSUME_ROLE_ARN"] = "None"
        self.connection_object = connect.AWS()
        self.connection_object._boto_session = boto3.session.Session(
            region_name="us-west-2")
        self.idv = self.connection_object.identity_vault_client()
        # u = fake_profile.FakeUser()
        # u = helpers.ensure_appropriate_publishers_and_sign(fake_profile=u, condition="create")
        # u.verify_all_publishers(profile.User(user_structure_json=None))

        fh = open("fixtures/durable.json")
        self.durable_profile = fh.read()
        fh.close()

        self.durable_profiles = []

        logger.info("Loading 10 fake users.")
        for x in range(0, 10):
            fh = open("fixtures/{}.json".format(x))
            self.durable_profiles.append(fh.read())
            fh.close()

        logger.info(
            "Bypassing change service and writing directly to the id_vault.")
        vault = user.Profile(dynamodb_table_resource=self.idv["table"],
                             dynamodb_client=self.idv["client"],
                             transactions=True)

        this_user = json.loads(self.durable_profile)
        user_profile = {
            "id": this_user["user_id"]["value"],
            "profile": self.durable_profile,
            "primary_username": this_user["primary_username"]["value"],
            "primary_email": this_user["primary_email"]["value"],
            "user_uuid": this_user["uuid"]["value"],
            "sequence_number": "1",
        }

        res = vault.find_or_create(user_profile)
        logger.info("Single user created in vault result: {}".format(res))

        for this_profile in self.durable_profiles:
            this_user = json.loads(this_profile)
            user_profile = {
                "id": this_user["user_id"]["value"],
                "profile": this_profile,
                "primary_username": this_user["primary_username"]["value"],
                "primary_email": this_user["primary_email"]["value"],
                "user_uuid": this_user["uuid"]["value"],
                "sequence_number": "1",
            }
            res = vault.find_or_create(user_profile=user_profile)
            logger.info("Single user created in vault result: {}".format(res))
예제 #23
0
파일: common.py 프로젝트: mozilla-iam/cis
def seed(number_of_fake_users=100):
    seed_data = config("seed_api_data", namespace="cis", default="false")
    if seed_data.lower() == "true":
        table = get_table_resource()
        user_profile = user.Profile(table, None, False)

        if len(user_profile.all) > 0:
            logger.info(
                "Identity vault is already seeded.  Passing on the additiona of users."
            )
            pass
        else:
            logger.info("Beginning the creation of seed users.")
            identities = batch_create_fake_profiles(1337, number_of_fake_users)

            for identity in identities:
                identity["pronouns"]["metadata"]["display"] = None
                identity_vault_data_structure = {
                    "id":
                    identity.get("user_id").get("value"),
                    "primary_email":
                    identity.get("primary_email").get("value"),
                    "user_uuid":
                    identity.get("uuid").get("value"),
                    "primary_username":
                    identity.get("primary_username").get("value"),
                    "sequence_number":
                    "1234567890",
                    "profile":
                    dumps(identity),
                }

                user_profile.create(identity_vault_data_structure)

            identities = batch_create_fake_profiles(1337, 1)

            for identity in identities:
                identity["pronouns"]["metadata"]["display"] = None
                identity["active"]["value"] = False
                identity_vault_data_structure = {
                    "id":
                    identity.get("user_id").get("value"),
                    "primary_email":
                    identity.get("primary_email").get("value"),
                    "user_uuid":
                    identity.get("uuid").get("value"),
                    "primary_username":
                    identity.get("primary_username").get("value"),
                    "sequence_number":
                    "1234567890",
                    "profile":
                    dumps(identity),
                }
                user_profile.create(identity_vault_data_structure)
            logger.info(
                "Count: {} seed users created.".format(number_of_fake_users))
예제 #24
0
파일: v2_api.py 프로젝트: viorelaioia/cis
def getUser(id, find_by):
    """Return a single user with identifier using find_by."""
    id = urllib.parse.unquote(id)
    parser = reqparse.RequestParser()
    parser.add_argument("Authorization", location="headers")
    parser.add_argument("filterDisplay", type=str)
    args = parser.parse_args()
    scopes = get_scopes(args.get("Authorization"))
    filter_display = args.get("filterDisplay", None)

    if transactions == "false":
        identity_vault = user.Profile(dynamodb_table,
                                      dynamodb_client,
                                      transactions=False)

    if transactions == "true":
        identity_vault = user.Profile(dynamodb_table,
                                      dynamodb_client,
                                      transactions=True)

    result = find_by(identity_vault, id)

    if len(result["Items"]) > 0:
        vault_profile = result["Items"][0]["profile"]
        v2_profile = User(user_structure_json=json.loads(vault_profile))
        if "read:fullprofile" in scopes:
            logger.debug(
                "read:fullprofile in token returning the full user profile.")
        else:
            v2_profile.filter_scopes(
                scope_to_mozilla_data_classification(scopes))

        if "display:all" in scopes:
            logger.debug("display:all in token not filtering profile.")
        else:
            v2_profile.filter_display(scope_to_display_level(scopes))

        if filter_display is not None:
            v2_profile.filter_display(DisplayLevelParms.map(filter_display))

        return jsonify(v2_profile.as_dict())
    else:
        return jsonify({})
예제 #25
0
    def seed_fake_users(self):
        from cis_identity_vault.models import user

        u = user.Profile(
            dynamodb_table_resource=boto3.resource(
                "dynamodb",
                region_name="us-east-1").Table("testing-identity-vault"),
            dynamodb_client=boto3.client("dynamodb", region_name="us-east-1"),
            transactions=False,
        )
        u.create_batch(self.events_and_users["users"])
예제 #26
0
    def resolve_profile(self, info, **kwargs):
        """GraphQL resolver for a single profile."""
        table = get_table_resource()
        vault = user.Profile(table)

        if kwargs.get("userId"):
            search = vault.find_by_id(kwargs.get("userId"))
            if len(search.get("Items")) > 0:
                resp = search["Items"][0]["profile"]
        else:
            resp = json.dumps({})
        return resp
예제 #27
0
파일: profile.py 프로젝트: viorelaioia/cis
    def put_profile(self, profile_json):
        """Write profile to the identity vault."""
        self._connect()

        if isinstance(profile_json, str):
            profile_json = json.loads(profile_json)

        # Run some code that updates attrs and metadata for attributes cis is trusted to assert
        self._update_attr_owned_by_cis(profile_json)
        verified = self._verify(profile_json)

        if verified:
            if self.config("dynamodb_transactions", namespace="cis") == "true":
                vault = user.Profile(
                    self.identity_vault_client.get("table"),
                    self.identity_vault_client.get("client"),
                    transactions=True,
                )
            else:
                vault = user.Profile(
                    self.identity_vault_client.get("table"),
                    self.identity_vault_client.get("client"),
                    transactions=False,
                )

            user_profile = dict(
                id=profile_json["user_id"]["value"],
                primary_email=profile_json["primary_email"]["value"],
                uuid=profile_json["uuid"]["value"],
                primary_username=profile_json["primary_username"]["value"],
                sequence_number=self.sequence_number,
                profile=json.dumps(profile_json),
            )

            res = vault.find_or_create(user_profile)
            return res
        else:
            # XXX TBD do something else.
            pass
예제 #28
0
 def resolve_profiles(self, info, **kwargs):
     """GraphQL resolver for the profiles attribute."""
     table = get_table_resource()
     vault = user.Profile(table)
     profiles = []
     if kwargs.get("primaryEmail"):
         search = vault.find_by_email(kwargs.get("primaryEmail"))
         if len(search.get("Items")) > 0:
             for profile in search.get("Items"):
                 profiles.append(json.loads())
     else:
         for vault_profile in vault.all:
             profiles.append(json.loads(vault_profile.get("profile")))
예제 #29
0
    def test_all_by_filter(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table, self.dynamodb_client, transactions=False)
        result = profile.all_filtered(connection_method="email")
        assert len(result) > 0

        result = profile.all_filtered(connection_method="email", active=True)
        assert len(result) > 0
        for record in result:
            assert record["active"]["BOOL"] is True

        result = profile.all_filtered(connection_method="email", active=False)
        for record in result:
            assert record["active"]["BOOL"] is False
예제 #30
0
    def test_all_by_filter(self):
        from cis_identity_vault.models import user

        profile = user.Profile(self.table,
                               self.dynamodb_client,
                               transactions=False)
        result = profile.all_filtered(connection_method="email", active=None)
        assert len(result["users"]) > 0
        assert result.get("nextPage") is None
        logger.debug(f"The result of the filtered query is: {result}")

        result = profile.all_filtered(connection_method="email", active=True)
        assert len(result["users"]) > 0
        for record in result["users"]:
            assert record["active"]["BOOL"] is True