Exemplo n.º 1
0
    async def authenticate(  # noqa: C901
            self,
            handler: LTI13LoginHandler,
            data: Dict[str, str] = None) -> Dict[str, str]:
        """
        Overrides authenticate from base class to handle LTI 1.3 authentication requests.

        Args:
          handler: handler object
          data: authentication dictionary

        Returns:
          Authentication dictionary
        """
        lti_utils = LTIUtils()
        validator = LTI13LaunchValidator()

        # get jwks endpoint and token to use as args to decode jwt. we could pass in
        # self.endpoint directly as arg to jwt_verify_and_decode() but logging the
        self.log.debug("JWKS platform endpoint is %s" % self.endpoint)
        id_token = handler.get_argument("id_token")
        self.log.debug("ID token issued by platform is %s" % id_token)

        # extract claims from jwt (id_token) sent by the platform. as tool use the jwks (public key)
        # to verify the jwt's signature.
        jwt_decoded = await validator.jwt_verify_and_decode(
            id_token, self.endpoint, False, audience=self.client_id)
        self.log.debug("Decoded JWT is %s" % jwt_decoded)

        if validator.validate_launch_request(jwt_decoded):
            course_id = jwt_decoded[
                "https://purl.imsglobal.org/spec/lti/claim/context"]["label"]
            course_id = lti_utils.normalize_string(course_id)
            self.log.debug("Normalized course label is %s" % course_id)
            username = ""
            if "email" in jwt_decoded and jwt_decoded["email"]:
                username = lti_utils.email_to_username(jwt_decoded["email"])
            elif "name" in jwt_decoded and jwt_decoded["name"]:
                username = jwt_decoded["name"]
            elif "given_name" in jwt_decoded and jwt_decoded["given_name"]:
                username = jwt_decoded["given_name"]
            elif "family_name" in jwt_decoded and jwt_decoded["family_name"]:
                username = jwt_decoded["family_name"]
            elif ("https://purl.imsglobal.org/spec/lti/claim/lis"
                  in jwt_decoded and "person_sourcedid" in
                  jwt_decoded["https://purl.imsglobal.org/spec/lti/claim/lis"]
                  and
                  jwt_decoded["https://purl.imsglobal.org/spec/lti/claim/lis"]
                  ["person_sourcedid"]):
                username = jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/lis"][
                        "person_sourcedid"].lower()
            elif ("lms_user_id" in jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/custom"]
                  and jwt_decoded[
                      "https://purl.imsglobal.org/spec/lti/claim/custom"]
                  ["lms_user_id"]):
                username = str(jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/custom"]
                               ["lms_user_id"])

            # set role to learner role (by default) if instructor or learner/student roles aren't
            # sent with the request
            user_role = "Learner"
            for role in jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/roles"]:
                if role.find("Instructor") >= 1:
                    user_role = "Instructor"
                elif role.find("Learner") >= 1 or role.find("Student") >= 1:
                    user_role = "Learner"
            self.log.debug("user_role is %s" % user_role)

            launch_return_url = ""
            if ("https://purl.imsglobal.org/spec/lti/claim/launch_presentation"
                    in jwt_decoded and "return_url" in jwt_decoded[
                        "https://purl.imsglobal.org/spec/lti/claim/launch_presentation"]
                ):
                launch_return_url = jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/launch_presentation"][
                        "return_url"]
            # if there is a resource link request then process additional steps
            if not validator.is_deep_link_launch(jwt_decoded):
                await process_resource_link_lti_13(self.log, course_id,
                                                   jwt_decoded)

            lms_user_id = jwt_decoded[
                "sub"] if "sub" in jwt_decoded else username

            # ensure the username is normalized
            self.log.debug("username is %s" % username)
            if not username:
                raise HTTPError(400, "Unable to set the username")

            # ensure the user name is normalized
            username_normalized = lti_utils.normalize_string(username)
            self.log.debug("Assigned username is: %s" % username_normalized)

            return {
                "name": username_normalized,
                "auth_state": {
                    "course_id": course_id,
                    "user_role": user_role,
                    "lms_user_id": lms_user_id,
                    "launch_return_url": launch_return_url,
                },  # noqa: E231
            }
