Exemplo n.º 1
0
    def launch_lab(self):
        lab_id = request.args.get('id')
        lab = self.session.query(Laboratory).filter_by(id = lab_id).first()
        if lab is None:
            return "Laboratory id not found", 404

        db_rlms = lab.rlms
        ManagerClass = get_manager_class(db_rlms.kind, db_rlms.version, db_rlms.id)
        remote_laboratory = ManagerClass(db_rlms.configuration)
        back_url = url_for('.display_lab', id = lab_id)
        try:
            response = remote_laboratory.reserve(lab.laboratory_id,
                                             current_user.login,
                                             "admin-panel",
                                             "{}",
                                             [],
                                             {},
                                             { 
                                                'user_agent' : unicode(request.user_agent),
                                                'from_ip'    : remote_addr(),
                                                'referer'    : request.referrer,
                                            }, back_url = back_url, debug = True)

            load_url = response['load_url']
        except Exception as e:
            flash(gettext("There was a problem testing this experiment. Error message: %s" % e))
            return redirect(back_url)
        return redirect(load_url)
Exemplo n.º 2
0
    def launch_lab(self):
        lab_id = request.args.get('id')
        lab = self.session.query(Laboratory).filter_by(id=lab_id).first()
        if lab is None:
            return "Laboratory id not found", 404

        db_rlms = lab.rlms
        ManagerClass = get_manager_class(db_rlms.kind, db_rlms.version,
                                         db_rlms.id)
        remote_laboratory = ManagerClass(db_rlms.configuration)
        back_url = url_for('.display_lab', id=lab_id)
        try:
            response = remote_laboratory.reserve(
                lab.laboratory_id,
                current_user.login,
                "admin-panel",
                "{}", [], {}, {
                    'user_agent': unicode(request.user_agent),
                    'from_ip': remote_addr(),
                    'referer': request.referrer,
                },
                back_url=back_url,
                debug=True)

            load_url = response['load_url']
        except Exception as e:
            flash(
                gettext(
                    "There was a problem testing this experiment. Error message: %s"
                    % e))
            return redirect(back_url)
        return redirect(load_url)
Exemplo n.º 3
0
def stats():
    url = request.args.get('url')
    timezone_minutes = request.args.get('timezone_minutes')
    ip_address = remote_addr()
    log = UseLog(url = url, ip_address = ip_address, web_browser = request.headers.get('User-Agent'), user_agent = request.user_agent, lang_header=request.headers.get('Accept-Language'), timezone_minutes=timezone_minutes)
    db.session.add(log)
    db.session.commit()
    return "This is only for local statistics. No personal information is stored."
Exemplo n.º 4
0
def stats():
    url = request.args.get('url')
    timezone_minutes = request.args.get('timezone_minutes')
    ip_address = remote_addr()
    log = UseLog(url = url, ip_address = ip_address, web_browser = request.headers.get('User-Agent'), user_agent = request.user_agent, lang_header=request.headers.get('Accept-Language'), timezone_minutes=timezone_minutes)
    db.session.add(log)
    db.session.commit()
    return "This is only for local statistics. No personal information is stored."
Exemplo n.º 5
0
    def show_lab(self, public_identifier):
        lab = self.session.query(Laboratory).filter_by(
            public_identifier=public_identifier).first()
        if lab is None:
            return "Laboratory id not found", 404

        if request.method == 'GET':
            return self.render("public/display_public_lab.html",
                               laboratory=lab)

        # Else is post
        db_rlms = lab.rlms
        ManagerClass = get_manager_class(db_rlms.kind, db_rlms.version,
                                         db_rlms.id)
        remote_laboratory = ManagerClass(db_rlms.configuration)
        back_url = url_for('.show_lab',
                           public_identifier=public_identifier,
                           _external=True)
        next_url = request.args.get('return')
        if next_url:
            for url in current_app.config.get('VALID_REDIRECT_URLS') or []:
                if next_url.startswith(url):
                    back_url = next_url
                    break

        try:
            response = remote_laboratory.reserve(
                lab.laboratory_id,
                "anonymous",
                "admin-panel",
                "{}", [], {}, {
                    'user_agent': unicode(request.user_agent),
                    'from_ip': remote_addr(),
                    'referer': request.referrer,
                },
                back_url=back_url,
                debug=True)

            load_url = response['load_url']
        except Exception as e:
            import traceback
            traceback.print_exc()
            flash(
                gettext(
                    "There was a problem testing this experiment. Error message: %s"
                    % e))
            return redirect(back_url)
        return redirect(load_url)
