Ejemplo n.º 1
0
    def test_award_program_certificate(self, mock_get_api_base_url):
        """
        Ensure the correct API call gets made
        """
        mock_get_api_base_url.return_value = 'http://test-server/'
        student = UserFactory(username='******',
                              email='*****@*****.**')

        test_client = requests.Session()
        test_client.auth = SuppliedJwtAuth('test-token')

        httpretty.register_uri(
            httpretty.POST,
            'http://test-server/credentials/',
        )

        tasks.award_program_certificate(test_client, student, 123,
                                        datetime(2010, 5, 30))

        expected_body = {
            'username':
            student.username,
            'lms_user_id':
            student.id,
            'credential': {
                'program_uuid': 123,
                'type': tasks.PROGRAM_CERTIFICATE,
            },
            'attributes': [{
                'name': 'visible_date',
                'value': '2010-05-30T00:00:00Z',
            }]
        }
        last_request_body = httpretty.last_request().body.decode('utf-8')
        assert json.loads(last_request_body) == expected_body
Ejemplo n.º 2
0
    def __init__(self,
                 base_url,
                 client_id,
                 client_secret,
                 timeout=(REQUEST_CONNECT_TIMEOUT, REQUEST_READ_TIMEOUT),
                 **kwargs):
        """
        Args:
            base_url (str): base url of the LMS oauth endpoint, which can optionally include the path `/oauth2`.
                Commonly example settings that would work for `base_url` might include:
                    LMS_BASE_URL = 'http://edx.devstack.lms:18000'
                    BACKEND_SERVICE_EDX_OAUTH2_PROVIDER_URL = 'http://edx.devstack.lms:18000/oauth2'
            client_id (str): Client ID
            client_secret (str): Client secret
            timeout (tuple(float,float)): Requests timeout parameter for access token requests.
                (https://requests.readthedocs.io/en/master/user/advanced/#timeouts)

        """
        super().__init__(**kwargs)
        self.headers['user-agent'] = USER_AGENT
        self.auth = SuppliedJwtAuth(None)

        self._base_url = base_url.rstrip('/')
        self._client_id = client_id
        self._client_secret = client_secret
        self._timeout = timeout
Ejemplo n.º 3
0
    def test_post_course_certificate_configuration(self,
                                                   mock_get_api_base_url):
        """
        Ensure the correct API call gets made
        """
        mock_get_api_base_url.return_value = 'http://test-server/'
        test_client = requests.Session()
        test_client.auth = SuppliedJwtAuth('test-token')

        httpretty.register_uri(
            httpretty.POST,
            'http://test-server/course_certificates/',
        )

        available_date = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')

        tasks.post_course_certificate_configuration(test_client,
                                                    self.certificate,
                                                    available_date)

        expected_body = {
            "course_id": 'testCourse',
            "certificate_type": 'verified',
            "certificate_available_date": available_date,
            "is_active": True
        }
        last_request_body = httpretty.last_request().body.decode('utf-8')
        assert json.loads(last_request_body) == expected_body
Ejemplo n.º 4
0
    def test_revoke_program_certificate(self, mock_get_api_base_url):
        """
        Ensure the correct API call gets made
        """
        mock_get_api_base_url.return_value = 'http://test-server/'
        test_username = '******'
        test_client = requests.Session()
        test_client.auth = SuppliedJwtAuth('test-token')

        httpretty.register_uri(
            httpretty.POST,
            'http://test-server/credentials/',
        )

        tasks.revoke_program_certificate(test_client, test_username, 123)

        expected_body = {
            'username': test_username,
            'status': 'revoked',
            'credential': {
                'program_uuid': 123,
                'type': tasks.PROGRAM_CERTIFICATE,
            }
        }
        last_request_body = httpretty.last_request().body.decode('utf-8')
        assert json.loads(last_request_body) == expected_body
Ejemplo n.º 5
0
def get_catalog_api_client(user):
    """
    Returns an API client which can be used to make Catalog API requests.
    """
    jwt = create_jwt_for_user(user)
    client = requests.Session()
    client.auth = SuppliedJwtAuth(jwt)

    return client
Ejemplo n.º 6
0
def build_jwt_edx_client(user):
    """
    Returns an edx API client authorized using JWT.
    """

    jwt = create_jwt_for_user(user)
    session = Session()
    session.auth = SuppliedJwtAuth(jwt)
    return session
Ejemplo n.º 7
0
 def __init__(self, user):
     """
     Initialize an authenticated Consent service API client by using the
     provided user.
     """
     jwt = create_jwt_for_user(user)
     base_api_url = configuration_helpers.get_value(
         'ENTERPRISE_CONSENT_API_URL', settings.ENTERPRISE_CONSENT_API_URL)
     self.client = requests.Session()
     self.client.auth = SuppliedJwtAuth(jwt)
     self.consent_endpoint = urljoin(f"{base_api_url}/",
                                     "data_sharing_consent")
Ejemplo n.º 8
0
    def __init__(self, user):
        """
        Initialize an authenticated Enterprise service API client.

        Authentificate by jwt token using the provided user.
        """
        self.user = user
        jwt = create_jwt_for_user(user)
        self.base_api_url = configuration_helpers.get_value(
            'ENTERPRISE_API_URL', settings.ENTERPRISE_API_URL)
        self.client = requests.Session()
        self.client.auth = SuppliedJwtAuth(jwt)
Ejemplo n.º 9
0
def get_ecommerce_api_client(user):
    """
    Returns an E-Commerce API client setup with authentication for the specified user.
    """
    claims = {'tracking_context': create_tracking_context(user)}
    scopes = ['user_id', 'email', 'profile']
    jwt = create_jwt_for_user(user, additional_claims=claims, scopes=scopes)

    client = requests.Session()
    client.auth = SuppliedJwtAuth(jwt)

    return client
