Example #1
0
 def login(self, username, password):
     if True:
         params = {
             'AuthFlow': 'USER_PASSWORD_AUTH',
             'AuthParameters': {
                 'USERNAME': username,
                 'PASSWORD': password,
             },
             'ClientId': self.client_id
         }
         try:
             #start_time = time.time()
             response = self.__get_client().initiate_auth(**params)
             #print(time.time()-start_time)
         except Exception as e:
             print(e)
             return (False, None)
         return (self.__get_result(response), response)
     else:
         client = self.__get_client()
         params = {
             'username': username,
             'password': password,
             'pool_id': self.pool_id,
             'client_id': self.client_id,
             'client': client
         }
         try:
             #start_time = time.time()
             aws = AWSSRP(**params)
             response = aws.authenticate_user()
             #print(time.time()-start_time)
         except:
             return (False, None)
         return (self.__get_result(response), response)
    async def _auth(self):
        now = pendulum.now()
        if not self.token or now >= self.expires:
            print(self.expires.to_iso8601_string())
            client = boto3.client('cognito-idp', region_name='us-east-1', config=Config(signature_version="UNSIGNED"))
            aws = AWSSRP(
                username=self.bot.environs.get("STRIDEKICK_USER"),
                password=self.bot.environs.get("STRIDEKICK_PASS"),
                pool_id=self.bot.environs.get("STRIDEKICK_POOL"),
                client_id=self.bot.environs.get("STRIDEKICK_CLNT"),
                client=client,
            )
            tokens = aws.authenticate_user()
            id_token = tokens['AuthenticationResult']['IdToken']
            refresh_token = tokens['AuthenticationResult']['RefreshToken']
            access_token = tokens['AuthenticationResult']['AccessToken']
            token_type = tokens['AuthenticationResult']['TokenType']

            if tokens:
                print("Auth success")

            expires = tokens['AuthenticationResult']['ExpiresIn']
            # print(expires)
            self.token = access_token
            self.expires = now.add(seconds=int(expires))
            # print(now.add(seconds=int(expires)).to_iso8601_string())
            # self.EXPIRES = new_expires
            print(self.expires.to_iso8601_string())
        else:
            return
Example #3
0
    def __init__(self, username, password, token=None, always_test_token=False,
                 ignore_token_check=False, ignore_token_retry=True, autoload_data=True):
        """
        Initialise API.

        :param username: Account E-Mail
        :param password: Account Password
        :param token: AWS Cognito JWT token
        :param always_test_token: Whether the validity of a token should be tested after each request
        :param ignore_token_check: Whether a token should be checked at all (when supplied via the token param)
        :param ignore_token_retry: Whether to stop using the user/pass params if the supplied token is wrong
        :param autoload_data: Whether to automatically load the data on initialization
        """

        self.username = username
        self.password = password
        self.always_test_token = always_test_token
        self.ignore_token_check = ignore_token_check
        self.ignore_token_retry = ignore_token_retry

        self.client = boto3.client('cognito-idp', region_name=self.AWS_REGION,
                                   aws_access_key_id="", aws_secret_access_key="")

        self.aws = AWSSRP(username=self.username, password=self.password,
                          pool_id=self.AWS_POOL_ID,
                          client_id=self.AWS_CLIENT_ID, client=self.client)

        self.token = None
        self.getToken(token=token)

        self.data = None
        if autoload_data:
            self.getData()
Example #4
0
    def __init__(self,
                 username,
                 password,
                 token=None,
                 always_test_token=False):
        self.username = username
        self.password = password
        self.always_test_token = always_test_token

        self.client = boto3.client('cognito-idp',
                                   region_name=self.AWS_REGION,
                                   aws_access_key_id="",
                                   aws_secret_access_key="")

        self.aws = AWSSRP(username=self.username,
                          password=self.password,
                          pool_id=self.AWS_POOL_ID,
                          client_id=self.AWS_CLIENT_ID,
                          client=self.client)

        self.token = None
        self.getToken(token=token)

        self.data = None
        self.getData()
