Exemple #1
0
    def post(self):

        headers = {'Content-Type': 'text/html'}
        token = request.args.get('id_token')

        if token:
            return respondToToken(token)
        else:
            if request.form:
                user = request.form['username']
                pwd = request.form['pwd']
                u = Cognito(COGNITO_USER_POOL,COGNITO_APP_ID, username=user)
                print "No Token, Trying to login for user %s" %(user)
                try:
                    u.authenticate(password=pwd)
                except:
                    return make_response(
                          render_template('TokenError.html',
                                      msg="Login Failed. Access Denied"
                                    ),404,headers)
                try:
                    resp =  respondToToken(u.id_token)

                    return resp
                except:

                    return make_response(
                          render_template('TokenError.html',
                                      msg="Something very bad happend!! Can Not Open Homepage!!"
                                    ),404,headers)
Exemple #2
0
def homePage():
    if request.method == 'POST':
        #Gather username and password from form
        username = request.form['username']
        password = request.form['password']
        
        #Authenticate user login info
        u = Cognito(pool_id, client_id, username)
        try:
            u.authenticate(password)
            return redirect('/folders')
        except ForceChangePasswordException:
            #new_password = request.form['new_password']
            #u.change_password(password, new_password)
            u.change_password(password, 'Test@12345')
            return redirect('/folders')
            
        #aws = AWSSRP(username=username, password=password, pool_id=pool_id,
        #          client_id=client_id, client=auth_client)
        #tokens = aws.authenticate_user()

        #If user login info authenticated, return buckets page
        #if tokens:
        #    return redirect('/folders')
        #else:
        #    flash('Unable to authenticate user login information.')
        #    return redirect('/')
    else:
        return render_template('index.html')
Exemple #3
0
def login(username, password):
    """
    Use username and password to get Canotic api key.
    """
    user = Cognito(access_key='AKIAIOSFODNN7EXAMPLE', secret_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
                   user_pool_id=COGNITO_USERPOOL_ID, client_id=COGNITO_CLIENT_ID,
                   user_pool_region=COGNITO_REGION, username=username)
    try:
        user.authenticate(password)
    except ClientError as e:
        if e.response['Error']['Code'] == 'UserNotFoundException' or e.response['Error'][
            'Code'] == 'NotAuthorizedException':
            print("Incorrect username or password")
            return
        else:
            print(f"Unexpected error: {e}")
            return

    client = Client(auth_token=user.access_token)
    api_keys = client.get_apikeys()
    if len(api_keys) > 0:
        save_api_key(api_keys[0])
        print(f'Api key {api_keys[0]} was set')
    else:
        print(f'User {username} doesn\'t have any api keys')
Exemple #4
0
def login():

	loadMe = json.dumps(request.get_json(silent=True)["user"])
	payInfo = json.loads(loadMe)
	try:

		u = Cognito(pool_id, client_id, user_pool_region='us-east-2',
                    access_key=os.environ["AWS_ACCESS_KEY"], secret_key=os.environ['AWS_SECRET_KEY'],
                    username=payInfo["email"]);
		u.authenticate(password=payInfo["password"]);
		uuid = generate_uuid(payInfo)
		response = table.get_item(
			Key={
				'userID' : uuid
			}
		)
		item = response['Item'];
		# return jsonify(item);
		convertedItem = json.loads(json.dumps(item, default=decimal_default));
		adminStatus = convertedItem['admin'];
		wholeTable = getTable();
		if (adminStatus == 1):
			return response_with(responses.SUCCESS_200, value={"value" : wholeTable}, message={"userID" : uuid, "admin" : adminStatus});
		elif (adminStatus == 0): #just a reg employee
			return response_with(responses.SUCCESS_200, value={"value": convertedItem}, message={"userID" : uuid, "admin" : adminStatus}); #returns just user

	except Exception as e:
		return response_with(responses.UNAUTHORIZED_401, value={"value" : str(e)})
Exemple #5
0
 def get_token(self, username: str, password: str) -> str:
     u = Cognito(self.user_pool,
                 self.client_id,
                 self.region,
                 username=username)
     u.authenticate(password=password)
     return u.access_token
    def authenticate(self, username, password):
        clientId = self.identity['provider']['client_id']
        userPoolId = self.identity['provider']['userpool_id']

        u = Cognito(userPoolId, clientId, username=username)
        u.authenticate(password=password)
        # TODO: if this fails, we should error gracefully with a 401
        token = u.id_token
        self.allowed_perms = self.set_perms(token)