Ejemplo n.º 10
0
    def __init__(self,
                 url,
                 signing_key=None,
                 username=None,
                 full_name=None,
                 email=None,
                 timeout=5,
                 issuer=None,
                 expires_in=30,
                 tracking_context=None,
                 oauth_access_token=None,
                 session=None,
                 jwt=None,
                 **kwargs):
        """
        Instantiate a new client. You can pass extra kwargs to Slumber like
        'append_slash'.

        Raises:
            ValueError: If a URL is not provided.

        """

        if not url:
            raise ValueError('An API url must be supplied!')

        warnings.warn(
            'EdxRestApiClient is deprecated. Use OAuthAPIClient instead.')

        if jwt:
            auth = SuppliedJwtAuth(jwt)
        elif oauth_access_token:
            auth = BearerAuth(oauth_access_token)
        elif signing_key and username:
            auth = JwtAuth(username,
                           full_name,
                           email,
                           signing_key,
                           issuer=issuer,
                           expires_in=expires_in,
                           tracking_context=tracking_context)
        else:
            auth = None

        session = session or requests.Session()
        session.headers['User-Agent'] = self.user_agent()

        session.timeout = timeout
        super(EdxRestApiClient, self).__init__(url,
                                               session=session,
                                               auth=auth,
                                               **kwargs)
Ejemplo n.º 11
0
def get_credentials_api_client(user):
    """
    Returns an authenticated Credentials API client.

    Arguments:
        user (User): The user to authenticate as when requesting credentials.
    """
    scopes = ['email', 'profile', 'user_id']
    jwt = create_jwt_for_user(user, scopes=scopes)

    client = requests.Session()
    client.auth = SuppliedJwtAuth(jwt)
    return client
Ejemplo n.º 12
0
 def __init__(self, base_url, client_id, client_secret, **kwargs):
     """
     Args:
         base_url (str): base url of LMS instance
         client_id (str): Client ID
         client_secret (str): Client secret
     """
     super(OAuthAPIClient, self).__init__(**kwargs)
     self.headers['user-agent'] = USER_AGENT
     self._base_url = base_url
     self._client_id = client_id
     self._client_secret = client_secret
     self._expiration = datetime.datetime(1983, 4, 6, 7, 30, 0)
     self.auth = SuppliedJwtAuth(None)
Ejemplo n.º 13
0
    def __init__(self,
                 url,
                 signing_key=None,
                 username=None,
                 full_name=None,
                 email=None,
                 timeout=5,
                 issuer=None,
                 expires_in=30,
                 tracking_context=None,
                 oauth_access_token=None,
                 session=None,
                 jwt=None,
                 **kwargs):
        """
        Instantiate a new client. You can pass extra kwargs to Slumber like
        'append_slash'.

        Raises:
            ValueError: If a URL is not provided.

        """

        if not url:
            raise ValueError('An API url must be supplied!')

        if jwt:
            auth = SuppliedJwtAuth(jwt)
        elif oauth_access_token:
            auth = BearerAuth(oauth_access_token)  # pylint: disable=redefined-variable-type
        elif signing_key and username:
            auth = JwtAuth(username,
                           full_name,
                           email,
                           signing_key,
                           issuer=issuer,
                           expires_in=expires_in,
                           tracking_context=tracking_context)
        else:
            auth = None

        session = session or requests.Session()
        session.timeout = timeout
        super(EdxRestApiClient, self).__init__(url,
                                               session=session,
                                               auth=auth,
                                               **kwargs)
Ejemplo n.º 14
0
    def __init__(self,
                 url,
                 signing_key=None,
                 username=None,
                 full_name=None,
                 email=None,
                 timeout=5,
                 issuer=None,
                 expires_in=30,
                 tracking_context=None,
                 oauth_access_token=None,
                 session=None,
                 jwt=None):
        """
        Instantiate a new client.

        Raises:
            ValueError, if either the URL or necessary authentication values are not provided.
        """

        if not url:
            raise ValueError('An API url must be supplied!')

        if jwt:
            auth = SuppliedJwtAuth(jwt)
        elif oauth_access_token:
            auth = BearerAuth(oauth_access_token)
        elif signing_key and username:
            auth = JwtAuth(username,
                           full_name,
                           email,
                           signing_key,
                           issuer=issuer,
                           expires_in=expires_in,
                           tracking_context=tracking_context)
        else:
            raise ValueError(
                'Either JWT or OAuth2 credentials must be supplied for authentication!'
            )

        session = session or requests.Session()
        session.timeout = timeout
        super(EdxRestApiClient, self).__init__(url, session=session, auth=auth)
Ejemplo n.º 15
0
    def test_post_course_certificate(self, mock_get_api_base_url):
        """
        Ensure the correct API call gets made
        """
        mock_get_api_base_url.return_value = 'http://test-server/'
        test_client = requests.Session()
        test_client.auth = SuppliedJwtAuth('test-token')

        httpretty.register_uri(
            httpretty.POST,
            'http://test-server/credentials/',
        )

        visible_date = datetime.now()

        tasks.post_course_certificate(test_client, self.student.username,
                                      self.certificate, visible_date)

        expected_body = {
            'username':
            self.student.username,
            'status':
            'awarded',
            'credential': {
                'course_run_key': str(self.certificate.course_id),
                'mode': self.certificate.mode,
                'type': tasks.COURSE_CERTIFICATE,
            },
            'date_override':
            None,
            'attributes': [{
                'name': 'visible_date',
                'value': visible_date.strftime(
                    '%Y-%m-%dT%H:%M:%SZ')  # text representation of date
            }]
        }
        last_request_body = httpretty.last_request().body.decode('utf-8')
        assert json.loads(last_request_body) == expected_body