Example #5
0
    def _srp_auth(self):
        srp = AWSSRP(
            username=self.config["username"],
            password=self.config["password"],
            pool_id=self.config["user_pool_id"],
            client_id=self.config["app_id"],
            pool_region=self.config["region_name"],
        )

        AUTH_PARAMETERS = {
            "CHALLENGE_NAME": "SRP_A",
            "USERNAME": self.config["username"],
            "SRP_A": srp.get_auth_params()["SRP_A"],
        }

        auth = self.IDP.initiate_auth(
            AuthFlow="USER_SRP_AUTH",
            AuthParameters=AUTH_PARAMETERS,
            ClientId=self.config["app_id"],
            ClientMetadata=self.config.get("metadata"),
        )

        response = srp.process_challenge(auth["ChallengeParameters"])

        auth = self.IDP.respond_to_auth_challenge(
            ClientId=self.config["app_id"],
            ChallengeName="PASSWORD_VERIFIER",
            ChallengeResponses=response,
        )["AuthenticationResult"]

        return auth
 def _retrieve_tokens(self, user_name, password):
     """
     With the exchange of username and password this function retrieves an identity token.
     :param user_name: user_name as appears in the user pool
     :param password: password as set by the user after passing the password challenge
     :return: a dictionary with identity token and refresh token
     """
     client = boto3.client('cognito-idp')
     try:
         aws_srp = AWSSRP(user_name,
                          password,
                          self.user_pool_id,
                          self.client_id,
                          client=None)
         result = aws_srp.authenticate_user()
         id_token = result['AuthenticationResult']['IdToken']
         refresh_token = result['AuthenticationResult']['RefreshToken']
         return {'id_token': id_token, 'refresh_token': refresh_token}
     except (client.exceptions.NotAuthorizedException,
             client.exceptions.UserNotFoundException):
         raise LoginWithCognitoException(
             'Could not get identity token from Cognito user pool. Are you sure the '
             'user account exists in the Cognito user pool and the password is '
             'valid? Please test your user account by logging into the '
             'monitoring tool. https://www.fd19.sports.intel.com/')
Example #7
0
def authenticate(username, password):
    """
    Be careful about using this function excessively, e.g via tests, as the cognito request may get throttled by IP Address
    """
    if not username:
        raise CognitoAuthError("Empty username", "error.auth.invalid_user")
    if not password:
        raise CognitoAuthError("Empty password", "error.auth.invalid_password")

    client = boto3.client('cognito-idp', region_name=AWS_REGIOM)
    log.info("Authenticating user: {}".format(username))
    cognito = AWSSRP(username=username,
                     password=password,
                     pool_id=cognito_userpool_id,
                     client_id=cognito_app_client_id,
                     client=client)
    try:
        tokens = cognito.authenticate_user()
        return {
            'IdToken': tokens['AuthenticationResult']['IdToken'],
            'AccessToken': tokens['AuthenticationResult']['AccessToken'],
            'ExpiresIn': tokens['AuthenticationResult']['ExpiresIn'],
            'RefreshToken': tokens['AuthenticationResult']['RefreshToken'],
            'TokenType': tokens['AuthenticationResult']['TokenType']
        }
    except client.exceptions.NotAuthorizedException as ex:
        log.info("Failed to authenticate user: {}".format(username))
        raise CognitoAuthError(ex, "error.auth.not_authorized")
    except client.exceptions.UserNotFoundException as ex:
        log.info("Invalid user: {}".format(username))
        raise CognitoAuthError(ex, "error.auth.invalid_user")
    except client.exceptions.UserNotConfirmedException as ex:
        log.info("UserNotConfirmedException: {}".format(username))
        raise CognitoAuthError(ex, "error.auth.unconfirmed_user")
Example #8
0
    def _get_auth_token(self):
        aws = AWSSRP(username=self._username,
                     password=self._password,
                     pool_id=self._cognito_pool_id,
                     client_id=self._client_id,
                     pool_region=self._region_name)

        token = aws.authenticate_user()
        return token['AuthenticationResult']['IdToken']
Example #9
0
    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.aws = AWSSRP(username=self.username, password=self.password,
                          pool_id=self.cognito_user_pool_id,
                          client_id=self.app_id)
Example #10
0
def get_alis_access_token():
    config = configparser.ConfigParser()
    config.read('./alis_connect.ini')
    POOL_ID = 'ap-northeast-1_HNT0fUj4J'
    POOL_REGION = 'ap-northeast-1'
    CLIENT_ID = '2gri5iuukve302i4ghclh6p5rg'
    USERNAME = config.get('DB', 'USERNAME')
    PASSWORD = config.get('DB', 'PASSWORD')
    aws = AWSSRP(username=USERNAME, password=PASSWORD, pool_id=POOL_ID, client_id=CLIENT_ID, pool_region=POOL_REGION)
    id_token = aws.authenticate_user()['AuthenticationResult']['IdToken']
    return id_token