Exemple #7
0
 def post(self):
     data = self.parser.parse_args()
     u = Cognito(os.environ['COGNITO_USERPOOL_ID'],
                 os.environ['COGNITO_APP_CLIENT_ID'],
                 username=data['username'])
     try:
         u.authenticate(password=data['password'])
     except ClientError as e:
         return {'message': str(e)}
     return {'access_token': u.id_token}
Exemple #8
0
def valid_login(username, password):
    cognito = Cognito(cognito_userpool_id,
                      cognito_app_client_id,
                      username=username)
    try:
        cognito.authenticate(password)
    except Exception as e:
        print(e)
        return False
    return True
Exemple #9
0
 def setUpClass(cls):
     super(VGBaseTestCase, cls).setUpClass()
     user = Cognito(COGNITO_USER_POOL,
                    COGNITO_APP_ID,
                    username=COGNITO_USER)
     user.authenticate(password=COGNITO_USER_PASSWORD)
     cls.token = user.id_token
     nauser = Cognito(COGNITO_USER_POOL,
                      COGNITO_APP_ID,
                      username=COGNITO_USER_NONADMIN)
     nauser.authenticate(password=COGNITO_USER_PASSWORD_NONADMIN)
     cls.natoken = nauser.id_token
Exemple #10
0
def do_work():

    user_pool_id = os.environ['AWS_COGNITO_POOL_ID']
    client_id = os.environ['AWS_COGNITO_CLIENT_ID']
    client_secret = os.environ.get('AWS_COGNITO_SECRET_KEY')
    username = os.environ.get('COGNITO_USER')
    password = os.environ['COGNITO_PASSWORD']
    u = Cognito(user_pool_id=user_pool_id,
                client_id=client_id,
                client_secret=client_secret,
                username=username)
    u.authenticate(password=password)
    print(u.access_token)
Exemple #11
0
def authenticate_user(config, username, password):

    u = Cognito(config['aws']['cognitio']['userPoolId'],
                config['aws']['cognitio']['userPoolClientId'],
                username=username)
    u.authenticate(password=password)
    user = u.get_user(attr_map={
        "given_name": "first_name",
        "family_name": "last_name"
    })

    print user.username, user.email_verified, u.access_token

    return u.access_token
Exemple #12
0
def login_user():
    data = request.data
    dataDict = json.loads(data)
    _email = dataDict.get('email')
    _password = dataDict.get('password')
    u = Cognito(CONSTANTS['cognito_id'],
                CONSTANTS['cognito_app'],
                username=_email)
    u.authenticate(password=_password)
    info = {
        "idToken": u.id_token,
        "accessToken": u.access_token,
        "refreshToken": u.refresh_token
    }
    return Response(json.dumps(info), status=200, mimetype='application/json')
def test_valid_login():
    client_id = "5bl2caob065vqodmm3sobp3k7d"
    user_pool_id = "eu-west-1_mQ0D78123"

    login(username, password)
    user_details = User.get_instance()

    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"})

    assert user_details.user_id == user.sub
    assert user_details.username == user.username
    assert user_details.hcp_id != 0
def handler(event, context):
    print(event)
    cognito_pool_id = os.environ['COGNITO_POOL_ID']
    cognito_client_id = os.environ['COGNITO_CLIENT_ID']
    username = event['username']
    password = event['password']

    cognito = Cognito(cognito_pool_id,
                      cognito_client_id,
                      user_pool_region=os.environ['AWS_REGION'],
                      username=username)

    try:
        cognito.authenticate(password=password)
    except Exception as e:
        print(e)
        raise Exception
    else:
        return cognito.id_token
def handler(event, context):
    print(event)
    cognito_pool_id = os.environ['COGNITO_POOL_ID']
    cognito_client_id = os.environ['COGNITO_CLIENT_ID']
    username = event['username']
    password = event['password']

    cognito = Cognito(
        cognito_pool_id,
        cognito_client_id,
        user_pool_region=os.environ['AWS_REGION'],
        username=username)

    try:
        cognito.authenticate(password=password)
    except Exception as e:
        print(e)
        raise Exception
    else:
        return cognito.id_token
