def get_cognito(request): c = Cognito( settings.COGNITO_USER_POOL_ID, settings.COGNITO_APP_ID, access_token=request.session.get("ACCESS_TOKEN"), id_token=request.session.get("ID_TOKEN"), refresh_token=request.session.get("REFRESH_TOKEN"), ) changed = c.check_token() if changed: request.session["ACCESS_TOKEN"] = c.access_token request.session["REFRESH_TOKEN"] = c.refresh_token request.session["ID_TOKEN"] = c.id_token request.session.save() return c
class CognitoAuthTestCase(unittest.TestCase): def setUp(self): if env("USE_CLIENT_SECRET") == "True": self.app_id = env("COGNITO_APP_WITH_SECRET_ID", "app") self.client_secret = env("COGNITO_CLIENT_SECRET") else: self.app_id = env("COGNITO_APP_ID", "app") self.client_secret = None self.cognito_user_pool_id = env("COGNITO_USER_POOL_ID", "us-east-1_123456789") self.username = env("COGNITO_TEST_USERNAME", "bob") self.password = env("COGNITO_TEST_PASSWORD", "bobpassword") self.user = Cognito( self.cognito_user_pool_id, self.app_id, username=self.username, client_secret=self.client_secret, ) @patch("pycognito.aws_srp.AWSSRP.authenticate_user", _mock_authenticate_user) @patch("pycognito.Cognito.verify_token", _mock_verify_tokens) def test_authenticate(self): self.user.authenticate(self.password) self.assertNotEqual(self.user.access_token, None) self.assertNotEqual(self.user.id_token, None) self.assertNotEqual(self.user.refresh_token, None) @patch("pycognito.aws_srp.AWSSRP.authenticate_user", _mock_authenticate_user) @patch("pycognito.Cognito.verify_token", _mock_verify_tokens) def test_verify_token(self): self.user.authenticate(self.password) bad_access_token = "{}wrong".format(self.user.access_token) with self.assertRaises(TokenVerificationException): self.user.verify_token(bad_access_token, "access_token", "access") @patch("pycognito.Cognito", autospec=True) def test_register(self, cognito_user): user = cognito_user( self.cognito_user_pool_id, self.app_id, username=self.username ) base_attr = dict( given_name="Brian", family_name="Jones", name="Brian Jones", email="*****@*****.**", phone_number="+19194894555", gender="Male", preferred_username="******", ) user.set_base_attributes(**base_attr) user.register("sampleuser", "sample4#Password") @patch("pycognito.aws_srp.AWSSRP.authenticate_user", _mock_authenticate_user) @patch("pycognito.Cognito.verify_token", _mock_verify_tokens) @patch("pycognito.Cognito._add_secret_hash", return_value=None) def test_renew_tokens(self, _): stub = Stubber(self.user.client) # By the stubber nature, we need to add the sequence # of calls for the AWS SRP auth to test the whole process stub.add_response( method="initiate_auth", service_response={ "AuthenticationResult": { "TokenType": "admin", "IdToken": "dummy_token", "AccessToken": "dummy_token", "RefreshToken": "dummy_token", }, "ResponseMetadata": {"HTTPStatusCode": 200}, }, expected_params={ "ClientId": self.app_id, "AuthFlow": "REFRESH_TOKEN_AUTH", "AuthParameters": {"REFRESH_TOKEN": "dummy_token"}, }, ) with stub: self.user.authenticate(self.password) self.user.renew_access_token() stub.assert_no_pending_responses() @patch("pycognito.Cognito", autospec=True) def test_update_profile(self, cognito_user): user = cognito_user( self.cognito_user_pool_id, self.app_id, username=self.username ) user.authenticate(self.password) user.update_profile({"given_name": "Jenkins"}) def test_admin_get_user(self): stub = Stubber(self.user.client) stub.add_response( method="admin_get_user", service_response={ "Enabled": True, "UserStatus": "CONFIRMED", "Username": self.username, "UserAttributes": [], }, expected_params={ "UserPoolId": self.cognito_user_pool_id, "Username": self.username, }, ) with stub: u = self.user.admin_get_user() self.assertEqual(u.username, self.username) stub.assert_no_pending_responses() def test_check_token(self): # This is a sample JWT with an expiration time set to January, 1st, 3000 self.user.access_token = ( "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG" "9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjMyNTAzNjgwMDAwfQ.C-1gPxrhUsiWeCvMvaZuuQYarkDNAc" "pEGJPIqu_SrKQ" ) self.assertFalse(self.user.check_token()) @patch("pycognito.Cognito", autospec=True) def test_validate_verification(self, cognito_user): u = cognito_user(self.cognito_user_pool_id, self.app_id, username=self.username) u.validate_verification("4321") @patch("pycognito.Cognito", autospec=True) def test_confirm_forgot_password(self, cognito_user): u = cognito_user(self.cognito_user_pool_id, self.app_id, username=self.username) u.confirm_forgot_password("4553", "samplepassword") with self.assertRaises(TypeError): u.confirm_forgot_password(self.password) @patch("pycognito.aws_srp.AWSSRP.authenticate_user", _mock_authenticate_user) @patch("pycognito.Cognito.verify_token", _mock_verify_tokens) @patch("pycognito.Cognito.check_token", return_value=True) def test_change_password(self, _): # u = cognito_user(self.cognito_user_pool_id, self.app_id, # username=self.username) self.user.authenticate(self.password) stub = Stubber(self.user.client) stub.add_response( method="change_password", service_response={"ResponseMetadata": {"HTTPStatusCode": 200}}, expected_params={ "PreviousPassword": self.password, "ProposedPassword": "******", "AccessToken": self.user.access_token, }, ) with stub: self.user.change_password(self.password, "crazypassword$45DOG") stub.assert_no_pending_responses() with self.assertRaises(ParamValidationError): self.user.change_password(self.password, None) def test_set_attributes(self): user = Cognito(self.cognito_user_pool_id, self.app_id) user._set_attributes( {"ResponseMetadata": {"HTTPStatusCode": 200}}, {"somerandom": "attribute"} ) self.assertEqual(user.somerandom, "attribute") @patch("pycognito.Cognito.verify_token", _mock_verify_tokens) def test_admin_authenticate(self): stub = Stubber(self.user.client) # By the stubber nature, we need to add the sequence # of calls for the AWS SRP auth to test the whole process stub.add_response( method="admin_initiate_auth", service_response={ "AuthenticationResult": { "TokenType": "admin", "IdToken": "dummy_token", "AccessToken": "dummy_token", "RefreshToken": "dummy_token", } }, expected_params={ "UserPoolId": self.cognito_user_pool_id, "ClientId": self.app_id, "AuthFlow": "ADMIN_NO_SRP_AUTH", "AuthParameters": { "USERNAME": self.username, "PASSWORD": self.password, }, }, ) with stub: self.user.admin_authenticate(self.password) self.assertNotEqual(self.user.access_token, None) self.assertNotEqual(self.user.id_token, None) self.assertNotEqual(self.user.refresh_token, None) stub.assert_no_pending_responses()