def get_paid_token(username, password):
    session = custom_session.Session(force_tlsv1=False)
    prog_dialog = xbmcgui.DialogProgress()
    prog_dialog.create('Logging in with mobile service')
    prog_dialog.update(1, 'Obtaining user ID from AWS')
    try:
        client = boto3.client('cognito-idp',
                              region_name=config.AWS_REGION,
                              aws_access_key_id='',
                              aws_secret_access_key='')
        aws = AWSSRP(username=username,
                     password=password,
                     pool_id=config.AWS_POOL_ID,
                     client_id=config.AWS_CLIENT_ID,
                     client=client)
    except NameError:
        raise TelstraAuthException('Paid subscriptions not supported on some '
                                   'platforms of Kodi < 18. Please upgrade to '
                                   'Kodi 18 to resolve this.')
    try:
        tokens = aws.authenticate_user().get('AuthenticationResult')
    except Exception as e:
        raise TelstraAuthException(str(e))

    response = client.get_user(AccessToken=tokens.get('AccessToken'))
    userid = response.get('Username')

    prog_dialog.update(33, 'Obtaining oauth token')
    config.OAUTH_DATA.update({'x-user-id': userid})
    oauth_resp = session.post(config.OAUTH_URL, data=config.OAUTH_DATA)
    oauth_json = json.loads(oauth_resp.text)
    access_token = oauth_json.get('access_token')
    session.headers = {}
    session.headers.update(
        {'Authorization': 'Bearer {0}'.format(access_token)})

    prog_dialog.update(66, 'Checking for valid subscription')
    try:
        session.get(config.MEDIA_PURCHASE_URL.format(userid))

    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 404:
            message = json.loads(e.response.text).get('message')
            raise TelstraAuthException(message)
        else:
            utils.log(json.loads(e.response.text).get('exception'))
            raise TelstraAuthException('Unknown error. Please check the log '
                                       'for more information.')
    session.close()
    prog_dialog.update(100, 'Finished!')
    prog_dialog.close()
    return json.dumps({'pai': str(userid), 'bearer': access_token})
    def __init__(self, config, username=None, password=None, logger=None):
        super(AMaaSPasswordSession, self).__init__(logger)
        self.username = username or config.username
        self.password = password or config.password
        self.aws = AWSSRP(
            username=self.username, password=self.password,
            pool_id=config.cognito_pool_id,
            pool_region=config.cognito_region,
            client_id=config.cognito_client_id,
        )

        if self.needs_refresh():
            self.login()
Example #13
0
 def getTokens(self):
     """Authenticates with Cognito. Return Cognito's tokens as a dict.
     result format : {'AccessToken':'str','ExpiresIn':int,'IdToken':'str','RefreshToken':'str','TokenType':'str'}
     See : https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AuthenticationResultType.html"""
     self.aws = AWSSRP(
         username=self.username,
         password=self.password,
         pool_id=self.poolID,
         pool_region=self.poolRegion,
         client_id=self.clientID)  #todo : manage authentification error
     self.cognitoTokens = self.aws.authenticate_user(
     )['AuthenticationResult']
     self.isConnected = True
     return self.cognitoTokens
Example #14
0
 def setUp(self):
     if env('USE_CLIENT_SECRET') == 'True':
         self.client_secret = env('COGNITO_CLIENT_SECRET')
         self.app_id = env('COGNITO_APP_WITH_SECRET_ID')
     else:
         self.app_id = env('COGNITO_APP_ID')
         self.client_secret = None
     self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID')
     self.username = env('COGNITO_TEST_USERNAME')
     self.password = env('COGNITO_TEST_PASSWORD')
     self.aws = AWSSRP(username=self.username,
                       password=self.password,
                       pool_id=self.cognito_user_pool_id,
                       client_id=self.app_id,
                       client_secret=self.client_secret)
def login():
    body = app.current_request.json_body
    aws = AWSSRP(username=body['email'],
                 password=body['password'],
                 pool_id=os.environ['APPUSERPOOLID'],
                 client_id=os.environ['APPCLIENTID'])
    tokens = None
    try:
        if 'newpassword' in body:
            tokens = aws.set_new_password_challenge(body['newpassword'])
        else:
            tokens = aws.authenticate_user()
        return {'token': tokens, 'status': 'loggedin'}
    except ForceChangePasswordException:
        return {"status": "changepwd"}
Example #16
0
class AWSSRPTestCase(unittest.TestCase):
    def setUp(self):
        if env('USE_CLIENT_SECRET') == 'True':
            self.client_secret = env('COGNITO_CLIENT_SECRET')
            self.app_id = env('COGNITO_APP_WITH_SECRET_ID')
        else:
            self.app_id = env('COGNITO_APP_ID')
            self.client_secret = None
        self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID')
        self.username = env('COGNITO_TEST_USERNAME')
        self.password = env('COGNITO_TEST_PASSWORD')
        self.aws = AWSSRP(username=self.username,
                          password=self.password,
                          pool_id=self.cognito_user_pool_id,
                          client_id=self.app_id,
                          client_secret=self.client_secret)

    def tearDown(self):
        del self.aws

    def test_authenticate_user(self):
        tokens = self.aws.authenticate_user()
        self.assertTrue('IdToken' in tokens['AuthenticationResult'])
        self.assertTrue('AccessToken' in tokens['AuthenticationResult'])
        self.assertTrue('RefreshToken' in tokens['AuthenticationResult'])