Exemplo n.º 6
0
    def show_lab(self, public_identifier):
        lab = self.session.query(Laboratory).filter_by(public_identifier = public_identifier).first()
        if lab is None:
            return "Laboratory id not found", 404

        if request.method == 'GET':
            return self.render("public/display_public_lab.html", laboratory = lab)

        # Else is post
        db_rlms = lab.rlms
        ManagerClass = get_manager_class(db_rlms.kind, db_rlms.version, db_rlms.id)
        remote_laboratory = ManagerClass(db_rlms.configuration)
        back_url = url_for('.show_lab', public_identifier=public_identifier, _external=True)
        next_url = request.args.get('return')
        if next_url:
            for url in current_app.config.get('VALID_REDIRECT_URLS') or []:
                if next_url.startswith(url):
                    back_url = next_url
                    break

        try:
            response = remote_laboratory.reserve(lab.laboratory_id,
                                             "anonymous",
                                             "admin-panel",
                                             "{}",
                                             [],
                                             {},
                                             { 
                                                'user_agent' : unicode(request.user_agent),
                                                'from_ip'    : remote_addr(),
                                                'referer'    : request.referrer,
                                            }, back_url = back_url, debug = True)

            load_url = response['load_url']
        except Exception as e:
            import traceback
            traceback.print_exc()
            flash(gettext("There was a problem testing this experiment. Error message: %s" % e))
            return redirect(back_url)
        return redirect(load_url)
Exemplo n.º 7
0
def launch_experiment():
    consumer_key = session.get('consumer')
    if consumer_key is None:
        return gettext("consumer key not found")
    permission_to_lt_user = PermissionToLtUser.find(key = consumer_key)
    if permission_to_lt_user is None:
        return gettext("permission not found")
    p_to_lt = permission_to_lt_user.permission_to_lt
    courses_configurations = [] # No such concept in the LTI version
    request_payload = {} # This could be populated in the HTML. Pending.
    lt_configuration = p_to_lt.configuration
    db_laboratory     = p_to_lt.laboratory
    db_rlms           = db_laboratory.rlms
    author            = session.get('author_identifier', '(not in session)')
    referer           = request.referrer
    ManagerClass = get_manager_class(db_rlms.kind, db_rlms.version, db_rlms.id)
    remote_laboratory = ManagerClass(db_rlms.configuration)

    request_info = { 
        'user_agent' : unicode(request.user_agent),
        'from_ip'    : remote_addr(),
        'referer'    : referer,
    }
    for key in 'group_name', 'group_id', 'user_fullname':
        if key in session:
            request_info[key] = session[key]
    kwargs = {}
    if 'launch_locale' in session:
        kwargs['locale'] = session['launch_locale'].split('-')[0].split('_')[0]

    response = remote_laboratory.reserve(db_laboratory.laboratory_id,
                                         author,
                                         p_to_lt.lt.name,
                                         lt_configuration,
                                         courses_configurations,
                                         request_payload,
                                         request_info,
                                         **kwargs)
    load_url = response['load_url']
    return redirect(load_url)