Exemplo n.º 2
0
    async def authenticate(  # noqa: C901
        self, handler: LTI13LoginHandler, data: Dict[str, str] = None
    ) -> Dict[str, str]:
        """
        Overrides authenticate from base class to handle LTI 1.3 authentication requests.

        Args:
          handler: handler object
          data: authentication dictionary

        Returns:
          Authentication dictionary
        """
        lti_utils = LTIUtils()
        validator = LTI13LaunchValidator()

        # get jwks endpoint and token to use as args to decode jwt. we could pass in
        # self.endpoint directly as arg to jwt_verify_and_decode() but logging the
        self.log.debug('JWKS platform endpoint is %s' % self.endpoint)
        id_token = handler.get_argument('id_token')
        self.log.debug('ID token issued by platform is %s' % id_token)

        # extract claims from jwt (id_token) sent by the platform. as tool use the jwks (public key)
        # to verify the jwt's signature.
        jwt_decoded = await validator.jwt_verify_and_decode(id_token, self.endpoint, False, audience=self.client_id)
        self.log.debug('Decoded JWT is %s' % jwt_decoded)

        if validator.validate_launch_request(jwt_decoded):
            course_id = jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/context']['label']
            course_id = lti_utils.normalize_string(course_id)
            self.log.debug('Normalized course label is %s' % course_id)
            username = ''
            if 'email' in jwt_decoded and jwt_decoded['email']:
                username = lti_utils.email_to_username(jwt_decoded['email'])
            elif 'name' in jwt_decoded and jwt_decoded['name']:
                username = jwt_decoded['name']
            elif 'given_name' in jwt_decoded and jwt_decoded['given_name']:
                username = jwt_decoded['given_name']
            elif 'family_name' in jwt_decoded and jwt_decoded['family_name']:
                username = jwt_decoded['family_name']
            elif (
                'https://purl.imsglobal.org/spec/lti/claim/lis' in jwt_decoded
                and 'person_sourcedid' in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']
                and jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']['person_sourcedid']
            ):
                username = jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']['person_sourcedid'].lower()
            elif (
                'lms_user_id' in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/custom']
                and jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/custom']['lms_user_id']
            ):
                username = str(jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/custom']['lms_user_id'])
            self.log.debug('username is %s' % username)
            # ensure the username is normalized
            self.log.debug('username is %s' % username)
            if username == '':
                raise HTTPError('Unable to set the username')

            # set role to learner role (by default) if instructor or learner/student roles aren't
            # sent with the request
            user_role = 'Learner'
            for role in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/roles']:
                if role.find('Instructor') >= 1:
                    user_role = 'Instructor'
                elif role.find('Learner') >= 1 or role.find('Student') >= 1:
                    user_role = 'Learner'
            self.log.debug('user_role is %s' % user_role)

            launch_return_url = ''
            if (
                'https://purl.imsglobal.org/spec/lti/claim/launch_presentation' in jwt_decoded
                and 'return_url' in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/launch_presentation']
            ):
                launch_return_url = jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/launch_presentation'][
                    'return_url'
                ]
            # if there is a resource link request then process additional steps
            if not validator.is_deep_link_launch(jwt_decoded):
                await process_resource_link(self.log, course_id, jwt_decoded)

            lms_user_id = jwt_decoded['sub'] if 'sub' in jwt_decoded else username

            # ensure the user name is normalized
            username_normalized = lti_utils.normalize_string(username)
            self.log.debug('Assigned username is: %s' % username_normalized)

            return {
                'name': username_normalized,
                'auth_state': {
                    'course_id': course_id,
                    'user_role': user_role,
                    'lms_user_id': lms_user_id,
                    'launch_return_url': launch_return_url,
                },  # noqa: E231
            }
