Exemplo n.º 1
0
def topup():
    form = CreditForm()
    if request.method == 'POST':
        msg = ""

        token = request.form['id']  # Using Flask
        amount = request.form['amount']
        charge = stripe.Charge.create(
            amount=amount,
            currency='nzd',
            description='vr 360 service fee',
            source=token,
        )  # todo how to know charge is success?
        try:
            if 'id_token' in session and 'access_token' in session and 'refresh_token':
                u = Cognito(cognito_userpool_id,
                            cognito_client_id,
                            cognito_userpool_region,
                            id_token=session['id_token'],
                            refresh_token=session['refresh_token'],
                            access_token=session['access_token'],
                            username=current_user.id)
                topup_amount = int(float(amount) / 100)
                user = u.get_user()
                balance = int(user._data['custom:credit'])
                new_balance = topup_amount + balance
                u.update_profile({'custom:credit': str(new_balance)})
                user = u.get_user()
                balance = user._data['custom:credit']
                session['credit'] = balance
                current_user.credit = balance
            else:
                raise Exception("Charged,but fail to topup the account")
        except Exception as e:
            if hasattr(e, 'message'):
                msg = e.message
            else:
                msg = e
        else:
            msg = "Topup Successfully"
        finally:
            # flash(msg)
            return msg  #render_template("topup.html",form=form, key=stripe_keys['publishable_key'])#redirect(url_for("topup"))

    elif request.method == 'GET':
        return render_template("topup.html",
                               form=form,
                               key=stripe_keys['publishable_key'])
Exemplo n.º 2
0
    def load_user_from_request_header(request):
        try:
            access_token_enc = request.headers["Authorization"]
            access_token_dec = auth.decodeJWT(access_token_enc)

            if(access_token_dec['exp'] < time.time()):
                return None

            # id_token_enc = request.headers["ID"]
            # kid = jwt.get_unverified_header(id_token_enc)['kid']
            # key = public_keys[kid]
            # access_token_dec = jwt.decode(id_token_enc, public_keys[kid], algorithms='RS256')

            access_token = request.headers["Authorization"]
            cognito = Cognito(
                environ.get('COGNITO_REGION'), environ.get('COGNITO_ACCESS'), access_token=access_token, user_pool_region='us-east-2')
            username = cognito.get_user()._metadata.get("username")
            if username is None:
                return None

            return User(username)

        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
            print(e)
            return None
Exemplo n.º 3
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
Exemplo n.º 4
0
def load_user_from_request_header(request):
    try:
        access_token = request.headers.get("X-LiQR-Authorization")
        id_token = request.headers.get("X-LiQR-ID")
        unique_id = request.form['unique_id']
        name = request.form['name']

        # sys.stderr.write("LiQR_Error: " + access_token+ " who is a " + str(request.args) + " connected\n")
        cognito = Cognito("ap-south-1_v9uz3gNH6",
                          "2oauo7q0odvn3c99dsevmstk54",
                          user_pool_region="ap-south-1",
                          access_token=access_token,
                          id_token=id_token)
        username = cognito.get_user().sub
        phone_number = cognito.get_user().phone_number
        # sys.stderr.write("LiQR_Error: " + phone_number + " who is a " + " connected\n")
        # sys.stderr.write("LiQR_Error: " + username + " who is a " + " connected\n")
        # sys.stderr.write("LiQR_Error: " + unique_id + " who is a " + " connected\n")
        if len(AppUser.objects(username=username)) == 0:
            print("New user here")
            the_user = PhoneUser(phone_no=phone_number,
                                 unique_id=unique_id,
                                 name=name,
                                 aws_id=username).save()
            app_user = AppUser(username=username,
                               user_type="neo_customer",
                               rest_user=the_user.to_dbref(),
                               timestamp=datetime.now()).save()
            return app_user
        if username is None:
            return None
        print("Old user")
        return AppUser.objects(username=username).first()
    except Exception as e:
        print(e)
        return None
Exemplo n.º 5
0
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
Exemplo n.º 6
0
def sign_in():
    if request and request.method == "GET":
        resp, err = GetUserPasswordFromAuthHeader(request)
        if err:
            log.error(err)
            res = GetResponseObject(err, 400)
            return res

        username, password = resp[0], resp[1]

        try:
            user = Cognito(user_pool_id=COGNITO_USER_POOL_ID, \
                client_id=COGNITO_APP_CLIENT_ID, \
                user_pool_region=AWS_REGION, \
                username=username)

            user.admin_authenticate(password=password)
            user_rec = user.get_user()

            uid = user_rec.sub
            usertype = user_rec._data['custom:usertype']

            userObj = Users.get(uid)
            # userObj = Users.get(uid, usertype)

            out = SerializeUserObj(userObj)
            # out["usertype"] = usertype
            data = {
                # "idToken": user.id_token,
                "accessToken": user.access_token,
                # "refreshToken": user.refresh_token,
                "profile": out
            }
            res = GetResponseObject(data, 200, True)
            res.headers['HMS-TOKEN'] = "Bearer " + user.access_token
            # res.set_cookie(settings.COOKIE_NAME , user.access_token)
            return res

        except Exception as e:
            msg = f"Error while authenticating user {str(e)}"
            return GetResponseObject(msg)
            # return HttpResponseServerError(res)
    else:
        data = f"Invalid request method, method {request.method} not supported !!!"
        return GetResponseObject(data, 405)
    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:")
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
0
 def getUserData(self, username, attr_map):
     u = Cognito(self.USER_POOL_ID, self.CLIENT_ID)
     user = u.get_user(attr_map)
     return user
Exemplo n.º 12
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,
                            self.username)

    def tearDown(self):
        del self.user

    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_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()

    def test_update_profile(self):
        self.user.authenticate(self.password)
        self.user.update_profile({'given_name': 'Jenkins'})
        u = self.user.get_user()
        self.assertEquals(u.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.assertEquals(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)
Exemplo n.º 13
0
 def user_obj_from_cognito(cognito: Cognito):
     return cognito.get_user(attr_map={
         'sub': 'id'
     })