Exemple #16
0
    def post(self):
        """login/authenticate a user"""
        json_data = request.get_json(force=True)

        email = json_data['email']
        password = json_data['password']

        try:
            u = Cognito(cognitoUserPoolId, cognitoUserPoolClientId, awsRegion, username=email)
            u.authenticate(password)
            data = {
                # "email":email,
                "id_token": u.id_token,
                "refresh_token": u.refresh_token,
                "access_token": u.access_token,
                "token_type": u.token_type,
            }
            print(ReturnDocument(data, "success").asdict())
            return ReturnDocument(data, "success").asdict()
        except ClientError as err:
            return ReturnDocument(err.__str__(), "error").asdict()
Exemple #17
0
 def validate_user(
     self,
     username,
     pin,
 ):
     info = self.ids.info
     username = self.ids.username.text
     pin = self.ids.pin.text + self.ids.pin.text
     try:
         #### enter your AWS creds here
         u = Cognito(
             'eu-west-1_#########',
             '#################',
             user_pool_region='eu-west-1',
             username=username,
             access_key='#############',
             secret_key='##########################################')
         u.authenticate(password=pin)
         self.isAuthenticated = True
     except:
         info.text = '[color=#FF0000]Invalid Username and/or Password[/color]'
    def cog_test_authenticate(self):
        cognito = Cognito(
            'us-east-1_V2t2miGey',
            '3nlvl0p7duau88cbbmd3pv337o',
            user_pool_region='us-east-1',
            client_secret='4q67ap5cb1msfci67v5p7bgv3buam78mvvhcbbmgq9va9konod4',
            username='******')

        # cognito = Cognito('us-east-1_iWsiqRN3n', '4stcts76mik8nvc1rjef5s3c3p',
        #                   user_pool_region='us-east-1',
        #                   client_secret='5n2kp1j7p818hril9eqcmgsqqjqedfgou544rrf9qjk29dkispm',
        #                   username='******')

        # cognito = Cognito('us-east-1_V2t2miGey', '3nlvl0p7duau88cbbmd3pv337o',
        #                   user_pool_region='us-east-1',
        #                   client_secret='4q67ap5cb1msfci67v5p7bgv3buam78mvvhcbbmgq9va9konod4')

        # Registration
        # cognito.add_base_attributes(email='*****@*****.**')
        #
        # cognito.register('nauge1', 'Nauge009#')
        #
        # cognito.admin_confirm_sign_up(username='******')

        # Authentication
        cognito.authenticate(password='******')

        access_token = cognito.access_token
        id_token = cognito.id_token
        refresh_token = cognito.refresh_token

        user = cognito.get_user(attr_map={"email": "email"})
        user_emnail = user._data['email']

        # Delete User
        # cognito.authenticate(password='******')
        # cognito.delete_user()

        self.logger.debug("Cognito:")
Exemple #19
0
def login():
    # TODO: render to each user
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        u = Cognito(USER_POOL_ID, CLIENT_ID, REGION, username=username,
                    access_key='dummy_not_used', secret_key='dummy_not_used')

        try:
            u.authenticate(password)
            session['asscess_token'] = u.access_token
            session['refresh_token'] = u.refresh_token
            session['id_token'] = u.id_token
            session['user_login'] = True
            session['username'] = username
            return redirect(url_for('index'))
        except ClientError as e:
            flash(e.response.get('Error').get('Message'))
        except ValueError as e:
            flash('Incorrect username or password.')

    return render_template("login.html")
Exemple #20
0
class Client:
    def __init__(self):

        # AWS cognito account info imported from .env
        dotenv_path = join(dirname(__file__), '.client_env')
        load_dotenv(dotenv_path)
        self.region = os.environ.get('REGION')
        self.userpool_id = os.environ.get('USERPOOL_ID')
        self.app_id_client = os.environ.get('APP_CLIENT_ID')
        self.app_client_secret = os.environ.get('APP_CLIENT_SECRET')
        self.username = os.environ.get('USERNAME')
        self.password = os.environ.get('PASS')

        self.user = Cognito(self.userpool_id,
                            self.app_id_client,
                            client_secret=self.app_client_secret,
                            username=self.username)
        try:
            self.user.authenticate(password=self.password)
        except Exception as e:
            print(e)

    def public_api_route(self):
        response = requests.get("http://localhost:5000/public")
        return response.text

    def private_api_route(self):
        header = {}
        try:
            self.user.check_token()
            header = {"Authorization": f"Bearer {self.user.access_token}"}
        except AttributeError as e:
            print(e)
        response = requests.get("http://localhost:5000/private",
                                headers=header)
        return response.text