Exemplo n.º 8
0
def launch_experiment():
    consumer_key = session.get('consumer')
    if consumer_key is None:
        return gettext("consumer key not found")
    permission_to_lt_user = PermissionToLtUser.find(key=consumer_key)
    if permission_to_lt_user is None:
        return gettext("permission not found")
    p_to_lt = permission_to_lt_user.permission_to_lt
    courses_configurations = []  # No such concept in the LTI version
    request_payload = {}  # This could be populated in the HTML. Pending.
    lt_configuration = p_to_lt.configuration
    db_laboratory = p_to_lt.laboratory
    db_rlms = db_laboratory.rlms
    author = session.get('author_identifier', '(not in session)')
    referer = request.referrer
    ManagerClass = get_manager_class(db_rlms.kind, db_rlms.version, db_rlms.id)
    remote_laboratory = ManagerClass(db_rlms.configuration)

    request_info = {
        'user_agent': unicode(request.user_agent),
        'from_ip': remote_addr(),
        'referer': referer,
    }
    for key in 'group_name', 'group_id', 'user_fullname':
        if key in session:
            request_info[key] = session[key]
    kwargs = {}
    if 'launch_locale' in session:
        kwargs['locale'] = session['launch_locale'].split('-')[0].split('_')[0]

    response = remote_laboratory.reserve(db_laboratory.laboratory_id, author,
                                         p_to_lt.lt.name, lt_configuration,
                                         courses_configurations,
                                         request_payload, request_info,
                                         **kwargs)
    load_url = response['load_url']
    return redirect(load_url)
