Exemplo n.º 1
0
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
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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,
    }
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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
Exemplo n.º 7
0
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()