Exemple #21
0
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)
Exemple #22
0
class PyEmVue(object):
    def __init__(self):
        self.username = None
        self.token_storage_file = None
        self.customer = None
        self.cognito = None

    def get_devices(self):
        """Get all devices under the current customer account."""
        url = API_ROOT + API_CUSTOMER_DEVICES.format(customerGid = self.customer.customer_gid)
        response = self._get_request(url)
        response.raise_for_status()
        devices = []
        if response.text:
            j = response.json()
            if 'devices' in j:
                for dev in j['devices']:
                    devices.append(VueDevice().from_json_dictionary(dev))
                    if 'devices' in dev:
                        for subdev in dev['devices']:
                            devices.append(VueDevice().from_json_dictionary(subdev))
        return devices

    def populate_device_properties(self, device):
        """Get details about a specific device"""
        url = API_ROOT + API_DEVICE_PROPERTIES.format(deviceGid=device.device_gid)
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            device.populate_location_properties_from_json(j)
        return device

    def get_customer_details(self):
        """Get details for the current customer."""
        
        url = API_ROOT + API_CUSTOMER.format(email=quote(self.username))
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            return Customer().from_json_dictionary(j)
        return None

    def get_devices_usage(self, deviceGids, instant, scale=Scale.SECOND.value, unit=Unit.KWH.value):
        """Returns a list of VueDeviceChannelUsage with the total usage of the devices over the specified scale. Note that you may need to scale this to get a rate (1MIN in kw = 60*result)"""
        if not instant: instant = datetime.datetime.utcnow()
        gids = deviceGids
        if isinstance(deviceGids, list):
            gids = '+'.join(map(str, deviceGids))
        
        url = API_ROOT + API_DEVICES_USAGE.format(deviceGids=gids, instant=_format_time(instant), scale=scale, unit=unit)
        response = self._get_request(url)
        response.raise_for_status()
        channels = []
        if response.text:
            j = response.json()
            if 'channelUsages' in j:
                for channel in j['channelUsages']:
                    if channel: channels.append(VueDeviceChannelUsage().from_json_dictionary(channel))
        return channels


    def get_chart_usage(self, channel, start, end, scale=Scale.SECOND.value, unit=Unit.KWH.value):
        """Gets the usage over a given time period and the start of the measurement period. Note that you may need to scale this to get a rate (1MIN in kw = 60*result)"""
        if channel.channel_num in ['MainsFromGrid', 'MainsToGrid']:
            # These is not populated for the special Mains data as of right now
            return [], start
        if not start: start = datetime.datetime.utcnow()
        if not end: end = datetime.datetime.utcnow()
        url = API_ROOT + API_CHART_USAGE.format(deviceGid=channel.device_gid, channel=channel.channel_num, start=_format_time(start), end=_format_time(end), scale=scale, unit=unit)
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            if 'firstUsageInstant' in j: instant = parse(j['firstUsageInstant'])
            else: instant = start
            if 'usageList' in j: usage = j['usageList']
            else: usage = []
            return usage, instant
        return [], start

    def get_outlets(self):
        """ Return a list of outlets linked to the account. """
        url = API_ROOT + API_GET_OUTLETS.format(customerGid=self.customer.customer_gid)
        response = self._get_request(url)
        response.raise_for_status()
        outlets = []
        if response.text:
            j = response.json()
            for raw_outlet in j:
                outlets.append(OutletDevice().from_json_dictionary(raw_outlet))
        return outlets

    def update_outlet(self, outlet, on=None):
        """ Primarily to turn an outlet on or off. If the on parameter is not provided then uses the value in the outlet object.
            If on parameter provided uses the provided value."""
        url = API_ROOT + API_OUTLET
        if on is not None:
            outlet.outlet_on = on

        response = self._put_request(url, outlet.as_dictionary())
        response.raise_for_status()
        outlet.from_json_dictionary(response.json())
        return outlet

    def login(self, username=None, password=None, id_token=None, access_token=None, refresh_token=None, token_storage_file=None):
        """ Authenticates the current user using access tokens if provided or username/password if no tokens available.
            Provide a path for storing the token data that can be used to reauthenticate without providing the password.
            Tokens stored in the file are updated when they expire.
        """
        # Use warrant to go through the SRP authentication to get an auth token and refresh token
        client = boto3.client('cognito-idp', region_name='us-east-2', 
            config=botocore.client.Config(signature_version=botocore.UNSIGNED))
        if id_token is not None and access_token is not None and refresh_token is not None:
            # use existing tokens
            self.cognito = Cognito(USER_POOL, CLIENT_ID,
                user_pool_region='us-east-2', 
                id_token=id_token, 
                access_token=access_token, 
                refresh_token=refresh_token)
            self.cognito.client = client
        elif username is not None and password is not None:
            #log in with username and password
            self.cognito = Cognito(USER_POOL, CLIENT_ID, 
                user_pool_region='us-east-2', username=username)
            self.cognito.client = client
            self.cognito.authenticate(password=password)
        else:
            raise Exception('No authentication method found. Must supply username/password or id/auth/refresh tokens.')
        if self.cognito.access_token is not None:
            if token_storage_file is not None: self.token_storage_file = token_storage_file
            self._check_token()
            user = self.cognito.get_user()
            self.username = user._data['email']
            self.customer = self.get_customer_details()
            self._store_tokens()
        return self.customer is not None
        
    def _check_token(self):
        if self.cognito.check_token(renew=True):
            # Token expired and we renewed it. Store new token
            self._store_tokens()

    def _store_tokens(self):
        if not self.token_storage_file: return
        data = {
            'idToken': self.cognito.id_token,
            'accessToken': self.cognito.access_token,
            'refreshToken': self.cognito.refresh_token
        }
        if self.username:
            data['email'] = self.username
        with open(self.token_storage_file, 'w') as f:
            json.dump(data, f, indent=2)

    def _get_request(self, full_endpoint):
        if not self.cognito: raise Exception('Must call "login" before calling any API methods.')
        self._check_token() # ensure our token hasn't expired, refresh if it has
        headers = {'authtoken': self.cognito.id_token}
        return requests.get(full_endpoint, headers=headers)

    def _put_request(self, full_endpoint, body):
        if not self.cognito: raise Exception('Must call "login" before calling any API methods.')
        self._check_token() # ensure our token hasn't expired, refresh if it has
        headers = {'authtoken': self.cognito.id_token}
        return requests.put(full_endpoint, headers=headers, json=body)