Exemplo n.º 9
0
def _reserve_impl(lab_name,
                  public_rlms=False,
                  public_lab=False,
                  institution_id=None,
                  rlms_identifier=None,
                  gadget_url_base=None):
    # TODO XXX SECURITY BUG: THIS METHOD DOES NOT USE THE BOOKING THING
    st = request.args.get('st') or ''
    SHINDIG.url = 'http://shindig2.epfl.ch'

    if public_rlms:
        db_rlms = db.session.query(RLMS).filter_by(
            publicly_available=True,
            public_identifier=rlms_identifier).first()
        if db_rlms is None:
            return render_template(
                "opensocial/errors.html",
                message=gettext(
                    "That lab does not exist or it is not publicly available.")
            )
        lab_identifier = lab_name

        ple_configuration = '{}'
        institution_name = 'public-labs'  # TODO: make sure that this name is unique
        courses_configurations = []
        booking_required = False
    else:
        if public_lab:
            db_laboratory = db.session.query(Laboratory).filter_by(
                publicly_available=True, public_identifier=lab_name).first()
            if db_laboratory is None:
                return render_template(
                    "opensocial/errors.html",
                    message=gettext(
                        "That lab does not exist or it is not publicly available."
                    ))

            ple_configuration = '{}'
            institution_name = 'public-labs'  # TODO: make sure that this name is unique
            courses_configurations = []
        else:
            institution = db.session.query(LearningTool).filter_by(
                name=institution_id).first()
            if institution is None or len(institution.shindig_credentials) < 1:
                return render_template(
                    "opensocial/errors.html",
                    message=gettext(
                        "This is not a valid PLE. Make sure that the institution id is fine and that there are Shindig Credentials configured"
                    ))

            SHINDIG.url = institution.shindig_credentials[0].shindig_url

            # Obtain current application data (especially, on which space is the user running it)
            current_app_str = urllib2.urlopen(
                url_shindig('/rest/apps/@self?st=%s' % st)).read()
            current_app_data = json.loads(current_app_str)
            space_id = current_app_data['entry'].get(
                'parentId') or 'null parent'
            parent_type = current_app_data['entry'].get('parentType')
            if parent_type != '@space':
                return render_template(
                    "opensocial/errors.html",
                    message=gettext(
                        "Invalid parent: it should be a space, and it is a %(parenttype)s",
                        parenttype=parent_type))
            # Obtain the list of parent spaces of that space
            spaces = [space_id]
            get_parent_spaces(space_id, spaces)
            # Now, check permissions:
            # First, check if the lab is public (e.g. the lab can be accessed by anyone)
            # Second, check accesibility permissions (e.g. the lab is accessible for everyone from that institution without specifying any Graasp space).
            # After that, in the case that there are not accesibility permissions, check for that institution if there is a permission identified by that lab_name, and check which courses (spaces in OpenSocial) have that permission.
            public_lab_db = db.session.query(Laboratory).filter_by(
                public_identifier=lab_name, publicly_available=True).first()
            courses_configurations = []
            if public_lab_db is None:
                # No public access is granted for the lab, check accesibility permissions
                accessible_permission = db.session.query(
                    PermissionToLt).filter_by(lt=institution,
                                              local_identifier=lab_name,
                                              accessible=True).first()
                if accessible_permission is None:
                    permission = db.session.query(PermissionToLt).filter_by(
                        lt=institution, local_identifier=lab_name).first()
                    if permission is None:
                        return render_template(
                            "opensocial/errors.html",
                            message=gettext(
                                "Your PLE is valid, but don't have permissions for the requested laboratory."
                            ))
                    for course_permission in permission.course_permissions:
                        if course_permission.course.context_id in spaces:
                            # Let the server choose among the best possible configuration
                            courses_configurations.append(
                                course_permission.configuration)
                    if len(courses_configurations) == 0:
                        return render_template(
                            "opensocial/errors.html",
                            message=gettext(
                                "Your PLE is valid and your lab too, but you're not in one of the spaces that have permissions (you are in %(space)r)",
                                space=spaces))
                else:
                    # There is a accesibility permission for that lab and institution
                    permission = accessible_permission

                ple_configuration = permission.configuration
                db_laboratory = permission.laboratory
                institution_name = institution.name
            else:
                # There is a public permission for the lab
                ple_configuration = []
                db_laboratory = public_lab_db
                institution_name = institution.name

        booking_required = db_laboratory.go_lab_reservation
        lab_identifier = db_laboratory.laboratory_id
        db_rlms = db_laboratory.rlms

    if booking_required:
        next_session = check_ils_booking(gadget_url_base)
        if next_session is not None:
            return render_template("opensocial/errors-booking.html",
                                   next_session=next_session)

    # Obtain user data
    if st == 'null' and (public_lab or public_rlms):
        user_id = 'no-id'
    else:
        try:
            current_user_str = urllib2.urlopen(
                url_shindig("/rest/people/@me/@self?st=%s" % st)).read()
            current_user_data = json.loads(current_user_str)
        except:
            traceback.print_exc()
            if public_lab or public_rlms:
                user_id = 'no-id'
            else:
                return render_template(
                    "opensocial/errors.html",
                    message=gettext("Could not connect to %(urlshindig)s.",
                                    urlshindig=url_shindig(
                                        "/rest/people/@me/@self?st=%s" % st)))
        else:
            # name    = current_user_data['entry'].get('displayName') or 'anonymous'
            user_id = current_user_data['entry'].get('id') or 'no-id'

    rlms_version = db_rlms.version
    rlms_kind = db_rlms.kind
    user_agent = unicode(request.user_agent)
    origin_ip = remote_addr()
    referer = request.referrer
    # Load the plug-in for the current RLMS, and instanciate it
    ManagerClass = get_manager_class(rlms_kind, rlms_version, db_rlms.id)
    remote_laboratory = ManagerClass(db_rlms.configuration)

    kwargs = {}

    locale = request.args.get('locale') or None
    if locale:
        kwargs['locale'] = locale

    lab_config = request.args.get('lab_config')
    try:
        lab_config = urllib.unquote(lab_config)
        json.loads(lab_config)  # Verify that it's a valid JSON
    except:
        lab_config = '{}'
    if lab_config:
        request_payload = {'initial': lab_config}
    else:
        request_payload = {}

    try:
        response = remote_laboratory.reserve(
            laboratory_id=lab_identifier,
            username=user_id,
            institution=institution_name,
            general_configuration_str=ple_configuration,
            particular_configurations=courses_configurations,
            request_payload=request_payload,
            user_properties={
                'user_agent': user_agent,
                'from_ip': origin_ip,
                'referer': referer
            },
            back=url_for('.reload', _external=True),
            **kwargs)
    except Exception as e:
        app.logger.error("Error processing request: %s" % e, exc_info=True)
        traceback.print_exc()
        # Don't translate, just in case there are issues with the problem itself
        return render_template(
            "opensocial/errors.html",
            message=
            "There was an error performing the reservation to the final laboratory."
        )
    else:
        if Capabilities.WIDGET in remote_laboratory.get_capabilities():
            reservation_id = response['reservation_id']
        else:
            reservation_id = response['load_url']

        quoted_reservation_id = urllib2.quote(reservation_id, '')
        g4l_session_id = "{0}-{1}-{2}".format(
            quoted_reservation_id, time.time(),
            str(random.randint(0, 9999)).zfill(4))

        return render_template("opensocial/confirmed.html",
                               reservation_id=quoted_reservation_id,
                               g4l_session_id=g4l_session_id,
                               shindig_url=SHINDIG.url)