Example #17
0
 def login(self, username, password):
     client = self.__get_client()
     params = {
         'username': username,
         'password': password,
         'pool_id': self.pool_id,
         'client_id': self.client_id,
         'client': client
     }
     try:
         aws = AWSSRP(**params)
         response = aws.authenticate_user()
         (self.keys, self.keys_iss) = self.__get_userpool_keys()
     except:
         return (False, None)
     return (self.__get_result(response), response)
def login(username, password):

    # Parse configuration
    config = configparser.ConfigParser()
    config.read(['fleet.cfg', os.path.expanduser('~/.fleet.cfg')])
    cognito = config['cognito']

    # Amazon Cognito User Pool - authenticate
    client = boto3.client('cognito-idp')
    aws = AWSSRP(username=username,
                 password=password,
                 pool_id=cognito['pool_id'],
                 client_id=cognito['client_id'],
                 client=client)
    try:
        tokens = aws.authenticate_user()
    except ForceChangePasswordException:
        ntries = 3
        while ntries > 0:
            try:
                ntries -= 1
                new_password = getpass.getpass('Enter new password: '******'ResponseMetadata']['HTTPHeaders'][
                    'x-amzn-errormessage']
                print('\tERROR: {}'.format(errormessage))
        if ntries == 0:
            print('ERROR: Too many attempts to set password')
            return {}
    # TODO: implement PasswordResetRequiredException

    # Amazon Cognito Federated Identities - get credentials
    cognito_id = boto3.client('cognito-identity')
    id_token = tokens['AuthenticationResult']['IdToken']
    response = cognito_id.get_id(IdentityPoolId=cognito['identity_pool_id'],
                                 Logins={cognito['login']: id_token})
    identity_id = response['IdentityId']

    # Amazon Cognito Federated Identities - get credentials
    response = cognito_id.get_credentials_for_identity(
        IdentityId=identity_id, Logins={cognito['login']: id_token})

    return response
Example #19
0
def login_email(username, password):
    customLoginKey = "cognito-idp.us-east-1.amazonaws.com/us-east-1_917Igx5Ld"
    aws = AWSSRP(username=username,
                 password=password,
                 pool_id=userPoolId,
                 client_id=clientId,
                 client=id_provider)
    tokens = aws.authenticate_user(id_provider)["AuthenticationResult"]
    idObj = client.get_id(AccountId=awsAccountId,
                          IdentityPoolId=identityPoolId,
                          Logins={customLoginKey: tokens["IdToken"]})
    result = {
        "IdentityId": idObj["IdentityId"],
        "Logins": {
            customLoginKey: tokens["IdToken"]
        }
    }
    return jsonify(result)
Example #20
0
 def __init__(self, username, password, logger):
     if not AMaaSSession.__shared_state:
         AMaaSSession.__shared_state = self.__dict__
         self.refresh_period = 45 * 60  # minutes * seconds
         self.username = username
         self.password = password
         self.tokens = None
         self.last_authenticated = None
         self.session = requests.Session()
         self.client = boto3.client('cognito-idp', COGNITO_REGION)
         self.aws = AWSSRP(username=self.username,
                           password=self.password,
                           pool_id=COGNITO_POOL,
                           client_id=COGNITO_CLIENT_ID,
                           client=self.client)
         self.logger = logger
     else:
         self.__dict__ = AMaaSSession.__shared_state
     if self.needs_refresh():
         self.login()
Example #21
0
def generate_token(username, password):
    """Generate a Cognito token

    :param str username: username
    :param str password: password
    """

    # Amazon Cognito User Pool - authenticate
    client = boto3.client('cognito-idp', region_name=conf['region'])
    # TODO region could change with user?
    aws = AWSSRP( # AWSSRP -> AWS Secure Remote Password protocol
        username = username,
        password = password,
        pool_id = conf['pool_id'],
        client_id = conf['client_id'],
        client = client
    )
    # get tokens
    tokens = aws.authenticate_user()
    id_token = tokens['AuthenticationResult']['IdToken'] 
    return id_token