Exemple #23
0
IDP = "cognito-idp.us-east-1.amazonaws.com/" + COGNITO_POOL_ID
REGION_NAME = 'us-east-1'
ACCOUNT_ID = '978327071167'

# This URL will come from API
url = "https://s3.amazonaws.com/v-lambda-package-v1/Firmware/Backend_Architecture_v4.0.pdf"

# These are App User --> Tied to a respective Cognito User Pool
user = "******"
pwd = "Sunday@2017"

# Authenticating with Cognito User Pool(CUP). it_token is a JWT Token
# User is assigned to "AppGroup" group in CUP. AppGroup in linked with an IAM Role

u = Cognito(COGNITO_POOL_ID, COGNITO_APP, username=user)
u.authenticate(password=pwd)
u.id_token

# With the id_token, user will now try to Assume an IAM role
# This process is federated by Cognito Identity Pool (CIP)
# CIP lets user to assume an IAM role, namely AppRole.
# AppRole is configured to read S3 files

boto3.setup_default_session(region_name=REGION_NAME)
identity_client = boto3.client('cognito-identity', region_name=REGION_NAME)
identity_response = identity_client.get_id(AccountId=ACCOUNT_ID,
                                           IdentityPoolId=IDENTITY_POOL_ID,
                                           Logins={IDP: u.id_token})
identity_id = identity_response['IdentityId']
credentials_response = identity_client.get_credentials_for_identity(
    IdentityId=identity_id, Logins={IDP: u.id_token})
Exemple #24
0
class WheelFeederAuthentication:

    """
    WheelFeederAuthentication takes care about building valid session with the Wheel's API
    using Cognito User Pool that gets created using Cloudformation Template during deployment of the Wheel.
    """

    def __init__(self, cognito_user_pool_id, cognito_client_id, region_name=None):
        """
        :param cognito_user_pool_id: Cognito User Pool Id which the Wheel uses to authenticate the Users
        :type cognito_user_pool_id: str
        :param cognito_client_id: Client Id configured in the Cognito User Pool
        :type cognito_client_id: str
        """
        self._username = None
        self._password = None
        self._cognito_user_pool_id = cognito_user_pool_id
        self._cognito_client_id = cognito_client_id
        self.region_name = region_name

        # stores object returned by warrant
        self._cognito_user_obj = None


    def build(self):
        """
        Drives the process of getting credentials from the User and initializing valid session with Cognito.
        """
        print("Initiating Authentication with Cognito")
        self._prompt_for_credentials()
        self._initalize_tokens()
        return self

    @property
    def id_token(self):
        return self._cognito_user_obj.id_token

    def _initalize_tokens(self):
        """
        Calls Cognito to initialize Credentials.
        There is no easy way yet to authenticate a user against a Cognito User Pool in Boto3.
        Hence we are using a library that makes it easy:
          - https://github.com/capless/warrant/tree/master/warrant
        """
        self._cognito_user_obj = Cognito(
            self._cognito_user_pool_id,
            self._cognito_client_id,
            username=self._username,
            user_pool_region=self.region_name
        )

        try:
            self._cognito_user_obj.authenticate(password=self._password)
        except Exception as e:
            print('Authentication Failed. Please try again. Error message:')
            print(f'{str(e)}')
            exit(1)

    def _prompt_for_credentials(self):
        """
        Prompts the user for username and password interactively
        """
        print("In order to be able to upload Participants, you need to authenticate.")
        print("Provide credentials of one of the valid users stored in Cognito User Pool")
        self._username = input('Username: '******'Password: ')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# encoding=utf8