Exemplo n.º 10
0
def _reserve_json(lab_name, public_rlms = False, public_lab = False, institution_id = None, rlms_identifier = None, gadget_url_base = None):
    # TODO XXX SECURITY BUG: THIS METHOD DOES NOT USE THE BOOKING THING
    st = request.args.get('st') or ''
    SHINDIG.url = 'http://shindig2.epfl.ch'

    if public_rlms:
        db_rlms = db.session.query(RLMS).filter_by(publicly_available = True, public_identifier = rlms_identifier).first()
        if db_rlms is None:
            return jsonify(success=False, message = gettext("That lab does not exist or it is not publicly available."))
        lab_identifier = lab_name

        ple_configuration = '{}'
        institution_name  = 'public-labs' # TODO: make sure that this name is unique
        courses_configurations = []
        booking_required = False
    else:
        if public_lab:
            db_laboratory = db.session.query(Laboratory).filter_by(publicly_available = True, public_identifier = lab_name).first()
            if db_laboratory is None:
                return jsonify(success=False, message = gettext("That lab does not exist or it is not publicly available."))
            
            ple_configuration = '{}'
            institution_name  = 'public-labs' # TODO: make sure that this name is unique
            courses_configurations = []
        else:
            institution = db.session.query(LearningTool).filter_by(name = institution_id).first()
            if institution is None or len(institution.shindig_credentials) < 1:
                return jsonify(success=False, message = gettext("This is not a valid PLE. Make sure that the institution id is fine and that there are Shindig Credentials configured"))

            SHINDIG.url = institution.shindig_credentials[0].shindig_url

            # Obtain current application data (especially, on which space is the user running it)
            current_app_str  = urllib2.urlopen(url_shindig('/rest/apps/@self?st=%s' % st)).read()
            current_app_data = json.loads(current_app_str)
            space_id = current_app_data['entry'].get('parentId') or 'null parent'
            parent_type = current_app_data['entry'].get('parentType')
            if parent_type != '@space':
                return jsonify(success=False, message=gettext("Invalid parent: it should be a space, and it is a %(parenttype)s", parenttype=parent_type))
            # Obtain the list of parent spaces of that space
            spaces = [space_id]
            get_parent_spaces(space_id, spaces)
            # Now, check permissions:
            # First, check if the lab is public (e.g. the lab can be accessed by anyone)
            # Second, check accesibility permissions (e.g. the lab is accessible for everyone from that institution without specifying any Graasp space). 
            # After that, in the case that there are not accesibility permissions, check for that institution if there is a permission identified by that lab_name, and check which courses (spaces in OpenSocial) have that permission.
            public_lab_db = db.session.query(Laboratory).filter_by(public_identifier = lab_name, publicly_available = True).first()
            courses_configurations = []
            if public_lab_db is None:
                # No public access is granted for the lab, check accesibility permissions
                accessible_permission = db.session.query(PermissionToLt).filter_by(lt = institution, local_identifier = lab_name, accessible = True).first()
                if accessible_permission is None:
                    permission = db.session.query(PermissionToLt).filter_by(lt = institution, local_identifier = lab_name).first()
                    if permission is None:
                        return jsonify(success=False, message=gettext("Your PLE is valid, but don't have permissions for the requested laboratory."))
                    for course_permission in permission.course_permissions:
                        if course_permission.course.context_id in spaces:
                            # Let the server choose among the best possible configuration
                            courses_configurations.append(course_permission.configuration)
                    if len(courses_configurations) == 0:
                        return jsonify(success=False, message = gettext("Your PLE is valid and your lab too, but you're not in one of the spaces that have permissions (you are in %(space)r)", space=spaces))
                else:
                    # There is a accesibility permission for that lab and institution
                    permission = accessible_permission

                ple_configuration = permission.configuration
                db_laboratory     = permission.laboratory
                institution_name  = institution.name
            else: 
                # There is a public permission for the lab
                ple_configuration = []
                db_laboratory     = public_lab_db
                institution_name  = institution.name

        lab_identifier = db_laboratory.laboratory_id
        db_rlms = db_laboratory.rlms

    # Obtain user data
    if st == 'null' and (public_lab or public_rlms):
        user_id = 'no-id'
    else:
        try:
            current_user_str  = urllib2.urlopen(url_shindig("/rest/people/@me/@self?st=%s" % st)).read()
            current_user_data = json.loads(current_user_str)
        except:
            traceback.print_exc()
            if public_lab or public_rlms:
                user_id = 'no-id'
            else:
                return jsonify(success=False, message=gettext("Could not connect to %(urlshindig)s.", urlshindig=url_shindig("/rest/people/@me/@self?st=%s" % st)))
        else:
            # name    = current_user_data['entry'].get('displayName') or 'anonymous'
            user_id = current_user_data['entry'].get('id') or 'no-id'

    rlms_version      = db_rlms.version
    rlms_kind         = db_rlms.kind
    user_agent = unicode(request.user_agent)
    origin_ip  = remote_addr()
    referer    = request.referrer
    # Load the plug-in for the current RLMS, and instanciate it
    ManagerClass = get_manager_class(rlms_kind, rlms_version, db_rlms.id)
    remote_laboratory = ManagerClass(db_rlms.configuration)

    kwargs = {}

    locale = request.args.get('locale') or None
    if locale:
        kwargs['locale'] = locale

    lab_config = request.args.get('lab_config')
    try:
        lab_config = urllib.unquote(lab_config)
        json.loads(lab_config) # Verify that it's a valid JSON
    except:
        lab_config = '{}'
    if lab_config:
        request_payload = { 'initial' : lab_config }
    else:
        request_payload = {}

    try:
        response = remote_laboratory.reserve(laboratory_id                = lab_identifier,
                                                username                  = user_id,
                                                institution               = institution_name,
                                                general_configuration_str = ple_configuration,
                                                particular_configurations = courses_configurations,
                                                request_payload           = request_payload,
                                                user_properties           = {
                                                    'user_agent' : user_agent,
                                                    'from_ip'    : origin_ip,
                                                    'referer'    : referer
                                                },
                                                back = url_for('.reload', _external = True),
                                                **kwargs)
    except Exception as e:
        app.logger.error("Error processing request: %s" % e, exc_info = True)
        traceback.print_exc()
        # Don't translate, just in case there are issues with the problem itself
        return jsonify(success=False, message = "There was an error performing the reservation to the final laboratory.")

    if Capabilities.WIDGET in remote_laboratory.get_capabilities():
        reservation_id = response['reservation_id']
    else:
        reservation_id = response['load_url']

    quoted_reservation_id = urllib2.quote(reservation_id, '')
    g4l_session_id = "{0}-{1}-{2}".format(quoted_reservation_id, time.time(), str(random.randint(0, 9999)).zfill(4))

    return jsonify(success=True, reservation_id=quoted_reservation_id, g4l_session_id=g4l_session_id, shindig_url=SHINDIG.url)
