def lambda_handler(event, context): print("Got event \n" + json.dumps(event, indent=2)) p_body = parse_qs(event['body']) #print str(p_body['user'][0]) #print str(p_body['tenant_id'][0]) #print str(p_body['user_id'][0]) #print p_body['email_addr'][0] print event cognito = boto3.client('cognito-idp', region_name='us-east-2') if p_body['user'] != None: user = p_body['user'][0] email_add = p_body['email_addr'][0] t_id = p_body['tenant_id'][0] u_id = p_body['user_id'][0] passwd = gen_random_string(8) passwd = passwd + "!!" + str(random.randint(0, 100)) print passwd u = Cognito(USER_POOL_ID, CLIENT_ID) u.add_base_attributes(email=email_add) u.add_custom_attributes(tenantId=t_id, userId=u_id, lib_view='*') u.register(user, passwd) response = cognito.admin_confirm_sign_up(UserPoolId=USER_POOL_ID, Username=user) u = Cognito(USER_POOL_ID, CLIENT_ID, username=user) u.admin_authenticate(password=passwd) print "getting refresh token" return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json' }, 'body': json.dumps({'refresh_token': u.refresh_token}) } else: return { 'statusCode': 403, 'headers': { 'Content-Type': 'application/json' }, 'body': json.dumps({'message': 'invalid user input'}) }
def authenticate_new_user(userPoolId,appClientId, username, password, region ): u = Cognito(userPoolId, appClientId, username = username,user_pool_region=region) authenticateUser = u.admin_authenticate(password) return authenticateUser
def sign_in(): if request and request.method == "GET": resp, err = GetUserPasswordFromAuthHeader(request) if err: log.error(err) res = GetResponseObject(err, 400) return res username, password = resp[0], resp[1] try: user = Cognito(user_pool_id=COGNITO_USER_POOL_ID, \ client_id=COGNITO_APP_CLIENT_ID, \ user_pool_region=AWS_REGION, \ username=username) user.admin_authenticate(password=password) user_rec = user.get_user() uid = user_rec.sub usertype = user_rec._data['custom:usertype'] userObj = Users.get(uid) # userObj = Users.get(uid, usertype) out = SerializeUserObj(userObj) # out["usertype"] = usertype data = { # "idToken": user.id_token, "accessToken": user.access_token, # "refreshToken": user.refresh_token, "profile": out } res = GetResponseObject(data, 200, True) res.headers['HMS-TOKEN'] = "Bearer " + user.access_token # res.set_cookie(settings.COOKIE_NAME , user.access_token) return res except Exception as e: msg = f"Error while authenticating user {str(e)}" return GetResponseObject(msg) # return HttpResponseServerError(res) else: data = f"Invalid request method, method {request.method} not supported !!!" return GetResponseObject(data, 405)
class CognitoAuthTestCase(unittest.TestCase): def setUp(self): self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID') self.app_id = env('COGNITO_APP_ID') self.username = env('COGNITO_TEST_USERNAME') self.password = env('COGNITO_TEST_PASSWORD') self.user = Cognito(self.cognito_user_pool_id, self.app_id, username=self.username) 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) def test_verify_token(self): self.user.authenticate(self.password) bad_access_token = '{}wrong'.format(self.user.access_token) with self.assertRaises(TokenVerificationException) as vm: self.user.verify_token(bad_access_token, 'access_token', 'access') # def test_logout(self): # self.user.authenticate(self.password) # self.user.logout() # self.assertEqual(self.user.id_token,None) # self.assertEqual(self.user.refresh_token,None) # self.assertEqual(self.user.access_token,None) @patch('warrant.Cognito', autospec=True) def test_register(self, cognito_user): u = cognito_user(self.cognito_user_pool_id, self.app_id, username=self.username) res = u.register('sampleuser', 'sample4#Password', given_name='Brian', family_name='Jones', name='Brian Jones', email='*****@*****.**', phone_number='+19194894555', gender='Male', preferred_username='******') # TODO: Write assumptions def test_renew_tokens(self): self.user.authenticate(self.password) self.user.renew_access_token() @patch('warrant.Cognito', autospec=True) def test_update_profile(self, cognito_user): u = cognito_user(self.cognito_user_pool_id, self.app_id, username=self.username) u.authenticate(self.password) u.update_profile({'given_name': 'Jenkins'}) def test_admin_get_user(self): u = self.user.admin_get_user() self.assertEqual(u.pk, self.username) def test_check_token(self): self.user.authenticate(self.password) self.assertFalse(self.user.check_token()) @patch('warrant.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('warrant.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) as vm: u.confirm_forgot_password(self.password) @patch('warrant.Cognito', autospec=True) def test_change_password(self, cognito_user): u = cognito_user(self.cognito_user_pool_id, self.app_id, username=self.username) u.authenticate(self.password) u.change_password(self.password, 'crazypassword$45DOG') with self.assertRaises(TypeError) as vm: self.user.change_password(self.password) def test_set_attributes(self): u = Cognito(self.cognito_user_pool_id, self.app_id) u._set_attributes({'ResponseMetadata': { 'HTTPStatusCode': 200 }}, {'somerandom': 'attribute'}) self.assertEqual(u.somerandom, 'attribute') def test_admin_authenticate(self): 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)
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('warrant.aws_srp.AWSSRP.authenticate_user', _mock_authenticate_user) @patch('warrant.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('warrant.aws_srp.AWSSRP.authenticate_user', _mock_authenticate_user) @patch('warrant.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') # def test_logout(self): # self.user.authenticate(self.password) # self.user.logout() # self.assertEqual(self.user.id_token,None) # self.assertEqual(self.user.refresh_token,None) # self.assertEqual(self.user.access_token,None) @patch('warrant.Cognito', autospec=True) def test_register(self, cognito_user): u = cognito_user(self.cognito_user_pool_id, self.app_id, username=self.username) u.add_base_attributes(given_name='Brian', family_name='Jones', name='Brian Jones', email='*****@*****.**', phone_number='+19194894555', gender='Male', preferred_username='******') u.register('sampleuser', 'sample4#Password') # TODO: Write assumptions @patch('warrant.aws_srp.AWSSRP.authenticate_user', _mock_authenticate_user) @patch('warrant.Cognito.verify_token', _mock_verify_tokens) @patch('warrant.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', 'AuthParameters': { 'REFRESH_TOKEN': 'dummy_token' } }) with stub: self.user.authenticate(self.password) self.user.renew_access_token() stub.assert_no_pending_responses() @patch('warrant.Cognito', autospec=True) def test_update_profile(self, cognito_user): u = cognito_user(self.cognito_user_pool_id, self.app_id, username=self.username) u.authenticate(self.password) u.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.pk, 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('warrant.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('warrant.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('warrant.aws_srp.AWSSRP.authenticate_user', _mock_authenticate_user) @patch('warrant.Cognito.verify_token', _mock_verify_tokens) @patch('warrant.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): u = Cognito(self.cognito_user_pool_id, self.app_id) u._set_attributes({'ResponseMetadata': { 'HTTPStatusCode': 200 }}, {'somerandom': 'attribute'}) self.assertEqual(u.somerandom, 'attribute') # @patch('warrant.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()