Example #22
0
    def cognito_login(username, password, pool_id, client_id, region, account_id, user_pool_id):
        aws = AWSSRP(username=username, password=password, pool_id=user_pool_id, client_id=client_id, pool_region=region)
        tokens = aws.authenticate_user()
        id_token = tokens['AuthenticationResult']['IdToken']
        access_token = tokens['AuthenticationResult']['AccessToken']

        logins = {'cognito-idp.' + region + '.amazonaws.com/' + user_pool_id: id_token}

        client = boto3.client('cognito-identity', region_name=region)
        cognito_identity_id = client.get_id(
            AccountId=str(account_id),
            IdentityPoolId=pool_id,
            Logins=logins
        )

        credentials = client.get_credentials_for_identity(
            IdentityId=cognito_identity_id['IdentityId'],
            Logins=logins
        )
        accesskey = credentials['Credentials']['AccessKeyId']
        secretkey = credentials['Credentials']['SecretKey']
        session_token = credentials['Credentials']['SessionToken']
        service = 'execute-api'
        return AWS4Auth(accesskey, secretkey, region, service, session_token=session_token), session_token, access_token
class AMaaSPasswordSession(AMaaSSession):

    __session_cache = {}

    def __new__(cls,
                environment_config,
                username=None,
                password=None,
                logger=None):
        cache_key = (environment_config, username, password)
        cached = cls.__session_cache.get(cache_key)
        if not cached:
            cached = super(AMaaSPasswordSession, cls).__new__(cls)
            cls.__session_cache[cache_key] = cached

        return cached

    def __init__(self,
                 environment_config,
                 username=None,
                 password=None,
                 logger=None):
        super(AMaaSPasswordSession, self).__init__(logger)
        self.username = username
        self.password = password
        self.aws = AWSSRP(
            username=self.username,
            password=self.password,
            pool_id=environment_config.cognito_pool,
            client_id=environment_config.cognito_client_id,
            pool_region=environment_config.cognito_region,
        )

        if self.needs_refresh():
            self.login()

    def login(self):
        try:
            self.logger.info("Attempting login for: %s", self.username)
            tokens = self.aws.authenticate_user().get('AuthenticationResult')
            self.logger.info("Login successful")
            self.last_authenticated = datetime.utcnow()
            self.session.headers.update(
                {'Authorization': tokens.get('IdToken')})
        except self.aws.client.exceptions.NotAuthorizedException:
            self.logger.exception("Login failed")
            self.last_authenticated = None
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import boto3
from getpass import getpass
from warrant.aws_srp import AWSSRP

from settings import *