Exemplo n.º 11
0
def requests():
    """SCORM packages will perform requests to this method, which will
    interact with the permitted laboratories"""
    
    db_lt = db.session.query(LearningTool).filter_by(name = g.lt).first()
    if request.method == 'GET':
        local_identifiers = [ permission.local_identifier for permission in  db_lt.lab_permissions ]
        return render_template("http/requests.html", local_identifiers = local_identifiers, remote_addr = remote_addr(), courses = db_lt.courses)
    from labmanager.views import get_json
    json_data = get_json()
    if json_data is None:
        return messages_codes["ERROR_json"]
    courses             = json_data['courses']
    request_payload_str = json_data['request-payload']
    general_role        = json_data.get('is-admin', False)
    author              = json_data['user-id']
    complete_name       = json_data['full-name']
    user_agent          = json_data.get('user-agent', 'unknown user agent')
    origin_ip           = json_data.get('origin-ip', 'unknown IP address')
    referer             = json_data.get('referer', 'unknown referer')
    try:
        request_payload = json.loads(request_payload_str)
    except:
        traceback.print_exc()
        return messages_codes["ERROR_invalid_json"]
    try:
        action = request_payload['action']
        if action == 'reserve':
            experiment_identifier = request_payload['experiment']
        else:
            # TODO: other operations: for instructors, booking, etc.
            return messages_codes["ERROR_unsupported"]
    except KeyError:
        traceback.print_exc()
        return messages_codes["ERROR_invalid"]
    # reserving...
    permission_to_lt = db.session.query(PermissionToLt).filter_by(lt = db_lt, local_identifier = experiment_identifier).first()
    good_msg  = messages_codes["ERROR_no_good"]
    error_msg = None
    reservation_url = ""
    if permission_to_lt is None:
        error_msg = messages_codes["ERROR_permission"]
    else:
        courses_configurations = []
        for course_permission in permission_to_lt.course_permissions:
            if course_permission.course.context_id in courses:
                # Let the server choose among the best possible configuration
                courses_configurations.append(course_permission.configuration)                
        if len(courses_configurations) == 0 and not general_role:
            error_msg = messages_codes["ERROR_enrolled"]
        else:
            lt_configuration = permission_to_lt.configuration
            db_laboratory     = permission_to_lt.laboratory
            db_rlms           = db_laboratory.rlms
            rlms_version      = db_rlms.version
            rlms_kind         = db_rlms.kind
            # 
            # Load the plug-in for the current RLMS, and instanciate it
            ManagerClass = get_manager_class(rlms_kind, rlms_version, db_rlms.id)
            remote_laboratory = ManagerClass(db_rlms.configuration)
            
            response = remote_laboratory.reserve(laboratory_id             = db_laboratory.laboratory_id,
                                                        username                  = author,
                                                        institution               = db_lt.name, 
                                                        general_configuration_str = lt_configuration,
                                                        particular_configurations = courses_configurations,
                                                        request_payload           = request_payload,
                                                        user_properties           = {
                                                            'user_agent' : user_agent,
                                                            'from_ip'    : origin_ip,
                                                            'referer'    : referer,
                                                        })
            reservation_url = response['load_url']
            good_msg = messages_codes['MSG_asigned'] % (db_rlms.kind,
                                                        db_rlms.version,
                                                        db_rlms.url,
                                                        reservation_url,
                                                        reservation_url)
    if app.config.get('DEBUGGING_REQUESTS', False):
        rendering_data = {
            'name'        : cgi.escape(complete_name),
            'author'      : cgi.escape(author),
            'lms'         : cgi.escape(g.lt),
            'courses'     : courses,
            'request'     : cgi.escape(request_payload_str),
            'admin'       : general_role,
            'json'        : cgi.escape(json.dumps(json_data)),
            'error_msg'   : cgi.escape(error_msg or 'no error message'),
            'good_msg'    : good_msg or 'no good message',
            }
        return render_template('debug.html', data=rendering_data)
    if error_msg:
        return error_msg
    return reservation_url