## COGNITO_JWKS
# https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_J1HZ86uLX/.well-known/jwks.json

from warrant import Cognito

POOL_ID = 'eu-central-1_J1HZ86uLX'
APP_NAME = 'cognito-app-clients'
APP_ID = '6h58tr9l145ek8vqhqo9g3vi4d'
USERNAME = '******'
PASSWORD = '******'

u = Cognito(POOL_ID, APP_ID, username=USERNAME)
u.authenticate(password=PASSWORD)
print u
Exemple #26
0
def sign():
    signinform = SigninForm(prefix="signin")
    signupform = SignupForm(prefix="signup")

    if request.method == 'POST':
        form = request.form
        pprint.pprint(form)
        if request.form['btn'] == 'Signin':
            # session["active_panel"] = "login-form-link"
            if signinform.validate_on_submit():
                try:
                    auth_cognito = Cognito(
                        cognito_userpool_id,
                        cognito_client_id,
                        user_pool_region=cognito_userpool_region,
                        username=form['signin-username'])
                    auth_cognito.authenticate(password=form['signin-password'])
                    decoded_token = cognitojwt.decode(auth_cognito.id_token,
                                                      cognito_userpool_region,
                                                      cognito_userpool_id,
                                                      cognito_client_id)
                    user = auth_cognito.get_user()
                    credit = user._data['custom:credit']
                # except NotAuthorizedException as e:
                #     flash(e.response['Error']['Message'])
                #     return redirect(request.referrer)
                except Exception as e:
                    if hasattr(e, 'message'):
                        msg = e.message
                    else:
                        msg = str(e)
                    flash(msg, 'error')
                    return redirect(request.referrer)
                else:
                    flash("Signin Successfully!")

                    user = User()
                    user.id = decoded_token["cognito:username"]
                    user.credit = credit
                    session['credit'] = credit
                    session['expires'] = decoded_token["exp"]
                    session['refresh_token'] = auth_cognito.refresh_token
                    session['id_token'] = auth_cognito.id_token
                    session['access_token'] = auth_cognito.access_token
                    login_user(user, remember=True)
                    next_url = request.args.get('next', 'index').strip("/")
                    print("next_url:{}".format(next_url))
                    return redirect(url_for(next_url))

            else:
                flash(signinform.errors)
                return redirect(request.referrer)

        elif request.form['btn'] == 'Signup':
            # session["active_panel"] = "register-form-link"
            if signupform.validate_on_submit():
                try:
                    u = Cognito(cognito_userpool_id, cognito_client_id,
                                cognito_userpool_region)
                    u.add_base_attributes(email=form['signup-email'])
                    u.add_custom_attributes(credit='0')
                    u.register(form['signup-username'],
                               form['signup-password'])
                except Exception as e:
                    if hasattr(e, 'message'):
                        msg = e.message
                    else:
                        msg = str(e)
                    flash(msg, 'error')
                else:
                    pprint.pprint(session)
                    flash("Finish the signup by confirm link in mailbox")
            else:
                flash(signupform.errors, "error")

            return redirect(request.referrer)

    return render_template('sign.html',
                           signinform=signinform,
                           signupform=signupform)
