Exemplo n.º 1
0
    def save(self):
        """Add the access token to the cache."""
        token = token_urlsafe()
        adviser = self.cleaned_data['adviser']
        timeout_hours = self.cleaned_data['expires_in_hours']
        timeout = timeout_hours * 60 * 60

        add_token_data_to_cache(token, adviser.email,
                                adviser.sso_email_user_id, timeout)
        return token, timeout_hours
Exemplo n.º 2
0
def create_user(request):
    """
    Create user

    This view is to facilitate End to End testing. It has no authentication and should
    only be enabled to run tests and never in production!

    POST to this view with a payload which is a single JSON object containing the following
    properties:

    {
        "first_name": <first name>,
        "last_name": <last name>,
        "email": <email>,
        "dit_team_id: <DIT team id>,
        "sso_email_user_id": <sso email user id>,
        "token": <desired token>
    }

    Provided token can be used to authenticate subsequent user requests.
    """
    if not settings.ALLOW_TEST_FIXTURE_SETUP:
        logger.warning(
            'The `create_user` endpoint is not enabled. The ALLOW_TEST_FIXTURE_SETUP environment'
            ' variable is not set.', )
        raise Http404

    seed_user_data = {
        'first_name': request.data['first_name'],
        'last_name': request.data['last_name'],
        'email': request.data['email'],
        'dit_team_id': request.data['dit_team_id'],
        'sso_email_user_id': request.data['sso_email_user_id'],
    }

    user_info = json.dumps(seed_user_data, indent=4, sort_keys=True)
    logger.info(f'Creating a user: {user_info}')

    seed_user = Advisor.objects.create(**seed_user_data)

    token = request.data['token']
    add_token_data_to_cache(
        token,
        seed_user.email,
        seed_user.sso_email_user_id,
        TEST_USER_TOKEN_TIMEOUT,
    )
    logger.info(f'Created a token `{token}` for user {seed_user.id}.')

    return Response(status=status.HTTP_201_CREATED, data={'id': seed_user.id})
Exemplo n.º 3
0
def _look_up_token(token, request) -> Tuple[Optional[dict], bool]:
    """
    Look up data about an access token.

    This first checks the cache, and falls back to querying Staff SSO if the token isn't cached.

    :returns: a 2-tuple of: (token data, was the token cached)
    """
    cached_token_data = get_token_data_from_cache(token)

    if cached_token_data:
        return cached_token_data, True

    try:
        introspection_data = introspect_token(token, request)
    except SSOInvalidTokenError:
        return None, False
    except SSORequestError:
        logger.exception('SSO introspection request failed')
        return None, False

    relative_expiry = _calculate_expiry(introspection_data['exp'])

    # This should not happen as expiry times should be in the future
    if relative_expiry <= 0:
        logger.warning('Introspected token has an expiry time in the past')
        return None, False

    cached_token_data = add_token_data_to_cache(
        token,
        introspection_data['username'],
        introspection_data['email_user_id'],
        relative_expiry,
    )
    return cached_token_data, False
Exemplo n.º 4
0
    def get_token(self, user=None):
        """Get access token for user test."""
        if not hasattr(self, '_tokens'):
            self._tokens = {}

        if user is None:
            user = self.user

        token_cache_key = user.sso_email_user_id

        if token_cache_key not in self._tokens:
            token = token_hex(16)
            add_token_data_to_cache(token, user.email, user.sso_email_user_id, None)
            self._tokens[token_cache_key] = token

        return self._tokens[token_cache_key]
Exemplo n.º 5
0
    def handle(self, *args, **options):
        """Main logic for the actual command."""
        sso_email_user_id = options['sso_email_user_id']
        token = options['token'] or token_urlsafe()
        hours = options['hours']
        timeout = hours * 60 * 60

        try:
            adviser = Advisor.objects.get(sso_email_user_id=sso_email_user_id)
        except Advisor.DoesNotExist:
            raise CommandError(f'No adviser with SSO email user ID {sso_email_user_id} found.')

        add_token_data_to_cache(token, adviser.email, adviser.sso_email_user_id, timeout)

        msg = f'The token {token} was successfully added and will expire in {hours} hours.'
        return self.style.SUCCESS(msg)
Exemplo n.º 6
0
    def test_adds_data_to_cache(self):
        """The data should be added to the cache."""
        token = 'test-token'
        email = '*****@*****.**'
        sso_email_user_id = '*****@*****.**'

        expected_data = {
            'email': email,
            'sso_email_user_id': sso_email_user_id,
        }

        frozen_time = now()
        with freeze_time(frozen_time):
            add_token_data_to_cache(token, email, sso_email_user_id, 10)

        cache_key = 'access_token:test-token'
        assert cache.get(cache_key) == expected_data

        # The data should expire after 10 seconds
        with freeze_time(frozen_time + timedelta(seconds=10)):
            assert cache.get(cache_key) is None
Exemplo n.º 7
0
    def test_returns_cached_data(self):
        """The data as stored in the cached should be returned."""
        token = 'test-token'
        email = '*****@*****.**'
        sso_email_user_id = '*****@*****.**'

        frozen_time = now()
        with freeze_time(frozen_time):
            returned_data = add_token_data_to_cache(token, email,
                                                    sso_email_user_id, 10)

        assert returned_data == {
            'email': email,
            'sso_email_user_id': sso_email_user_id,
        }