# authenticate
cognito_idp = boto3.client('cognito-idp')
username  = input('Email: ')
aws = AWSSRP(
    username  = username,
    password  = getpass('Password: '******'cognito-identity')
logins = {login: tokens['AuthenticationResult']['IdToken']}
identity = cognito_identity.get_id(
    IdentityPoolId=identity_pool_id,
    Logins=logins
)

# get credentials
credentials = cognito_identity.get_credentials_for_identity(
Example #25
0
def connect(envfile_path=None):
    """
    Connects to the MAGE server.  The connection details may be passed in as an argument.  Additional locations checked for the information include: ~/.env and ./.env

    Args:
        envfile_path (str, optional): Location of file that contains the connection parameters.

    Returns:
        bool: True on success, False on failure
    """
    global client_id
    global endpoint

    username = None
    password = None

    home_env = expanduser("~/.env")
    if envfile_path and not os.path.isfile(envfile_path):
        print('[-] Error locating %s' % envfile_path)

    for f in [home_env, '.env', envfile_path]:
        if f and os.path.isfile(f):
            load_dotenv(f)
            username = os.getenv('COGNITO_USERNAME')
            password = os.getenv('COGNITO_PASSWORD')

    gql_url = os.getenv('GQL_URL')
    pool_id = os.getenv('POOL_ID')
    client_id = os.getenv('CLIENT_ID')

    if not all([gql_url, pool_id, client_id]):
        print(
            '[-] You must supply a GQL_URL, POOL_ID, and CLIENT_ID in your environment'
        )
        print("""[!] You can create a .env file with these values at:
    * ./.env
    * in %s
    * the location passed into the connect function""" % home_env)
        return False

    if not username or not password:
        print('[!] Could not load Cognito credentials from .env file')
        username, password = _get_credentials()

    ##########################

    print('[*] Authenticating')
    try:
        u = AWSSRP(username=username,
                   password=password,
                   pool_id=pool_id,
                   client_id=client_id)
    except botocore.exceptions.NoRegionError:
        os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'
        u = AWSSRP(username=username,
                   password=password,
                   pool_id=pool_id,
                   client_id=client_id)

    tokens = u.authenticate_user()
    auth = tokens['AuthenticationResult']['AccessToken']
    headers = {'Authorization': auth, 'Content-Type': 'application/json'}

    endpoint = HTTPEndpoint(gql_url, headers, None)

    print('[*] Retrieving client id')
    client_id = Client.select('id').list()[0].id

    return (client_id is not None and endpoint is not None)
Example #26
0
USERNAME = '******'
PASSWORD = '******'
POOL_ID = 'us-east-1_AgAJAlp74'
CLIENT_ID = '7mic2g4j3tkve6sn2hns91uk91'
POOL_REGION = 'us-east-1'

IDENTITYPOOLID = 'us-east-1:e1a2e785-6445-4a73-8b2c-e4395ec34a09'

# athenticate user using SRP and time it

Mastertic = time.time()
tic = time.time()
aws = AWSSRP(username=USERNAME,
             password=PASSWORD,
             pool_id=POOL_ID,
             client_id=CLIENT_ID,
             pool_region=POOL_REGION)
tokens = aws.authenticate_user()
toc = time.time()
print("time to authenticate the user in pool", toc - tic)

id_token = tokens['AuthenticationResult']['IdToken']
refresh_token = tokens['AuthenticationResult']['RefreshToken']
access_token = tokens['AuthenticationResult']['AccessToken']
token_type = tokens['AuthenticationResult']['TokenType']

print id_token

#federate user and time it
Example #27
0
class FunkAPI:
    API_ENDPOINT = "https://appapi.funk.services/"
    API_KEY = "FZ3OkFFfdMahh4a1xagOnaon39pUpml732kkb2Aw"
    AWS_REGION = "eu-central-1"
    AWS_POOL_ID = "eu-central-1_ZPDpzBJy4"
    AWS_CLIENT_ID = "3asd34f9vfrg6pd2mrbqhn3g3r"

    def __init__(self, username, password, token=None, always_test_token=False):
        self.username = username
        self.password = password
        self.always_test_token = always_test_token

        self.client = boto3.client('cognito-idp', region_name=self.AWS_REGION, aws_access_key_id="",
                                   aws_secret_access_key="")

        self.aws = AWSSRP(username=self.username, password=self.password,
                          pool_id=self.AWS_POOL_ID,
                          client_id=self.AWS_CLIENT_ID, client=self.client)

        self.token = None
        self.getToken(token=token)

        self.data = None
        self.getData()

    # TOKEN
    def getToken(self, refresh=False, token=None):
        if token is not None:
            if self.testToken(token):
                self.token = token
                return self.token
            self.getToken(refresh=True)

        if self.token is None or refresh or (
                False if not self.always_test_token else not self.testToken(self.token)):
            self.token = self.aws.authenticate_user(
            )["AuthenticationResult"]["AccessToken"]
        return self.token

    def testToken(self, token):
        if token is None:
            return False

        json = {"operationName": "CustomerForDashboardQuery", "variables": {},
                "query": "query CustomerForDashboardQuery { me { id } }"}

        req = requests.post(self.API_ENDPOINT, json=json,
                            headers={
                                "x-api-key": self.API_KEY,
                                "Authorization": "Bearer " + token
                            })
        result = req.json()

        if "errors" in result.keys():
            return False
        return True

    # DATA
    def getData(self, refresh=False):
        json = {"operationName": "CustomerForDashboardQuery", "variables": {},
                "query": "query CustomerForDashboardQuery {\n  me {\n    ...CustomerForDashboardFragment\n    __typename\n  }\n}\n\nfragment CustomerForDashboardFragment on Customer {\n  id\n  details {\n    ...DetailsFragment\n    __typename\n  }\n  customerProducts {\n    ...ProductFragment\n    __typename\n  }\n  __typename\n}\n\nfragment DetailsFragment on Details {\n  firstName\n  lastName\n  dateOfBirth\n  contactEmail\n  __typename\n}\n\nfragment ProductFragment on FUNKCustomerProduct {\n  id\n  state\n  paymentMethods {\n    ...PaymentMethodFragment\n    __typename\n  }\n  mobileNumbers {\n    ...MobileNumberFragment\n    __typename\n  }\n  sims {\n    ...SIMFragment\n    __typename\n  }\n  tariffs: tariffCustomerProductServices {\n    ...TariffFragment\n    __typename\n  }\n  __typename\n}\n\nfragment PaymentMethodFragment on PaymentMethod {\n  id\n  state\n  approvalChallenge {\n    approvalURL\n    __typename\n  }\n  agreement {\n    state\n    payerInfo {\n      payerID\n      email\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment MobileNumberFragment on MobileNumberCPS {\n  id\n  number\n  state\n  usage {\n    usedDataPercentage\n    __typename\n  }\n  productServiceId\n  productServiceInfo {\n    id\n    label\n    __typename\n  }\n  ... on MNPImportCustomerProductService {\n    otherProviderShortcut\n    otherProviderCustomName\n    otherContract {\n      contractType\n      mobileNumber\n      mobileNumberIsVerified\n      __typename\n    }\n    mnpInfos {\n      confirmedPortingDate\n      lastPortingResult\n      problemCode\n      problemReason\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment SIMFragment on SIMCustomerProductService {\n  id\n  networkState\n  state\n  iccid\n  delivery {\n    state\n    trackingDetails {\n      stateId\n      stateLabel\n      trackingURL\n      __typename\n    }\n    deliveryProvider\n    address {\n      city\n      additionalInfo\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment TariffFragment on TariffCustomerProductService {\n  id\n  booked\n  starts\n  state\n  productServiceId\n  productServiceInfo {\n    id\n    label\n    follower {\n      id\n      label\n      __typename\n    }\n    marketingInfo {\n      name\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n"}

        if self.data is None or refresh:
            req = requests.post(self.API_ENDPOINT, json=json,
                                headers={
                                    "x-api-key": self.API_KEY,
                                    "Authorization": "Bearer " + self.getToken()
                                })

            self.data = req.json()

        return self.data

    def getPersonalInfo(self, refreshData=False):
        data = self.getData(refresh=refreshData)["data"]["me"]
        personalInfo = {"id": data["id"], **data["details"]}
        del personalInfo["__typename"]
        return personalInfo

    def getOrderedProducts(self, refreshData=False):
        return self.getData(refresh=refreshData)["data"]["me"]["customerProducts"]

    def getCurrentTariff(self, refreshData=False):
        return self.getData(refresh=refreshData)["data"]["me"]["customerProducts"][0]["tariffs"][-1]

    # TARIFFS
    def orderTariff(self, tariffID, productID=None, refreshData=True):
        if productID is None:
            productID = self.getOrderedProducts()[0]["id"]

        json = {"operationName": "AddTariffToProductMutation",
                "variables": {"productID": productID, "tariffID": str(tariffID)},
                "query": "mutation AddTariffToProductMutation($productID: String!, $tariffID: String!) {\n  tariffAddToCustomerProduct(customerProductId: $productID, productServiceId: $tariffID) {\n    ...TariffFragment\n    __typename\n  }\n}\n\nfragment TariffFragment on TariffCustomerProductService {\n  id\n  booked\n  starts\n  state\n  productServiceId\n  productServiceInfo {\n    id\n    label\n    follower {\n      id\n      label\n      __typename\n    }\n    marketingInfo {\n      name\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n"}

        req = requests.post(self.API_ENDPOINT, json=json,
                            headers={
                                "x-api-key": self.API_KEY,
                                "Authorization": "Bearer " + self.getToken()
                            })

        self.getData(refresh=refreshData)

        return req.json()

    def removeProduct(self, personalTariffID, refreshData=True):

        json = {"operationName": "TerminateTariffMutation",
                "variables": {"tariffID": personalTariffID},
                "query": "mutation TerminateTariffMutation($tariffID: String!) {\n  tariffTerminate(customerProductServiceId: $tariffID) {\n    ...TariffFragment\n    __typename\n  }\n}\n\nfragment TariffFragment on TariffCustomerProductService {\n  id\n  booked\n  starts\n  state\n  productServiceId\n  productServiceInfo {\n    id\n    label\n    follower {\n      id\n      label\n      __typename\n    }\n    marketingInfo {\n      name\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n"}

        req = requests.post(self.API_ENDPOINT, json=json,
                            headers={
                                "x-api-key": self.API_KEY,
                                "Authorization": "Bearer " + self.getToken()
                            })

        self.getData(refresh=refreshData)

        return req.json()

    def order1GBTariff(self, **kwargs):
        return self.orderTariff(9, **kwargs)

    def orderUnlimitedTariff(self, **kwargs):
        return self.orderTariff(8, **kwargs)

    def startPause(self, **kwargs):
        return self.orderTariff(42, **kwargs)

    def stopLatestTariff(self, productIndex=0, **kwargs):
        personalTariffID = self.getOrderedProducts(
        )[productIndex]["tariffs"][-1]["id"]
        self.removeProduct(personalTariffID, **kwargs)
Example #28
0
class AWSSRPTestCase(unittest.TestCase):
    def setUp(self):
        if env('USE_CLIENT_SECRET') == 'True':
            self.client_secret = env('COGNITO_CLIENT_SECRET')
            self.app_id = env('COGNITO_APP_WITH_SECRET_ID', 'app')
        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')
        self.password = env('COGNITO_TEST_PASSWORD')
        self.aws = AWSSRP(username=self.username,
                          password=self.password,
                          pool_region='us-east-1',
                          pool_id=self.cognito_user_pool_id,
                          client_id=self.app_id,
                          client_secret=self.client_secret)

    def tearDown(self):
        del self.aws

    @patch('warrant.aws_srp.AWSSRP.get_auth_params', _mock_get_params)
    @patch('warrant.aws_srp.AWSSRP.process_challenge', return_value={})
    def test_authenticate_user(self, _):

        stub = Stubber(self.aws.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={
                              'ChallengeName': 'PASSWORD_VERIFIER',
                              'ChallengeParameters': {}
                          },
                          expected_params={
                              'AuthFlow': 'USER_SRP_AUTH',
                              'AuthParameters': _mock_get_params(None),
                              'ClientId': self.app_id
                          })

        stub.add_response(method='respond_to_auth_challenge',
                          service_response={
                              'AuthenticationResult': {
                                  'IdToken': 'dummy_token',
                                  'AccessToken': 'dummy_token',
                                  'RefreshToken': 'dummy_token'
                              }
                          },
                          expected_params={
                              'ClientId': self.app_id,
                              'ChallengeName': 'PASSWORD_VERIFIER',
                              'ChallengeResponses': {}
                          })

        with stub:
            tokens = self.aws.authenticate_user()
            self.assertTrue('IdToken' in tokens['AuthenticationResult'])
            self.assertTrue('AccessToken' in tokens['AuthenticationResult'])
            self.assertTrue('RefreshToken' in tokens['AuthenticationResult'])
            stub.assert_no_pending_responses()
Example #29
0
class AMaaSSession(object):

    __shared_state = {}

    def __init__(self, username, password, logger):
        if not AMaaSSession.__shared_state:
            AMaaSSession.__shared_state = self.__dict__
            self.refresh_period = 45 * 60  # minutes * seconds
            self.username = username
            self.password = password
            self.tokens = None
            self.last_authenticated = None
            self.session = requests.Session()
            self.client = boto3.client('cognito-idp', COGNITO_REGION)
            self.aws = AWSSRP(username=self.username,
                              password=self.password,
                              pool_id=COGNITO_POOL,
                              client_id=COGNITO_CLIENT_ID,
                              client=self.client)
            self.logger = logger
        else:
            self.__dict__ = AMaaSSession.__shared_state
        if self.needs_refresh():
            self.login()

    def needs_refresh(self):
        if not (self.last_authenticated and
                (datetime.utcnow() - self.last_authenticated).seconds <
                self.refresh_period):
            return True
        else:
            return False

    def login(self):
        self.logger.info("Attempting login for: %s", self.username)
        try:
            self.tokens = self.aws.authenticate_user().get(
                'AuthenticationResult')
            self.logger.info("Login successful")
            self.last_authenticated = datetime.utcnow()
            self.session.headers.update(
                {'Authorization': self.tokens.get('IdToken')})
        except self.client.exceptions.NotAuthorizedException as e:
            self.logger.info("Login failed")
            self.logger.error(e.response.get('Error'))
            self.last_authenticated = None

    def put(self, url, data=None, **kwargs):
        # Add a refresh
        if self.last_authenticated and not self.needs_refresh():
            return self.session.put(url=url, data=data, **kwargs)
        else:
            raise AMaaSException('Not Authenticated')

    def post(self, url, data=None, **kwargs):
        # Add a refresh
        if self.last_authenticated and not self.needs_refresh():
            return self.session.post(url=url, data=data, **kwargs)
        else:
            raise AMaaSException('Not Authenticated')

    def delete(self, url, **kwargs):
        # Add a refresh
        if self.last_authenticated and not self.needs_refresh():
            return self.session.delete(url=url, **kwargs)
        else:
            raise AMaaSException('Not Authenticated')

    def get(self, url, **kwargs):
        # Add a refresh
        if self.last_authenticated and not self.needs_refresh():
            return self.session.get(url=url, **kwargs)
        else:
            raise AMaaSException('Not Authenticated')

    def patch(self, url, data=None, **kwargs):
        # Add a refresh
        if self.last_authenticated and not self.needs_refresh():
            return self.session.patch(url=url, data=data, **kwargs)
        else:
            raise AMaaSException('Not Authenticated')
Example #30
0
 def __auth(self, user, pwd):
     aws = AWSSRP(username=user, password=pwd, pool_id=self.POOL_ID, client_id=self.CLIENT_ID, pool_region=self.POOL_REGION)
     id_token = aws.authenticate_user()['AuthenticationResult']['IdToken']
     self.headers = {'Authorization': id_token}