Exemplo n.º 3
0
    async def authenticate(  # noqa: C901
            self,
            handler: LTI13LoginHandler,
            data: Dict[str, str] = None) -> Dict[str, str]:
        """
        Overrides authenticate from base class to handle LTI 1.3 authentication requests.

        Args:
          handler: handler object
          data: authentication dictionary

        Returns:
          Authentication dictionary
        """
        lti_utils = LTIUtils()
        validator = LTI13LaunchValidator()

        # get jwks endpoint and token to use as args to decode jwt. we could pass in
        # self.endpoint directly as arg to jwt_verify_and_decode() but logging the
        self.log.debug('JWKS platform endpoint is %s' % self.endpoint)
        id_token = handler.get_argument('id_token')
        self.log.debug('ID token issued by platform is %s' % id_token)

        # extract claims from jwt (id_token) sent by the platform. as tool use the jwks (public key)
        # to verify the jwt's signature.
        jwt_decoded = await validator.jwt_verify_and_decode(
            id_token, self.endpoint, False, audience=self.client_id)
        self.log.debug('Decoded JWT is %s' % jwt_decoded)

        if validator.validate_launch_request(jwt_decoded):
            course_id = jwt_decoded[
                'https://purl.imsglobal.org/spec/lti/claim/context']['label']
            self.log.debug('Normalized course label is %s' % course_id)
            username = ''
            if 'email' in jwt_decoded.keys() and jwt_decoded.get('email'):
                username = lti_utils.email_to_username(jwt_decoded['email'])
            elif 'name' in jwt_decoded.keys() and jwt_decoded.get('name'):
                username = jwt_decoded.get('name')
            elif 'given_name' in jwt_decoded.keys() and jwt_decoded.get(
                    'given_name'):
                username = jwt_decoded.get('given_name')
            elif 'family_name' in jwt_decoded.keys() and jwt_decoded.get(
                    'family_name'):
                username = jwt_decoded.get('family_name')
            elif ('person_sourcedid' in
                  jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']
                  and
                  jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']
                  ['person_sourcedid']):
                username = jwt_decoded[
                    'https://purl.imsglobal.org/spec/lti/claim/lis'][
                        'person_sourcedid'].lower()
            if username == '':
                raise HTTPError('Unable to set the username')
            self.log.debug('username is %s' % username)

            # assign a workspace type, if provided, otherwise defaults to jupyter classic nb
            workspace_type = ''
            if ('https://purl.imsglobal.org/spec/lti/claim/custom'
                    in jwt_decoded and jwt_decoded[
                        'https://purl.imsglobal.org/spec/lti/claim/custom']
                    is not None):
                if ('workspace_type' in jwt_decoded[
                        'https://purl.imsglobal.org/spec/lti/claim/custom']
                        and jwt_decoded[
                            'https://purl.imsglobal.org/spec/lti/claim/custom']
                    ['workspace_type'] is not None):
                    workspace_type = jwt_decoded[
                        'https://purl.imsglobal.org/spec/lti/claim/custom'][
                            'workspace_type']
            if workspace_type not in WORKSPACE_TYPES:
                workspace_type = 'notebook'
            self.log.debug('workspace type is %s' % workspace_type)

            user_role = ''
            for role in jwt_decoded[
                    'https://purl.imsglobal.org/spec/lti/claim/roles']:
                if role.find('Instructor') >= 1:
                    user_role = 'Instructor'
                elif role.find('Learner') >= 1 or role.find('Student') >= 1:
                    user_role = 'Learner'
            # set role to learner role if instructor or learner/student roles aren't
            # sent with the request
            if user_role == '':
                user_role = 'Learner'
            self.log.debug('user_role is %s' % user_role)

            lms_user_id = jwt_decoded[
                'sub'] if 'sub' in jwt_decoded else username
            # Values for the send-grades functionality
            course_lineitems = ''
            if 'https://purl.imsglobal.org/spec/lti-ags/claim/endpoint' in jwt_decoded:
                course_lineitems = jwt_decoded[
                    'https://purl.imsglobal.org/spec/lti-ags/claim/endpoint'][
                        'lineitems']

            return {
                'name': username,
                'auth_state': {
                    'course_id': course_id,
                    'user_role': user_role,
                    'workspace_type': workspace_type,
                    'course_lineitems': course_lineitems,
                    'user_role': user_role,
                    'lms_user_id': lms_user_id,
                },  # noqa: E231
            }