Example #1
0
def create_app(config_class="config.ProdConfig", user_class=User):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.json_encoder = Serializer
    CORS(app)
    app.config.from_object(config_class)

    with app.app_context():
        logger = logging.getLogger(__name__)
        log_level = app.config.get("LOG_LEVEL")
        logging.basicConfig(level=log_level)

        from oktaadminapi import groups, factors, users
        app.register_blueprint(factors.bp, url_prefix="/api/v1/users")
        app.register_blueprint(groups.bp, url_prefix="/api/v1/groups")
        app.register_blueprint(users.bp, url_prefix="/api/v1/users")

        # set up the users client. we have to do this here because there's
        # no other way to get the custom User subclass into the blueprint
        app.usersClient = UsersClient(base_url=app.config.get("ORG_NAME"),
                                      api_token=app.config.get("API_TOKEN"),
                                      user_class=user_class)

        logger.info("Org name: {0}".format(app.config.get("ORG_NAME")))
        logger.info("API token: {0}".format(app.config.get("API_TOKEN")))
        logger.info("Issuer: {0}".format(app.config.get("ISSUER")))
        logger.info("Audience: {0}".format(app.config.get("AUDIENCE")))
        logger.info("JWKS caching: {0}".format(app.config.get("CACHE_METHOD")))
        logger.info("S3 Bucket: {0}".format(app.config.get("BUCKET_NAME")))
        return app
Example #2
0
    def setUp(self):
        self.client = UsersClient(base_url="https://mockta.com",
                                  api_token="abcdefg")

        with open("tests/data/user.json", "r") as file:
            self.user = file.read()

        self.user_json = Utils.deserialize(self.user, User)

        with open("tests/data/users.json", "r") as file:
            self.users = file.read()

        self.users_json = Utils.deserialize(self.users, User)

        with open("tests/data/user_groups.json", "r") as file:
            self.user_groups = file.read()

        self.user_groups_json = Utils.deserialize(self.user_groups, UserGroup)

        with open("tests/data/created_user.json", "r") as file:
            self.created_user = file.read()

        self.created_user_json = Utils.deserialize(self.created_user, User)
from okta.UsersClient import UsersClient
from okta.FactorsClient import FactorsClient
from okta.framework.OktaError import OktaError
from script_config import base_url, api_token, user_id

usersClient = UsersClient(base_url=base_url, api_token=api_token)
factorsClient = FactorsClient(base_url=base_url, api_token=api_token)

user = usersClient.get_user(user_id)

print("Enroll SMS factor started")
phone_number = input("Please enter your phone number (just numbers please): ")
enroll_request = {
    "factorType": "sms",
    "provider": "OKTA",
    "profile": {
        "phoneNumber": phone_number
    }
}

try:
    response = factorsClient.enroll_factor(user_id, enroll_request)
    result = response.status
    factor_id = response.id
except OktaError as e:
    print(e.error_causes)
    exit(2)

while result == "PENDING_ACTIVATION":
    # active when done
    try:
Example #4
0
class UsersClientTest(unittest.TestCase):

    def setUp(self):
        self.client = UsersClient(base_url="https://mockta.com",
                                  api_token="abcdefg")

        with open("tests/data/user.json", "r") as file:
            self.user = file.read()

        self.user_json = Utils.deserialize(self.user, User)

        with open("tests/data/users.json", "r") as file:
            self.users = file.read()

        self.users_json = Utils.deserialize(self.users, User)

        with open("tests/data/user_groups.json", "r") as file:
            self.user_groups = file.read()

        self.user_groups_json = Utils.deserialize(self.user_groups, UserGroup)

        with open("tests/data/created_user.json", "r") as file:
            self.created_user = file.read()

        self.created_user_json = Utils.deserialize(self.created_user, User)

    def tearDown(self):
        pass

    @patch("okta.framework.ApiClient.requests.post")
    def test_activate_user_in_staged_status_returns_ok(self, mock_post):
        user = self.created_user_json
        activation_response = """
        {
            "activationUrl": "https://subdomain.okta.com/welcome/XE6wE17zmphl3KqAPFxO",
            "activationToken": "XE6wE17zmphl3KqAPFxO"
        }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=activation_response)
        response = self.client.activate_user(user.id, send_email=False)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, ActivationResponse)

    @patch("okta.framework.ApiClient.requests.post")
    def test_activate_user_not_in_staged_status_raises_okta_error(self, mock_post):
        user = self.created_user_json
        activation_response = """
            {
                "errorCode": "E0000016",
                "errorSummary": "Activation failed because the user is already active",
                "errorLink": "E0000016",
                "errorId": "oaeXSgWaUtkTvm8Vj9dkWGKiA",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_403_FORBIDDEN, text=activation_response)

        with self.assertRaises(OktaError):
            response = self.client.activate_user(user.id, send_email=False)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_deactivate_user_not_in_deprovisioned_status_returns_ok(self, mock_post):
        user = self.created_user_json
        deactivation_response = "{}"
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=deactivation_response)
        response = self.client.deactivate_user(user.id)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)

    @patch("okta.framework.ApiClient.requests.post")
    def test_deactivate_user_in_deprovisioned_status_raises_okta_error(self, mock_post):
        user = self.created_user_json
        deactivation_response = """
            {
                "errorCode": "E0000007",
                "errorSummary": "Not found: Resource not found: 00us1r8ltrdVHGEJU0h7 (User)",
                "errorLink": "E0000007",
                "errorId": "oaeQJJQ-IClRTay4IS780nTiQ",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_404_NOT_FOUND, text=deactivation_response)

        with self.assertRaises(OktaError):
            response = self.client.deactivate_user(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_suspend_user_in_active_status_returns_ok(self, mock_post):
        user = self.created_user_json
        deactivation_response = "{}"
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=deactivation_response)
        response = self.client.suspend_user(user.id)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)

    @patch("okta.framework.ApiClient.requests.post")
    def test_suspend_user_not_in_active_status_raises_okta_error(self, mock_post):
        user = self.created_user_json
        suspend_response = """
            {
                "errorCode": "E0000001",
                "errorSummary": "Api validation failed: suspendUser",
                "errorLink": "E0000001",
                "errorId": "oaeEZ0YOffyTiKJMrfTUGdGMg",
                "errorCauses": [
                    {
                        "errorSummary": "Cannot suspend a user that is not active"
                    }
                ]
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_400_BAD_REQUEST, text=suspend_response)

        with self.assertRaises(OktaError):
            response = self.client.suspend_user(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_suspend_user_not_found_raises_okta_error(self, mock_post):
        user = self.created_user_json
        suspend_response = """
            {
                "errorCode": "E0000007",
                "errorSummary": "Not found: Resource not found: 00us1r8ltrdVHGEJU0h7 (User)",
                "errorLink": "E0000007",
                "errorId": "oaeQJJQ-IClRTay4IS780nTiQ",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_404_NOT_FOUND, text=suspend_response)

        with self.assertRaises(OktaError):
            response = self.client.suspend_user(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_unsuspend_user_in_suspend_status_returns_ok(self, mock_post):
        user = self.created_user_json
        unsuspend_response = "{}"
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=unsuspend_response)
        response = self.client.suspend_user(user.id)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)

    @patch("okta.framework.ApiClient.requests.post")
    def test_unsuspend_user_not_in_suspend_status_raises_okta_error(self, mock_post):
        user = self.created_user_json
        unsuspend_response = """
            {
                "errorCode": "E0000001",
                "errorSummary": "Api validation failed: suspendUser",
                "errorLink": "E0000001",
                "errorId": "oaeEZ0YOffyTiKJMrfTUGdGMg",
                "errorCauses": [
                    {
                        "errorSummary": "Cannot unsuspend a user that is not suspended"
                    }
                ]
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_400_BAD_REQUEST, text=unsuspend_response)

        with self.assertRaises(OktaError):
            response = self.client.suspend_user(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_unsuspend_user_not_found_raises_okta_error(self, mock_post):
        user = self.created_user_json
        unsuspend_response = """
            {
                "errorCode": "E0000007",
                "errorSummary": "Not found: Resource not found: 00us1r8ltrdVHGEJU0h7 (User)",
                "errorLink": "E0000007",
                "errorId": "oaeQJJQ-IClRTay4IS780nTiQ",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_404_NOT_FOUND, text=unsuspend_response)

        with self.assertRaises(OktaError):
            response = self.client.suspend_user(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_unlock_user_in_locked_out_status_returns_ok(self, mock_post):
        user = self.created_user_json
        unlock_response = "{}"
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=unlock_response)
        response = self.client.unlock_user(user.id)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)

    @patch("okta.framework.ApiClient.requests.post")
    def test_unlock_user_not_found_raises_okta_error(self, mock_post):
        user = self.created_user_json
        unlock_response = """
            {
                "errorCode": "E0000007",
                "errorSummary": "Not found: Resource not found: 00us1r8ltrdVHGEJU0h7 (User)",
                "errorLink": "E0000007",
                "errorId": "oaeQJJQ-IClRTay4IS780nTiQ",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_404_NOT_FOUND, text=unlock_response)

        with self.assertRaises(OktaError):
            response = self.client.suspend_user(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_unlock_user_not_in_locked_out_status_raises_okta_error(self, mock_post):
        user = self.created_user_json
        unlock_response = """
            {
                "errorCode": "E0000032",
                "errorSummary": "Unlock is not allowed for this user.",
                "errorLink": "E0000032",
                "errorId": "oaelf2h18-jTBW7wE8kDhC2-Q",
                "errorCauses": [
                    {
                        "errorSummary": "The user is not locked out."
                    }
                ]
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_403_FORBIDDEN, text=unlock_response)
        
        with self.assertRaises(OktaError):
            response = self.client.unlock_user(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_reset_password_returns_ok(self, mock_post):
        user = self.created_user_json
        reset_password_response = """
            {
                "resetPasswordUrl": "https://wallick.oktapreview.com/reset_password/drpGwLleDltyCLJHXlDx"
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=reset_password_response)
        response = self.client.reset_password(user.id)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, ResetPasswordToken)

    @patch("okta.framework.ApiClient.requests.post")
    def test_reset_password_user_not_found_raises_okta_error(self, mock_post):
        user = self.created_user_json
        reset_password_response = """
            {
                "errorCode": "E0000007",
                "errorSummary": "Not found: Resource not found: 00us1r8ltrdVHGEJU0h7 (User)",
                "errorLink": "E0000007",
                "errorId": "oaeQJJQ-IClRTay4IS780nTiQ",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_404_NOT_FOUND, text=reset_password_response)

        with self.assertRaises(OktaError):
            response = self.client.reset_password(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_change_password_returns_ok(self, mock_post):
        user = self.created_user_json
        change_password_response = """
            {
                "password": {},
                "recovery_question": {
                    "question": "What is the food you least liked as a child?"
                },
                "provider": {
                    "type": "OKTA",
                    "name": "OKTA"
                }
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=change_password_response)
        response = self.client.change_password(user.id, "oldpw", "newpw")
        
        self.assertIsNotNone(response)
        self.assertIsInstance(response, LoginCredentials)

    @patch("okta.framework.ApiClient.requests.post")
    def test_change_recovery_question_returns_ok(self, mock_post):
        user = self.created_user_json
        change_recovery_question_response = """
            {
                "password": {},
                "recovery_question": {
                    "question": "What is the food you least liked as a child?"
                },
                "provider": {
                    "type": "OKTA",
                    "name": "OKTA"
                }
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=change_recovery_question_response)
        response = self.client.change_recovery_question(user.id, "password", "question", "answer")
        
        self.assertIsNotNone(response)
        self.assertIsInstance(response, LoginCredentials)

    @patch("okta.framework.ApiClient.requests.post")
    def test_expire_password_no_temp_password_returns_ok(self, mock_post):
        user = self.created_user_json
        expire_password_response = self.created_user
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=expire_password_response)
        response = self.client.expire_password(user.id)
        
        self.assertIsNotNone(response)
        self.assertIsInstance(response, TempPassword)

    @patch("okta.framework.ApiClient.requests.post")
    def test_expire_password_with_temp_password_returns_ok(self, mock_post):
        user = self.created_user_json
        expire_password_response = """
            {
                "tempPassword": "******"
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=expire_password_response)
        response = self.client.expire_password(user.id, temp_password=True)
        
        self.assertIsNotNone(response)
        self.assertIsInstance(response, TempPassword)

    @patch("okta.framework.ApiClient.requests.post")
    def test_expire_password_user_not_found_raises_okta_error(self, mock_post):
        user = self.created_user_json
        expire_password_response = """
            {
                "errorCode": "E0000007",
                "errorSummary": "Not found: Resource not found: 00us1r8ltrdVHGEJU0h7 (User)",
                "errorLink": "E0000007",
                "errorId": "oaeQJJQ-IClRTay4IS780nTiQ",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_404_NOT_FOUND, text=expire_password_response)

        with self.assertRaises(OktaError):
            response = self.client.expire_password(user.id)
            self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.post")
    def test_reset_factors_returns_ok(self, mock_post):
        user = self.created_user_json
        reset_factor_response = "{}"
        mock_post.return_value = Mock(
            status_code=status.HTTP_200_OK, text=reset_factor_response)
        response = self.client.reset_factors(user.id)
        
        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)

    @patch("okta.framework.ApiClient.requests.post")
    def test_reset_factors_user_not_found_raises_okta_error(self, mock_post):
        user = self.created_user_json
        reset_factor_response = """
            {
                "errorCode": "E0000007",
                "errorSummary": "Not found: Resource not found: 00us1r8ltrdVHGEJU0h7 (User)",
                "errorLink": "E0000007",
                "errorId": "oaeQJJQ-IClRTay4IS780nTiQ",
                "errorCauses": []
            }
        """
        mock_post.return_value = Mock(
            status_code=status.HTTP_404_NOT_FOUND, text=reset_factor_response)

        with self.assertRaises(OktaError):
            response = self.client.reset_factors(user.id)
            self.assertIsNotNone(response)
            self.assertIsInstance(response, User)
Example #5
0
class UsersClientTest(unittest.TestCase):
    def setUp(self):
        self.client = UsersClient(base_url="https://mockta.com",
                                  api_token="abcdefg")

        with open("tests/data/user.json", "r") as file:
            self.user = file.read()

        self.user_json = Utils.deserialize(self.user, User)

        with open("tests/data/users.json", "r") as file:
            self.users = file.read()

        self.users_json = Utils.deserialize(self.users, User)

        with open("tests/data/user_groups.json", "r") as file:
            self.user_groups = file.read()

        self.user_groups_json = Utils.deserialize(self.user_groups, UserGroup)

        with open("tests/data/created_user.json", "r") as file:
            self.created_user = file.read()

        self.created_user_json = Utils.deserialize(self.created_user, User)

    def tearDown(self):
        pass

    @patch("okta.framework.ApiClient.requests.post")
    def test_create_new_user_returns_ok(self, mock_post):
        user = self.created_user_json
        mock_post.return_value = Mock(status_code=status.HTTP_200_OK,
                                      text=self.created_user)
        response = self.client.create_user(user)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)
        #self.assertEqual(response.status, "STAGED")

    @patch("okta.framework.ApiClient.requests.post")
    def test_update_user_partial_update_returns_ok(self, mock_post):
        user = self.created_user_json
        mock_post.return_value = Mock(status_code=status.HTTP_200_OK,
                                      text=self.created_user)
        response = self.client.update_user(user, partial=True)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)
        #self.assertEqual(response.status, "STAGED")

    @patch("okta.framework.ApiClient.requests.put")
    def test_update_user_full_update_returns_ok(self, mock_put):
        user = self.created_user_json
        mock_put.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=self.created_user)
        response = self.client.update_user(user, partial=False)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)
        #self.assertEqual(response.status, "STAGED")

    @patch("okta.framework.ApiClient.requests.delete")
    def test_delete_user_returns_ok(self, mock_delete):
        user_id = self.user_json.id
        mock_delete.return_value = Mock(status_code=status.HTTP_202_ACCEPTED,
                                        text="{}")
        response = self.client.delete_user(user_id)

        self.assertIsNotNone(response)

    @patch("okta.framework.ApiClient.requests.get")
    def test_get_users_returns_ok(self, mock_get):
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=self.users)
        response = self.client.get_users()

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertEqual(len(response), len(self.users_json))
        self.assertIsInstance(response[0], User)

    @patch("okta.framework.ApiClient.requests.get")
    def test_get_user_by_id_returns_ok(self, mock_get):
        user_id = self.user_json.id
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=self.user)
        response = self.client.get_user(user_id)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, User)
        self.assertEqual(response.id, user_id)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_limit_returns_ok(self, mock_get):
        limit = 2
        # is it a valid test to manipulate the return data from a mocked function?
        filtered_users = json.loads(self.users)
        # just get the first 2 users
        filtered_users = filtered_users[0:2]
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(limit=limit)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(len(response), limit)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_query_first_name_returns_ok(self, mock_get):
        # query supports searching by first name, last name and emails
        query = "Gordon"
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(query=query)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(query, response[0].profile.firstName)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_query_last_name_returns_ok(self, mock_get):
        # query supports searching by first name, last name and emails
        query = "Sumner"
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(query=query)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(query, response[0].profile.lastName)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_query_primary_email_returns_ok(self, mock_get):
        # query supports searching by first name, last name and emails
        query = "*****@*****.**"
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(query=query)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(query, response[0].profile.email)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_query_secondary_email_returns_nothing(
            self, mock_get):
        # query supports searching by first name, last name and emails
        query = "*****@*****.**"
        filtered_users = "[]"
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(query=query)

        self.assertIsNotNone(response)
        self.assertEqual(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_filter_by_status_returns_ok(self, mock_get):
        # filter supports a limited set of properties:
        # status, lastUpdated, id, profile.login, profile.email,
        # profile.firstName, and profile.lastName
        filter_string = urllib.parse.quote_plus("status eq \"ACTIVE\"")
        filtered_users = self.users
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(filter_string=filter_string)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        # 5 users in the test data that are active
        self.assertEqual(len(response), 5)
        self.assertIsInstance(response[0], User)
        self.assertEqual(response[0].status, "ACTIVE")

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_filter_by_lastUpdated_returns_ok(self, mock_get):
        # filter supports a limited set of properties:
        # status, lastUpdated, id, profile.login, profile.email,
        # profile.firstName, and profile.lastName
        filter_string = urllib.parse.quote_plus(
            "lastUpdated gt \"2019-12-17T00:00:00.000Z\"")
        filtered_users = self.users
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(filter_string=filter_string)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertEqual(len(response), 5)
        self.assertIsInstance(response[0], User)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_filter_by_id_returns_ok(self, mock_get):
        # filter supports a limited set of properties:
        # status, lastUpdated, id, profile.login, profile.email,
        # profile.firstName, and profile.lastName
        user_id = self.user_json.id
        filter_string = urllib.parse.quote_plus(
            "id eq \"{0}\"".format(user_id))
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(filter_string=filter_string)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(response[0].id, user_id)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_filter_by_login_returns_ok(self, mock_get):
        # filter supports a limited set of properties:
        # status, lastUpdated, id, profile.login, profile.email,
        # profile.firstName, and profile.lastName
        login = "******"
        filter_string = urllib.parse.quote_plus(
            "profile.login eq \"{0}\"".format(login))
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(filter_string=filter_string)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(response[0].profile.login, login)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_filter_by_email_returns_ok(self, mock_get):
        # filter supports a limited set of properties:
        # status, lastUpdated, id, profile.login, profile.email,
        # profile.firstName, and profile.lastName
        email = "*****@*****.**"
        filter_string = urllib.parse.quote_plus(
            "profile.email eq \"{0}\"".format(email))
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(filter_string=filter_string)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(response[0].profile.email, email)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_filter_by_first_name_returns_ok(self, mock_get):
        # filter supports a limited set of properties:
        # status, lastUpdated, id, profile.login, profile.email,
        # profile.firstName, and profile.lastName
        first_name = "Gordon"
        filter_string = urllib.parse.quote_plus(
            "profile.firstName eq \"{0}\"".format(first_name))
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(filter_string=filter_string)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(response[0].profile.firstName, first_name)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_list_users_with_filter_by_last_name_returns_ok(self, mock_get):
        # filter supports a limited set of properties:
        # status, lastUpdated, id, profile.login, profile.email,
        # profile.firstName, and profile.lastName
        last_name = "Sumner"
        filter_string = urllib.parse.quote_plus(
            "profile.lastName eq \"{0}\"".format(last_name))
        filtered_users = json.loads("[{0}]".format(self.user))
        filtered_users = json.dumps(filtered_users)
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=filtered_users)
        response = self.client.get_users(filter_string=filter_string)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], User)
        self.assertEqual(response[0].profile.lastName, last_name)
        self.assertGreater(len(response), 0)

    @patch("okta.framework.ApiClient.requests.get")
    def test_get_user_groups_returns_ok(self, mock_get):
        user_id = self.user_json.id
        mock_get.return_value = Mock(status_code=status.HTTP_200_OK,
                                     text=self.user_groups)
        response = self.client.get_user_groups(user_id)

        self.assertIsNotNone(response)
        self.assertIsInstance(response, list)
        self.assertIsInstance(response[0], UserGroup)
        self.assertEqual(len(response), 3)
 def get_app_links(self, uid):
     response = UsersClient.get_path(self, '/{}/appLinks'.format(uid))
     return Utils.deserialize(response.text, AppLinks)
 def __init__(self, base_url, api_token):
     UsersClient.__init__(self, base_url, api_token)
 def query_user(self, login):
     response = UsersClient.get_path(self, '?q={}'.format(login))
     return Utils.deserialize(response.text, AppLinks)
import json

from okta.UsersClient import UsersClient
from okta.models.user.User import User
from okta.framework.OktaError import OktaError
from okta.framework.Serializer import Serializer
from script_config import base_url, api_token

usersClient = UsersClient(base_url=base_url, api_token=api_token)

print("Search users...")
try:
    # set a low limit to guarantee we get at least 2 pages of results
    users = usersClient.get_paged_users(limit=2)
    pageNo = 1
    while not users.is_last_page():
        print("Page number {0}".format(pageNo))

        for user in users.result:
            print("{0} {1}".format(user.profile.firstName,
                                   user.profile.lastName))

        if not users.is_last_page():
            users = usersClient.get_paged_users(url=users.next_url)
            pageNo = pageNo + 1

except OktaError as e:
    print(e.error_summary)
    print(e.error_causes)

print("get_users with filter...")
Example #10
0
import json
import random

from okta.UsersClient import UsersClient
from okta.models.user.User import User
from okta.framework.OktaError import OktaError
from okta.framework.Serializer import Serializer
from script_config import base_url, api_token

start_number = random.randrange(1, 1000, 1)
end_number = random.randrange(1, 1000, 1)

usersClient = UsersClient(base_url=base_url, api_token=api_token)

user = User(login="******".format(start_number),
            firstName="Test",
            lastName="User {0}".format(start_number),
            middleName="David",
            honorificPrefix="Mr.",
            honorificSuffix="Sr.",
            email="testuser{0}@mailinator.com".format(start_number),
            title="Some sort of job title",
            displayName="Not automated",
            nickName="Testy{0}".format(start_number),
            profileUrl="http://localhost",
            secondEmail="testuser{0}@mailinator.com".format(end_number),
            mobilePhone="9135551212",
            primaryPhone="9135551213",
            streetAddress="123 Main Street",
            city="Anytown",
            state="KS",