Exemple #27
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('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()
Exemple #28
0
class PyEmVue(object):
    def __init__(self):
        self.username = None
        self.token_storage_file = None
        self.customer = None
        self.cognito = None

    def get_devices(self):
        """Get all devices under the current customer account."""
        url = API_ROOT + API_CUSTOMER_DEVICES.format(
            customerGid=self.customer.customer_gid)
        response = self._get_request(url)
        response.raise_for_status()
        devices = []
        if response.text:
            j = response.json()
            if 'devices' in j:
                for dev in j['devices']:
                    devices.append(VueDevice().from_json_dictionary(dev))
                    if 'devices' in dev:
                        for subdev in dev['devices']:
                            devices.append(
                                VueDevice().from_json_dictionary(subdev))
        return devices

    def populate_device_properties(self, device):
        """Get details about a specific device"""
        url = API_ROOT + API_DEVICE_PROPERTIES.format(
            deviceGid=device.device_gid)
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            device.populate_location_properties_from_json(j)
        return device

    def get_customer_details(self):
        """Get details for the current customer."""

        url = API_ROOT + API_CUSTOMER.format(email=quote(self.username))
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            return Customer().from_json_dictionary(j)
        return None

    def get_total_usage(self,
                        channel,
                        timeFrame=TotalTimeFrame.ALL.value,
                        unit=TotalUnit.WATTHOURS.value):
        """Get total usage over the provided timeframe for the given device channel."""
        url = API_ROOT + API_USAGE_TOTAL.format(deviceGid=channel.device_gid,
                                                timeFrame=timeFrame,
                                                unit=unit,
                                                channels=channel.channel_num)
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            if 'usage' in j: return j['usage']
        return 0

    def get_usage_over_time(self,
                            channel,
                            start,
                            end,
                            scale=Scale.SECOND.value,
                            unit=Unit.WATTS.value):
        """Get usage over the given time range. Used for primarily for plotting history. Supports time scales less than DAY."""
        if scale != Scale.SECOND.value and scale != Scale.MINUTE.value and scale != Scale.MINUTES_15.value and scale != Scale.HOUR.value:
            raise ValueError(
                f'Scale of {scale} is invalid, must be 1S, 1MIN, 15MIN, or 1H.'
            )
        url = API_ROOT + API_USAGE_TIME.format(deviceGid=channel.device_gid,
                                               startTime=_format_time(start),
                                               endTime=_format_time(end),
                                               scale=scale,
                                               unit=unit,
                                               channels=channel.channel_num)
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            if 'usage' in j: return j['usage']
        return []

    def get_usage_over_date_range(self,
                                  channel,
                                  start,
                                  end,
                                  scale=Scale.DAY.value,
                                  unit=Unit.WATTS.value):
        """
            Get usage over the given date range. Used for primarily for plotting history. Supports time scales of DAY or larger.
            Note strange behavior with what day is which, first value is for day before start, last value is for day before end, for test timezone of UTC-4.
            Advise getting a range of days around the desired day and manual verification.
        """
        if scale != Scale.DAY.value and scale != Scale.WEEK.value and scale != Scale.MONTH.value and scale != Scale.YEAR.value:
            raise ValueError(
                f'Scale of {scale} is invalid, must be 1D, 1W, 1MON, or 1Y.')
        url = API_ROOT + API_USAGE_DATE.format(deviceGid=channel.device_gid,
                                               startDate=_format_date(start),
                                               endDate=_format_date(end),
                                               scale=scale,
                                               unit=unit,
                                               channels=channel.channel_num)
        response = self._get_request(url)
        response.raise_for_status()
        if response.text:
            j = response.json()
            if 'usage' in j: return j['usage']
        return []

    def get_recent_usage(self, scale=Scale.HOUR.value, unit=Unit.WATTS.value):
        """Get usage over the last 'scale' timeframe."""
        now = datetime.datetime.utcnow()
        return self.get_usage_for_time_scale(now, scale, unit)[0]

    def get_usage_for_time_scale(self,
                                 time,
                                 scale=Scale.HOUR.value,
                                 unit=Unit.WATTS.value):
        """ Get usage for the 'scale' timeframe ending at the given time. 
            Only supported for scales less than one day, otherwise time value is ignored and most recent data is given.
        """
        start = time - datetime.timedelta(seconds=1)
        end = time
        url = API_ROOT + API_USAGE_DEVICES.format(
            customerGid=self.customer.customer_gid,
            scale=scale,
            unit=unit,
            startTime=_format_time(start),
            endTime=_format_time(end))
        response = self._get_request(url)
        response.raise_for_status()
        channels = []
        realStart = None
        realEnd = None
        if response.text:
            j = response.json()
            if 'start' in j:
                realStart = parse(j['start'])
            if 'end' in j:
                realEnd = parse(j['end'])
            if 'channels' in j:
                for channel in j['channels']:
                    channels.append(
                        VuewDeviceChannelUsage().from_json_dictionary(channel))
        return channels, realStart, realEnd

    def get_outlets(self):
        """ Return a list of outlets linked to the account. """
        url = API_ROOT + API_GET_OUTLETS.format(
            customerGid=self.customer.customer_gid)
        response = self._get_request(url)
        response.raise_for_status()
        outlets = []
        if response.text:
            j = response.json()
            for raw_outlet in j:
                outlets.append(OutletDevice().from_json_dictionary(raw_outlet))
        return outlets

    def update_outlet(self, outlet, on=None):
        """ Primarily to turn an outlet on or off. If the on parameter is not provided then uses the value in the outlet object.
            If on parameter provided uses the provided value."""
        url = API_ROOT + API_OUTLET
        if on is not None:
            outlet.outlet_on = on

        response = self._put_request(url, outlet.as_dictionary())
        response.raise_for_status()
        outlet.from_json_dictionary(response.json())
        return outlet

    def login(self,
              username=None,
              password=None,
              id_token=None,
              access_token=None,
              refresh_token=None,
              token_storage_file=None):
        """ Authenticates the current user using access tokens if provided or username/password if no tokens available.
            Provide a path for storing the token data that can be used to reauthenticate without providing the password.
            Tokens stored in the file are updated when they expire.
        """
        # Use warrant to go through the SRP authentication to get an auth token and refresh token
        client = boto3.client(
            'cognito-idp',
            region_name='us-east-2',
            config=botocore.client.Config(signature_version=botocore.UNSIGNED))
        if id_token is not None and access_token is not None and refresh_token is not None:
            # use existing tokens
            self.cognito = Cognito(USER_POOL,
                                   CLIENT_ID,
                                   user_pool_region='us-east-2',
                                   id_token=id_token,
                                   access_token=access_token,
                                   refresh_token=refresh_token)
            self.cognito.client = client
        elif username is not None and password is not None:
            #log in with username and password
            self.cognito = Cognito(USER_POOL,
                                   CLIENT_ID,
                                   user_pool_region='us-east-2',
                                   username=username)
            self.cognito.client = client
            self.cognito.authenticate(password=password)
        else:
            raise Exception(
                'No authentication method found. Must supply username/password or id/auth/refresh tokens.'
            )
        if self.cognito.access_token is not None:
            if token_storage_file is not None:
                self.token_storage_file = token_storage_file
            self._check_token()
            user = self.cognito.get_user()
            self.username = user._data['email']
            self.customer = self.get_customer_details()
            self._store_tokens()
        return self.customer is not None

    def _check_token(self):
        if self.cognito.check_token(renew=True):
            # Token expired and we renewed it. Store new token
            self._store_tokens()

    def _store_tokens(self):
        if not self.token_storage_file: return
        data = {
            'idToken': self.cognito.id_token,
            'accessToken': self.cognito.access_token,
            'refreshToken': self.cognito.refresh_token
        }
        if self.username:
            data['email'] = self.username
        with open(self.token_storage_file, 'w') as f:
            json.dump(data, f, indent=2)

    def _get_request(self, full_endpoint):
        if not self.cognito:
            raise Exception(
                'Must call "login" before calling any API methods.')
        self._check_token(
        )  # ensure our token hasn't expired, refresh if it has
        headers = {'authtoken': self.cognito.id_token}
        return requests.get(full_endpoint, headers=headers)

    def _put_request(self, full_endpoint, body):
        if not self.cognito:
            raise Exception(
                'Must call "login" before calling any API methods.')
        self._check_token(
        )  # ensure our token hasn't expired, refresh if it has
        headers = {'authtoken': self.cognito.id_token}
        return requests.put(full_endpoint, headers=headers, json=body)
 def login(self, user):
     u = Cognito(self.pool_id, self.client_id, username=user.user_id)
     u.authenticate(password=user.password)
     attrs = ["id_token", "refresh_token", "access_token", "token_type"]
     return {attr: getattr(u, attr) for attr in attrs}
Exemple #30
0
 def login(self, username, password):
     u = Cognito(self.USER_POOL_ID, self.CLIENT_ID, username=username)
     u.authenticate(password=password)
     return u
Exemple #31
0
 def authenticateUser(self, username, password):
     """Method to authenticate user"""
     u = Cognito(self.USER_POOL_ID, self.CLIENT_ID, username=username)
     u.authenticate(password=password)
     return u