def get_user_info(self, password): self.log.info("Getting user info for username = "******"given_name": "first_name", "middle_name": "middle_name", "family_name": "last_name", "email": "email", "phone_number": "phone_number" }) except Exception as e: print(str(e.with_traceback())) return user
def change_password(user_change_password: ChangePassword, token: str = Depends(verify_auth_header)): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID'], access_token=token) aws_cognito.change_password(user_change_password.old_password, user_change_password.new_password)
def register_provider(provider: RegisterProvider, database: BlockchainDb = Depends()): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID']) aws_cognito.username = provider.username aws_cognito.set_base_attributes(email=provider.username, name=f'{provider.name.firstName}') aws_cognito.add_custom_attributes(usertype='provider') response = aws_cognito.register(provider.username, provider.password) for providable_treatment in provider.providableTreatments: providable_treatment.providableTreatmentId = uuid.uuid4() for address in provider.addresses: address.addressId = uuid.uuid4() try: database.commit_transaction( Provider( providerId=response['UserSub'], name=provider.name, phoneNumbers=provider.phoneNumbers, addresses=provider.addresses, dateOfBirth=provider.dateOfBirth, email=provider.email, providableTreatments=provider.providableTreatments).dict(), 'CREATE', 'Provider', 'providerId', response['UserSub']) return response['UserSub'] except: aws_cognito.delete_user() return status.HTTP_400_BAD_REQUEST
def authenticate(user_name, password): try: u = Cognito(user_pool_id, client_id, username=user_name) u.authenticate(password=password) print("Logged in successfully!") return True except Exception as e: print(e) return False
def __init__(self, user_pool_id, client_id, client_secret, username): self.user_pool_id = user_pool_id self.client_id = client_id self.client_secret = client_secret self.username = username self.cognito = Cognito(user_pool_id, client_id, client_secret=client_secret, username=username) self.log = Helper.get_logger()
def confirm(user_name, code, registration_frame): try: u = Cognito(user_pool_id, client_id) u.confirm_sign_up(code, username=user_name) print("Your Email was confirmed!") Label(registration_frame, text="Your Email was confirmed!").grid(row=8, column=0, columnspan=2) except Exception as e: print(e) return False
async def verify_auth_header(authorization: HTTPBasicCredentials = Depends(auth)): """ Verifies the credentials sent in the authorisation header with cognito """ try: aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID'], access_token=authorization.credentials) if aws_cognito.get_user() is None: raise HTTPException(status_code=403) return authorization.credentials except Exception as forbidden: raise HTTPException(status_code=403) from forbidden
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
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, )
def setUp(self): if env("USE_CLIENT_SECRET", "False") == "True": self.app_id = env("COGNITO_APP_WITH_SECRET_ID") else: self.app_id = env("COGNITO_APP_ID") self.cognito_user_pool_id = env("COGNITO_USER_POOL_ID", "us-east-1_123456789") self.username = env("COGNITO_TEST_USERNAME") self.user = Cognito( user_pool_id=self.cognito_user_pool_id, client_id=self.app_id, username=self.username, ) self.user_metadata = { "user_status": "CONFIRMED", "username": "******", } self.user_info = [ { "Name": "name", "Value": "Brian Jones" }, { "Name": "given_name", "Value": "Brian" }, { "Name": "birthdate", "Value": "12/7/1980" }, ]
def forgot_password(user_forgot_password: ForgotPassword): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID']) aws_cognito.username = user_forgot_password.username aws_cognito.add_custom_attributes(email=user_forgot_password.username) aws_cognito.initiate_forgot_password()
def setUp(self): if env("USE_CLIENT_SECRET", "False") == "True": self.app_id = env("COGNITO_APP_WITH_SECRET_ID") else: self.app_id = env("COGNITO_APP_ID") self.cognito_user_pool_id = env("COGNITO_USER_POOL_ID", "us-east-1_123456789") self.group_data = {"GroupName": "test_group", "Precedence": 1} self.cognito_obj = Cognito( user_pool_id=self.cognito_user_pool_id, client_id=self.app_id )
def _client_from_env(**kwargs) -> Cognito: """ Constructs cognito client from required environment variables and any other given attributes :param kwargs: Any configuration attributes for cognito client instance :return: """ user_pool_id = pyocle.config.env_var('USER_POOL_ID') client_id = pyocle.config.encrypted_env_var('APP_CLIENT_ID') return Cognito(user_pool_id=user_pool_id, client_id=client_id, **kwargs)
async def get_tokens(username: str, password: str): # Get keys from AWS async key_dict_future = get_key_dict() # Meanwhile, authenticate with User Pool access_kwargs = { 'username': username, 'access_key': aws_access_key_id, 'secret_key': aws_secret_access_key } if client_secret: access_kwargs['client_secret'] = client_secret user = Cognito(pool_id, client_id, **access_kwargs) user.authenticate(password=password) # Await key response key_dict_response = await key_dict_future key_dict = key_dict_response.json() # Extract tokens and metadata groups = user.get_groups() region = user.user_pool_region id_token = user.id_token access_token = user.access_token refresh_token = user.refresh_token logins = {f"cognito-idp.{region}.amazonaws.com/{pool_id}": id_token} # Decode tokens id = decode_jwt(id_token, key_dict, client_id) access = decode_jwt(access_token, key_dict, client_id) # Fetch credentials from Identity Pool credentials = get_credentials(logins) return { "id": id, "access": access, "id_token": id_token, "access_token": access_token, "refresh_token": refresh_token, "credentials": credentials, }
def authenticate(appclientid, username, userpoolid, password): """ Authenticate a user and return id_token, refresh_token, access_token. :param appclientid: Userpool applcation client ID :param username: Cognito user login :param userpoolid: Userpool ID :param password: Cognito user password :return: id_token, refresh_token, access_token """ user = Cognito(userpoolid, appclientid, username=username) user.authenticate(password=password) data = { "access_token": user.access_token, "id_token": user.id_token, "refresh_token": user.refresh_token, } print(data) print("Written to tmp_token.json") with open("tmp_token.json", "w") as f: json.dump(data, f, indent=2)
def authenticate_user(username, password): try: u = Cognito(client_id=client_id, user_pool_id=user_pool_id, username=username, user_pool_region='eu-west-1') u.authenticate(password=password) user = u.get_user(attr_map={"user_id": "sub"}) user_id = user.sub except Exception as e: print("Incorrect username or password, please try again" + str(e)) return False user_data = { 'user_id': user_id, "username": username, "password": password } User.get_instance(user_data) # instantiate singleton object return True
def confirm_forgot_password( user_confirm_forgot_password: ConfirmForgotPassword): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID']) aws_cognito.username = user_confirm_forgot_password.username aws_cognito.add_custom_attributes( email=user_confirm_forgot_password.username) aws_cognito.confirm_forgot_password( user_confirm_forgot_password.verification_code, user_confirm_forgot_password.new_password)
def register(user_name, password, email, registration_frame): try: u = Cognito(user_pool_id, client_id) u.set_base_attributes(email=email) u.register(user_name, password) print("New user created successfully!") Label(registration_frame, text="New user created successfully!").grid(row=5, column=0, columnspan=2) except Exception as e: print(e) return False
def register_client(client: RegisterClient, database: BlockchainDb = Depends()): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID']) aws_cognito.username = client.username aws_cognito.set_base_attributes(email=client.username, name=f'{client.name.firstName}') aws_cognito.add_custom_attributes(usertype='client') response = aws_cognito.register(client.username, client.password) client.address.addressId = uuid.uuid4() database.commit_transaction( Client(clientId=response['UserSub'], name=client.name, phoneNumbers=client.phoneNumbers, address=client.address, dateOfBirth=client.dateOfBirth, email=client.email).dict(), 'CREATE', 'Client', 'clientId', response['UserSub']) return response['UserSub']
def sign_in(user_sign_in: SignIn): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID']) aws_cognito.username = user_sign_in.username aws_cognito.authenticate(password=user_sign_in.password) user = aws_cognito.get_user(attr_map={ "usertype": "custom:usertype", "user_id": "sub" }) usertype = user._data["custom:usertype"] user_id = user.sub resp = { "user": User(userId=user_id, username=user.username, usertype=usertype), "token": Token(**aws_cognito.__dict__) } return SignInResponse(**resp)
def get_queryset(self): return Cognito( settings.COGNITO_USER_POOL_ID, settings.COGNITO_APP_ID ).get_users(attr_map=settings.COGNITO_ATTR_MAPPING)
def get_user_object(self): return Cognito( settings.COGNITO_USER_POOL_ID, settings.COGNITO_APP_ID, username=self.kwargs.get("username"), ).admin_get_user(attr_map=settings.COGNITO_ATTR_MAPPING)
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")
def sign_out(token: str = Depends(verify_auth_header)): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID'], access_token=token) aws_cognito.logout()
def confirm_registration(confirm_sign_up: ConfirmSignUp): aws_cognito = Cognito(os.environ['USER_POOL_ID'], os.environ['USER_POOL_WEB_CLIENT_ID']) aws_cognito.confirm_sign_up(confirm_sign_up.verificationCode, username=confirm_sign_up.username)
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()
class CognitoUser: def __init__(self, user_pool_id, client_id, client_secret, username): self.user_pool_id = user_pool_id self.client_id = client_id self.client_secret = client_secret self.username = username self.cognito = Cognito(user_pool_id, client_id, client_secret=client_secret, username=username) self.log = Helper.get_logger() # this method allows the registration of a user in AWS cognito def register_user(self, password, email, first_name, middle_name, last_name, phone_number): is_registered = False self.log.info("registering user with username " + self.username) try: self.cognito.set_base_attributes(email=email, given_name=first_name, middle_name=middle_name, family_name=last_name, phone_number=phone_number) self.cognito.register(username=self.username, password=password) is_registered = True self.log.info("username " + self.username + " registered successfully") except Exception as e: if "UsernameExistException" in str(e): self.log.error( "Username already exist, please user another username") else: self.log.error(str(e)) return is_registered # This method allows for the user to confirm registration def confirm_signup(self, confirmation_code): signup_confirmed = False self.log.info("confirming user="******" with registration code " + confirmation_code) try: self.cognito.confirm_sign_up(confirmation_code, username=self.username) signup_confirmed = True self.log.info("user = "******" has been confirmed ") except Exception as e: self.log.error(str(e)) return signup_confirmed # This method allows a user to be authenticated with AWS cognito authentication def authenticate_user(self, password): is_authenticated = False self.log.info("Authenticating user = "******"user = "******" has been authenticated") except Exception as e: self.log.error(str(e)) return is_authenticated # this method returns all the personal information of a given username def get_user_info(self, password): self.log.info("Getting user info for username = "******"given_name": "first_name", "middle_name": "middle_name", "family_name": "last_name", "email": "email", "phone_number": "phone_number" }) except Exception as e: print(str(e.with_traceback())) return user
import graphene import requests from fastapi import FastAPI from starlette.graphql import GraphQLApp from pydantic import BaseModel from fastapi.security import PA from pycognito import Cognito u = Cognito("eu-west-1_evU2XlBPg", "5p05ojqacsr782fouu3nv0hm1r", client_secret="password1234", username="******") from gateway.auth import get_jwks, JWTBearer, jwks class User(BaseModel): username: str email: str disabled: bool class RoomType(graphene.ObjectType): id = graphene.Int() capacity = graphene.Int() faculty = graphene.String() projector = graphene.Boolean() booked = graphene.Boolean() class RoomBookingType(graphene.ObjectType):
from pycognito import Cognito import pprint import env pp = pprint.PrettyPrinter(indent=4) u = Cognito(env.USER_POOL_ID, env.CLIENT_ID, client_secret=env.CLIENT_SECRET, access_key=env.ACCESS_ID, secret_key=env.ACCESS_KEY) users = u.get_users(attr_map={ "mail": "email", "given_name": "first_name", "family_name": "last_name" }) for user in users: print('{}'.format(user.email))