Example #1
0
    def is_verified(self, site):
        """
        Check if a user has verified his/her identity.
        Calls the LMS verification status API endpoint and returns the verification status information.
        The status information is stored in cache, if the user is verified, until the verification expires.

        Args:
            site (Site): The site object from which the LMS account API endpoint is created.

        Returns:
            True if the user is verified, false otherwise.
        """
        try:
            cache_key = 'verification_status_{username}'.format(username=self.username)
            cache_key = hashlib.md5(cache_key).hexdigest()
            verification = cache.get(cache_key)
            if not verification:
                api = EdxRestApiClient(
                    site.siteconfiguration.build_lms_url('api/user/v1/'),
                    oauth_access_token=self.access_token
                )
                response = api.accounts(self.username).verification_status().get()

                verification = response.get('is_verified', False)
                if verification:
                    cache_timeout = int((parse(response.get('expiration_datetime')) - now()).total_seconds())
                    cache.set(cache_key, verification, cache_timeout)
            return verification
        except HttpNotFoundError:
            log.debug('No verification data found for [%s]', self.username)
            return False
        except (ConnectionError, SlumberBaseException, Timeout):
            msg = 'Failed to retrieve verification status details for [{username}]'.format(username=self.username)
            log.warning(msg)
            return False
Example #2
0
    def account_details(self, request):
        """ Returns the account details from LMS.

        Args:
            request (WSGIRequest): The request from which the LMS account API endpoint is created.

        Returns:
            A dictionary of account details.

        Raises:
            ConnectionError, SlumberBaseException and Timeout for failures in establishing a
            connection with the LMS account API endpoint.
        """
        try:
            api = EdxRestApiClient(
                request.site.siteconfiguration.build_lms_url('/api/user/v1'),
                append_slash=False,
                jwt=request.site.siteconfiguration.access_token
            )
            response = api.accounts(self.username).get()
            return response
        except (ConnectionError, SlumberBaseException, Timeout):
            log.exception(
                'Failed to retrieve account details for [%s]',
                self.username
            )
            raise
Example #3
0
    def account_details(cls, request, usernames):
        """
        Returns the account details from LMS.

        Args:
            request (WSGIRequest): The request from which the LMS account API endpoint is created.
            usernames: comma separated usernames, "username1,username2,username3"

        Returns:
            List of dictionaries of account details.

        Raises:
            ConnectionError, SlumberBaseException, Timeout, HttpClientError and  HttpNotFoundError
            for failures in establishing a connection with the LMS account API endpoint.
        """
        try:
            api = EdxRestApiClient(
                request.site.siteconfiguration.build_lms_url('/api/user/v1'),
                append_slash=False,
                jwt=request.site.siteconfiguration.access_token)
            response = api.accounts().get(username=usernames)
            return response
        except (ConnectionError, SlumberBaseException, Timeout,
                HttpClientError, HttpNotFoundError) as exc:
            log.exception(
                'Failed to retrieve account details for {usernames} due to: {exception}'
                .format(usernames=usernames, exception=str(exc)))
            return []
Example #4
0
    def is_verified(self, site):
        """
        Check if a user has verified his/her identity.
        Calls the LMS verification status API endpoint and returns the verification status information.
        The status information is stored in cache, if the user is verified, until the verification expires.

        Args:
            site (Site): The site object from which the LMS account API endpoint is created.

        Returns:
            True if the user is verified, false otherwise.

        Raises:
            ConnectionError, SlumberBaseException and Timeout for failures in
            establishing a connection with the LMS verification status API endpoint.
        """
        try:
            cache_key = 'verification_status_{username}'.format(username=self.username)
            cache_key = hashlib.md5(cache_key).hexdigest()
            verification = cache.get(cache_key)
            if not verification:
                api = EdxRestApiClient(
                    site.siteconfiguration.build_lms_url('api/user/v1/'),
                    oauth_access_token=self.access_token
                )
                response = api.accounts(self.username).verification_status().get()

                verification = response.get('is_verified', False)
                if verification:
                    cache_timeout = int((parse(response.get('expiration_datetime')) - now()).total_seconds())
                    cache.set(cache_key, verification, cache_timeout)
            return verification
        except HttpNotFoundError:
            log.debug('No verification data found for [%s]', self.username)
            return False
        except (ConnectionError, SlumberBaseException, Timeout):
            msg = 'Failed to retrieve verification status details for [{username}]'.format(username=self.username)
            log.exception(msg)
            raise VerificationStatusError(msg)
Example #5
0
class UserApiClient(object):
    """
    Object builds an API client to make calls to the edxapp User API.
    Authenticates using settings.OPENEDX_EDX_API_KEY.
    """

    API_BASE_URL = settings.OPENEDX_USER_API_URI
    APPEND_SLASH = False
    CACHE_ACCOUNTS_PREFIX = "userapi_accounts__"

    def __init__(self):
        """
        Create an LMS API client, authenticated with the OAuth2 token for client in settings
        """
        # session = Session()
        # # session.headers = {"X-Edx-Api-Key": settings.OPENEDX_EDX_API_KEY}
        token = EdxRestApiClient.get_oauth_access_token(
            url="{}{}".format(settings.OPENEDX_PLATFORM_URI,
                              constants.OPENEDX_OAUTH2_TOKEN_URL),
            client_id=settings.OPENEDX_OAUTH2_CLIENT_ID,
            client_secret=settings.OPENEDX_OAUTH2_CLIENT_SECRET)
        self.cache = False
        if settings.LMS_API_USE_MEMCACHED:
            self.cache = memcache.Client([settings.MEMCACHED_ADDRESS], debug=0)
        self.client = EdxRestApiClient(self.API_BASE_URL,
                                       append_slash=self.APPEND_SLASH,
                                       username="******",
                                       oauth_access_token=token[0])

    def get_edx_user_info(self, username):
        """
        Query the User API for the course details of the given course_id.
        Args:
            username (str): The username of the user
        Returns:
            dict with keys 'email', 'fullname' and 'unti_id' optionally
        """
        def _get_user_info_from_api(username, unti=False):

            try:
                resp = self.client.accounts(username).get()

                if resp:
                    data = {'email': resp['email'], 'fullname': resp['name']}
                    if unti and resp['unti_id']:
                        data.update({'unti_id': resp['unti_id']})
                    return data
                else:
                    # TODO: look at other reasons for no resp.success
                    message = 'Failed to retrieve user details for username {}. User not found in LMS'.format(
                        username)
                    raise exceptions.XAPIBridgeUserNotFoundError(message)

            except (SlumberBaseException, ConnectionError, Timeout,
                    HttpClientError) as e:
                message = 'Failed to retrieve user details for username {} due to: {}'.format(
                    username, str(e))
                e = exceptions.XAPIBridgeConnectionError(message)
                e.err_continue_exc()
                raise exceptions.XAPIBridgeUserNotFoundError(message)

        if username == '':
            raise exceptions.XAPIBridgeUserNotFoundError()
            # return {'email': '', 'fullname': ''}

        if hasattr(self, 'cache') and self.cache:
            cached_user_info = self.cache.get(self.CACHE_ACCOUNTS_PREFIX +
                                              username)
            if not cached_user_info:
                user_info = _get_user_info_from_api(username,
                                                    unti=settings.UNTI_XAPI)
                self.cache.set(self.CACHE_ACCOUNTS_PREFIX + username,
                               user_info,
                               time=300)
                return user_info
            else:
                return cached_user_info
        else:
            return _get_user_info_from_api(username, unti=settings.UNTI_XAPI)