Exemplo n.º 12
0
def requests():
    """SCORM packages will perform requests to this method, which will
    interact with the permitted laboratories"""

    db_lt = db.session.query(LearningTool).filter_by(name=g.lt).first()
    if request.method == 'GET':
        local_identifiers = [
            permission.local_identifier for permission in db_lt.lab_permissions
        ]
        return render_template("http/requests.html",
                               local_identifiers=local_identifiers,
                               remote_addr=remote_addr(),
                               courses=db_lt.courses)
    from labmanager.views import get_json
    json_data = get_json()
    if json_data is None:
        return messages_codes["ERROR_json"]
    courses = json_data['courses']
    request_payload_str = json_data['request-payload']
    general_role = json_data.get('is-admin', False)
    author = json_data['user-id']
    complete_name = json_data['full-name']
    user_agent = json_data.get('user-agent', 'unknown user agent')
    origin_ip = json_data.get('origin-ip', 'unknown IP address')
    referer = json_data.get('referer', 'unknown referer')
    try:
        request_payload = json.loads(request_payload_str)
    except:
        traceback.print_exc()
        return messages_codes["ERROR_invalid_json"]
    try:
        action = request_payload['action']
        if action == 'reserve':
            experiment_identifier = request_payload['experiment']
        else:
            # TODO: other operations: for instructors, booking, etc.
            return messages_codes["ERROR_unsupported"]
    except KeyError:
        traceback.print_exc()
        return messages_codes["ERROR_invalid"]
    # reserving...
    permission_to_lt = db.session.query(PermissionToLt).filter_by(
        lt=db_lt, local_identifier=experiment_identifier).first()
    good_msg = messages_codes["ERROR_no_good"]
    error_msg = None
    reservation_url = ""
    if permission_to_lt is None:
        error_msg = messages_codes["ERROR_permission"]
    else:
        courses_configurations = []
        for course_permission in permission_to_lt.course_permissions:
            if course_permission.course.context_id in courses:
                # Let the server choose among the best possible configuration
                courses_configurations.append(course_permission.configuration)
        if len(courses_configurations) == 0 and not general_role:
            error_msg = messages_codes["ERROR_enrolled"]
        else:
            lt_configuration = permission_to_lt.configuration
            db_laboratory = permission_to_lt.laboratory
            db_rlms = db_laboratory.rlms
            rlms_version = db_rlms.version
            rlms_kind = db_rlms.kind
            #
            # Load the plug-in for the current RLMS, and instanciate it
            ManagerClass = get_manager_class(rlms_kind, rlms_version,
                                             db_rlms.id)
            remote_laboratory = ManagerClass(db_rlms.configuration)

            response = remote_laboratory.reserve(
                laboratory_id=db_laboratory.laboratory_id,
                username=author,
                institution=db_lt.name,
                general_configuration_str=lt_configuration,
                particular_configurations=courses_configurations,
                request_payload=request_payload,
                user_properties={
                    'user_agent': user_agent,
                    'from_ip': origin_ip,
                    'referer': referer,
                })
            reservation_url = response['load_url']
            good_msg = messages_codes['MSG_asigned'] % (
                db_rlms.kind, db_rlms.version, db_rlms.url, reservation_url,
                reservation_url)
    if app.config.get('DEBUGGING_REQUESTS', False):
        rendering_data = {
            'name': cgi.escape(complete_name),
            'author': cgi.escape(author),
            'lms': cgi.escape(g.lt),
            'courses': courses,
            'request': cgi.escape(request_payload_str),
            'admin': general_role,
            'json': cgi.escape(json.dumps(json_data)),
            'error_msg': cgi.escape(error_msg or 'no error message'),
            'good_msg': good_msg or 'no good message',
        }
        return render_template('debug.html', data=rendering_data)
    if error_msg:
        return error_msg
    return reservation_url