Python web.input() Examples

The following are 30 code examples of web.input(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module web , or try the search function .
Example #1
Source File: authentication.py    From rucio with Apache License 2.0 7 votes vote down vote up
def POST(self):

        if not EXTRA_MODULES['onelogin']:
            header('X-Rucio-Auth-Token', None)
            return "SAML not configured on the server side."

        SAML_PATH = config_get('saml', 'config_path')
        request = ctx.env
        data = dict(param_input())
        req = prepare_webpy_request(request, data)
        auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)

        auth.process_response()
        errors = auth.get_errors()
        if not errors:
            if auth.is_authenticated():
                setcookie('saml-nameid', value=auth.get_nameid(), path='/') 
Example #2
Source File: utils.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET(self, *args, **kwargs):
        """
        Checks if user is authenticated and calls GET_AUTH or performs logout.
        Otherwise, returns the login template.
        """
        if self.user_manager.session_logged_in():
            if not self.user_manager.session_username() and not self.__class__.__name__ == "ProfilePage":
                raise web.seeother("/preferences/profile")

            if not self.is_lti_page and self.user_manager.session_lti_info() is not None: #lti session
                self.user_manager.disconnect_user()
                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods())

            return self.GET_AUTH(*args, **kwargs)
        elif self.preview_allowed(*args, **kwargs):
            return self.GET_AUTH(*args, **kwargs)
        else:
            error = ''
            if "binderror" in web.input():
                error = _("An account using this email already exists and is not bound with this service. "
                          "For security reasons, please log in via another method and bind your account in your profile.")
            if "callbackerror" in web.input():
                error = _("Couldn't fetch the required information from the service. Please check the provided "
                          "permissions (name, email) and contact your INGInious administrator if the error persists.")
            return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), error) 
Example #3
Source File: main.py    From rucio with Apache License 2.0 6 votes vote down vote up
def GET(self):
        try:
            data = param_input()
            response = get(str(data.file_location), cert=config_get('webui', 'usercert'), verify=False)
            if not response.ok:
                response.raise_for_status()
            cont = response.content
            file_like_object = BytesIO(cont)
            tar = open(mode='r:gz', fileobj=file_like_object)
            jsonResponse = {}
            for member in tar.getmembers():
                jsonResponse[member.name] = member.size
            header('Content-Type', 'application/json')
            return dumps(jsonResponse)
        except ConnectionError as err:
            raise generate_http_error(503, str(type(err)), str(err))
        except TarError as err:
            raise generate_http_error(415, str(type(err)), str(err))
        except IOError as err:
            raise generate_http_error(422, str(type(err)), str(err))
        except Exception as err:
            raise generate_http_error(500, str(type(err)), str(err)) 
Example #4
Source File: submissions.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def POST_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ POST request """
        course, __ = self.get_course_and_check_rights(courseid)
        msgs = []

        if "replay" in web.input():
            if not self.user_manager.has_admin_rights_on_course(course):
                raise web.notfound()

            input = self.get_input()
            tasks = course.get_tasks()
            data, __ = self.get_submissions(course, input)
            for submission in data:
                self.submission_manager.replay_job(tasks[submission["taskid"]], submission)
            msgs.append(_("{0} selected submissions were set for replay.").format(str(len(data))))

        return self.page(course, msgs) 
Example #5
Source File: utils.py    From rucio with Apache License 2.0 6 votes vote down vote up
def userpass_auth(data, rendered_tpl):
    """
    Manages login via Rucio USERPASS method.
    :param data: data object containing account, username and password string
    :param rendered_tpl: rendered page template
    :returns: final page or a page with an error message
    """
    if not data:
        return RENDERER.problem("No input credentials were provided.")
    else:
        # if user tries to access a page through URL without logging in, then redirect to login page.
        if rendered_tpl:
            return RENDERER.login(None)
        if hasattr(data, 'account') and data.account:
            ui_account = data.account
        else:
            ui_account = select_account_name(data.username, 'userpass')
        if not ui_account:
            return RENDERER.problem(('Cannot get find any account associated with %s identity.' % (html_escape(data.username))))
        token = get_token(auth.get_auth_token_user_pass, acc=ui_account, idt=data.username, pwd=data.password.encode("ascii"))
        if not token:
            return RENDERER.problem(('Cannot get auth token. It is possible that the presented identity %s is not mapped to any Rucio account %s.') % (html_escape(data.username), html_escape(ui_account)))
    return finalize_auth(token, 'userpass') 
Example #6
Source File: task_list.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def POST_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ POST request """
        course, __ = self.get_course_and_check_rights(courseid)
        data = web.input(task=[])

        if "task" in data:
            # Change tasks order
            for index, taskid in enumerate(data["task"]):
                try:
                    task = self.task_factory.get_task_descriptor_content(courseid, taskid)
                    task["order"] = index
                    self.task_factory.update_task_descriptor_content(courseid, taskid, task)
                except:
                    pass

        return self.page(course) 
Example #7
Source File: register.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET(self):
        """ Handles GET request """
        if self.user_manager.session_logged_in() or not self.app.allow_registration:
            raise web.notfound()

        error = False
        reset = None
        msg = ""
        data = web.input()

        if "activate" in data:
            msg, error = self.activate_user(data)
        elif "reset" in data:
            msg, error, reset = self.get_reset_data(data)

        return self.template_helper.get_renderer().register(reset, msg, error) 
Example #8
Source File: authentication.py    From rucio with Apache License 2.0 6 votes vote down vote up
def POST(self):

        if not EXTRA_MODULES['onelogin']:
            header('X-Rucio-Auth-Token', None)
            return "SAML not configured on the server side."

        SAML_PATH = config_get('saml', 'config_path')
        request = ctx.env
        data = dict(param_input())
        req = prepare_webpy_request(request, data)
        auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)

        auth.process_response()
        errors = auth.get_errors()
        if not errors:
            if auth.is_authenticated():
                setcookie('saml-nameid', value=auth.get_nameid(), path='/') 
Example #9
Source File: radamsa_server.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def GET(self, extension):
    i = web.input(seed=None)
    if i.seed is None:
      return "No seed specified"
    
    if not re.match("[a-z0-9-_]+", extension, re.IGNORECASE):
      return "Invalid extension"
    
    path = os.path.join(BASE_PATH, extension)
    if not os.path.exists(path) or not os.path.isdir(path):
      return "Extension not found"
    
    cmd = ["radamsa", "-r", path, "-s", i.seed]
    try:
      buf = check_output(cmd)
    except CalledProcessError as e:
      buf = e.output

    return buf 
Example #10
Source File: nightmare_frontend.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def POST(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)
    i = web.input(name="", description="", command="")

    if i.name == "":
      return render.error("No mutation engine name specified")
    elif i.description == "":
      return render.error("No mutation engine description specified")
    elif i.command == "":
      return render.error("No mutation engine command specified")
    elif i.command.find("%OUTPUT%") == -1:
      return render.error("No output mutated filename specified in the mutation engine command")
    
    db = init_web_db()
    with db.transaction():
      db.insert("mutation_engines", name=i.name, command=i.command,
                description=i.description, date=web.SQLLiteral("CURRENT_DATE"))
    return web.redirect("/engines")

#----------------------------------------------------------------------- 
Example #11
Source File: task_edit_file.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid, taskid):  # pylint: disable=arguments-differ
        """ Edit a task """
        if not id_checker(taskid):
            raise Exception("Invalid task id")

        self.get_course_and_check_rights(courseid, allow_all_staff=False)

        request = web.input()
        if request.get("action") == "download" and request.get('path') is not None:
            return self.action_download(courseid, taskid, request.get('path'))
        elif request.get("action") == "delete" and request.get('path') is not None:
            return self.action_delete(courseid, taskid, request.get('path'))
        elif request.get("action") == "rename" and request.get('path') is not None and request.get('new_path') is not None:
            return self.action_rename(courseid, taskid, request.get('path'), request.get('new_path'))
        elif request.get("action") == "create" and request.get('path') is not None:
            return self.action_create(courseid, taskid, request.get('path'))
        elif request.get("action") == "edit" and request.get('path') is not None:
            return self.action_edit(courseid, taskid, request.get('path'))
        else:
            return self.show_tab_file(courseid, taskid) 
Example #12
Source File: nightmare_frontend.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def POST(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)
    i = web.input(id=-1, sure="")
    if i.id == -1:
      return render.error("Invalid project identifier")
    elif i.sure != "on":
      return render.error("You must check the \"I'm sure\" field.")
    
    db = init_web_db()
    with db.transaction():
      vars={"project_id":i.id}
      where = "project_id=$project_id"
      db.delete("projects", where=where, vars=vars)
    return web.redirect("/projects") 
Example #13
Source File: nightmare_frontend.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def POST(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)
    i = web.input(id=-1, name="", description="", command="")
    if i.id == -1:
      return render.error("Invalid mutation engine identifier")
    elif i.name == "":
      return render.error("No mutation engine name specified")
    elif i.description == "":
      return render.error("No mutation engine description specified")
    elif i.command == "":
      return render.error("No mutation engine command specified")
    elif i.command.find("%OUTPUT%") == -1:
      return render.error("No output mutated filename specified in the mutation engine command")
    
    db = init_web_db()
    with db.transaction():
      where = "mutation_engine_id = $id"
      vars = {"id":i.id}
      db.update("mutation_engines", name=i.name, command=i.command,
                description=i.description, where=where, vars=vars)
    return web.redirect("/engines") 
Example #14
Source File: nightmare_frontend.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def GET(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)
    i = web.input(id=-1)
    if i.id == -1:
      return render.error("Invalid project identifier")
    
    db = init_web_db()
    what = "mutation_engine_id, name, description, command, date"
    where = "mutation_engine_id = $id"
    vars = {"id":i.id}
    res = db.select("mutation_engines", what=what, where=where, vars=vars)
    res = list(res)
    if len(res) == 0:
      return render.error("Invalid mutation engine identifier")
    return render.edit_mutation_engine(res[0])

#----------------------------------------------------------------------- 
Example #15
Source File: download.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course, __ = self.get_course_and_check_rights(courseid)
        user_input = web.input(tasks=[], aggregations=[], users=[])
        error = ""

        # First, check for a particular submission
        if "submission" in user_input:
            submission = self.database.submissions.find_one({"_id": ObjectId(user_input.submission),
                                                             "courseid": course.get_id(),
                                                             "status": {"$in": ["done", "error"]}})
            if submission is None:
                raise web.notfound()

            self._logger.info("Downloading submission %s - %s - %s - %s", submission['_id'], submission['courseid'],
                              submission['taskid'], submission['username'])
            archive, error = self.submission_manager.get_submission_archive(course, [submission], [])
            if not error:
                web.header('Content-Type', 'application/x-gzip', unique=True)
                web.header('Content-Disposition', 'attachment; filename="submissions.tgz"', unique=True)
                return archive

        # Else, display the complete page
        return self.display_page(course, user_input, error) 
Example #16
Source File: nightmare_frontend.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def GET(self):
    i = web.input()
    if not i.has_key("id"):
      return render.error("No crash identifier given")

    # XXX: FIXME: Joxean, why do 2 queries instead of one????
    # Get the project_id from the crash_id
    crash_id = i.id
    db = init_web_db()
    vars = {"id":crash_id}
    res = db.select("crashes", where="crash_id=$id", vars=vars)
    crash_row = res[0]

    # Get the project name
    where = "crash_id < $id and project_id = $project_id"
    vars = {"project_id":crash_row.project_id, "id":crash_id}
    rows = db.select("crashes", what="crash_id", where=where, vars=vars, order="crash_id desc")
    if len(rows) > 0:
      crash_id = rows[0].crash_id
      return render_crash(crash_id)
    else:
      return render.error("No more crashes for this project")

#----------------------------------------------------------------------- 
Example #17
Source File: group_edit.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid, groupid=''):  # pylint: disable=arguments-differ
        """ Edit a group """
        course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True)

        if course.is_lti():
            raise web.notfound()

        if "download" in web.input():
            web.header('Content-Type', 'text/x-yaml', unique=True)
            web.header('Content-Disposition', 'attachment; filename="groups.yaml"', unique=True)
            groups = [{"description": group["description"],
                           "students": group["students"],
                           "size": group["size"],
                            "audiences": [str(c) for c in group["audiences"]]} for group in
                          self.user_manager.get_course_groups(course)]

            return yaml.dump(groups)

        return self.display_page(course) 
Example #18
Source File: danger_zone.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)

        data = web.input()

        if "download" in data:
            filepath = os.path.join(self.backup_dir, courseid, data["download"] + '.zip')

            if not os.path.exists(os.path.dirname(filepath)):
                raise web.notfound()

            web.header('Content-Type', 'application/zip', unique=True)
            web.header('Content-Disposition', 'attachment; filename="' + data["download"] + '.zip' + '"', unique=True)

            return open(filepath, 'rb')

        else:
            return self.page(course) 
Example #19
Source File: app.py    From OsmocomBB_Raspberry-Pi_SMS_WEB_CODE with MIT License 6 votes vote down vote up
def POST(self):
		deviceId = str(web.input().get('devid'))
		try:
			devIndex = deviceId.split('USB')[1]
			cellLogshell = [sys.path[0]+"/osmocombb_x64/cell_log","-s","/tmp/osmocom_l2_"+ devIndex,"-O"];
			arfcnScan = subprocess.Popen(cellLogshell,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
			scanlog = arfcnScan.communicate()
			arfcnScan.wait()
			scanloginfo = ";".join(scanlog)
			scanbase = re.findall(r"ARFCN\=[^)]+\)",scanloginfo)

			logfile = file(sys.path[0]+"/arfcn_"+ devIndex +".log","w+")
			for line in scanbase:
				logfile.write(str(line)+"\r\n")
			logfile.write('Date: '+GetCurrentTime())
			logfile.close()
		except Exception,e:
			return json.dumps({"res":-1,"msg":str(e)}) 
Example #20
Source File: cookieless_app.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def _delegate(self, f, fvars, args=None):
        if args is None:
            args = [None]

        # load session
        if args[0] == "/@@":
            self._session.load('') # creates a new session
            raise web.redirect("/@" + self._session.session_id + "@"+web.ctx.fullpath[3:]) # redirect to the same page, with the new
            # session id
        elif args[0] is None:
            self._session.load(None)
        else:
            self._session.load(args[0][2:len(args[0])-1])

        # Switch language if specified
        input_data = web.input()
        if "lang" in input_data:
            self._session.language = input_data["lang"]
        elif "language" not in self._session:
            for lang in re.split("[,;]+", web.ctx.environ.get("HTTP_ACCEPT_LANGUAGE", "")):
                if lang in self._translations.keys():
                    self._session.language = lang
                    break

        return super(CookieLessCompatibleApplication, self)._delegate(f, fvars, args[1:]) 
Example #21
Source File: authentication.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def API_POST(self):  # pylint: disable=arguments-differ
        """
            Authenticates the remote client. Takes as input:

            login
                the INGInious account login

            password
                the associated password

            Response: a dict in the form {"status": "success"} (200 OK) or {"status": "error"} (403 Forbidden)
        """

        user_input = web.input()
        if "login" not in user_input or "password" not in user_input:
            raise APIInvalidArguments()

        try:
            if self.user_manager.auth_user(user_input["login"].strip(), user_input["password"]) is not None:
                    return 200, {"status": "success", "username": self.user_manager.session_username()}
        except:
            pass
        return 403, {"status": "error"} 
Example #22
Source File: utils.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def POST(self, *args, **kwargs):
        """
        Checks if user is authenticated and calls POST_AUTH or performs login and calls GET_AUTH.
        Otherwise, returns the login template.
        """
        if self.user_manager.session_logged_in():
            if not self.user_manager.session_username() and not self.__class__.__name__ == "ProfilePage":
                raise web.seeother("/preferences/profile")

            if not self.is_lti_page and self.user_manager.session_lti_info() is not None:  # lti session
                self.user_manager.disconnect_user()
                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods_fields())

            return self.POST_AUTH(*args, **kwargs)
        else:
            user_input = web.input()
            if "login" in user_input and "password" in user_input:
                if self.user_manager.auth_user(user_input["login"].strip(), user_input["password"]) is not None:
                    return self.GET_AUTH(*args, **kwargs)
                else:
                    return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), _("Invalid login/password"))
            elif self.preview_allowed(*args, **kwargs):
                return self.POST_AUTH(*args, **kwargs)
            else:
                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods()) 
Example #23
Source File: mycourses.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self):  # pylint: disable=arguments-differ
        """ Parse course registration or course creation and display the course list page """

        user_input = web.input()
        success = None

        if "new_courseid" in user_input and self.user_manager.user_is_superadmin():
            try:
                courseid = user_input["new_courseid"]
                self.course_factory.create_course(courseid, {"name": courseid, "accessible": False})
                success = True
            except:
                success = False

        return self.show_page(success) 
Example #24
Source File: task_edit_file.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self, courseid, taskid):  # pylint: disable=arguments-differ
        """ Upload or modify a file """
        if not id_checker(taskid):
            raise Exception("Invalid task id")

        self.get_course_and_check_rights(courseid, allow_all_staff=False)

        request = web.input(file={})
        if request.get("action") == "upload" and request.get('path') is not None and request.get('file') is not None:
            return self.action_upload(courseid, taskid, request.get('path'), request.get('file'))
        elif request.get("action") == "edit_save" and request.get('path') is not None and request.get('content') is not None:
            return self.action_edit_save(courseid, taskid, request.get('path'), request.get('content'))
        else:
            return self.show_tab_file(courseid, taskid) 
Example #25
Source File: profile.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self):  # pylint: disable=arguments-differ
        """ POST request """
        userdata = self.database.users.find_one({"email": self.user_manager.session_email()})

        if not userdata:
            raise web.notfound()

        msg = ""
        error = False
        data = web.input()
        if "save" in data:
            userdata, msg, error = self.save_profile(userdata, data)

        return self.template_helper.get_renderer().preferences.profile(msg, error) 
Example #26
Source File: lti.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self):
        input_data = web.input()
        if "sessionid" not in input_data:
            return self.template_helper.get_renderer().lti_bind(False, "", None, _("Missing LTI session id"))

        try:
            cookieless_session, data = self.fetch_lti_data(input_data["sessionid"])
        except KeyError:
            return self.template_helper.get_renderer().lti_bind(False, "", None, _("Invalid LTI session id"))

        try:
            course = self.course_factory.get_course(data["task"][0])
            if data["consumer_key"] not in course.lti_keys().keys():
                raise Exception()
        except:
            return self.template_helper.get_renderer().lti_bind(False, "", None, _("Invalid LTI data"))

        if data:
            user_profile = self.database.users.find_one({"username": self.user_manager.session_username()})
            lti_user_profile = self.database.users.find_one(
                {"ltibindings." + data["task"][0] + "." + data["consumer_key"]: data["username"]})
            if not user_profile.get("ltibindings", {}).get(data["task"][0], {}).get(data["consumer_key"],
                                                                                    "") and not lti_user_profile:
                # There is no binding yet, so bind LTI to this account
                self.database.users.find_one_and_update({"username": self.user_manager.session_username()}, {"$set": {
                    "ltibindings." + data["task"][0] + "." + data["consumer_key"]: data["username"]}})
            elif not (lti_user_profile and user_profile["username"] == lti_user_profile["username"]):
                # There exists an LTI binding for another account, refuse auth!
                self.logger.info("User %s tried to bind LTI user %s in for %s:%s, but %s is already bound.",
                                 user_profile["username"],
                                 data["username"],
                                 data["task"][0],
                                 data["consumer_key"],
                                 user_profile.get("ltibindings", {}).get(data["task"][0], {}).get(data["consumer_key"], ""))
                return self.template_helper.get_renderer().lti_bind(False, cookieless_session["session_id"],
                                                                    data, _("Your account is already bound with this context."))

        return self.template_helper.get_renderer().lti_bind(True, cookieless_session["session_id"], data, "") 
Example #27
Source File: delete.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_account(self, data):
        """ Delete account from DB """
        error = False
        msg = ""

        username = self.user_manager.session_username()

        # Check input format
        result = self.database.users.find_one_and_delete({"username": username,
                                                          "email": data.get("delete_email", "")})
        if not result:
            error = True
            msg = _("The specified email is incorrect.")
        else:
            self.database.submissions.remove({"username": username})
            self.database.user_tasks.remove({"username": username})

            all_courses = self.course_factory.get_all_courses()

            for courseid, course in all_courses.items():
                if self.user_manager.course_is_open_to_user(course, username):
                    self.user_manager.course_unregister_user(course, username)

            self.user_manager.disconnect_user()
            raise web.seeother("/index")

        return msg, error 
Example #28
Source File: delete.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self):  # pylint: disable=arguments-differ
        """ POST request """
        userdata = self.database.users.find_one({"username": self.user_manager.session_username()})

        if not userdata or not self.app.allow_deletion:
            raise web.notfound()

        msg = ""
        error = False
        data = web.input()
        if "delete" in data:
            msg, error = self.delete_account(data)

        return self.template_helper.get_renderer().preferences.delete(msg, error) 
Example #29
Source File: main.py    From jingwei with MIT License 5 votes vote down vote up
def GET(self):
        input = web.input(query=None)
        resp = {'status':0, 'hits':0, 'random':[], 'tagrel':[], 'metric':metric, 'perf':0}

        if input.query:
            resp['status'] = 1
            resp['query'] = input.query
            query = input.query.lower()

            if query.isdigit(): # request to view a specific image
                resp['hits'] = 1
                resp['tagrel'] = [{'id':query}]
                return  render.index(resp)
            
            try:
                names,labels = readAnnotationsFrom(collection, annotationName, query)
                name2label = dict(zip(names,labels))
            except Exception, e:
                name2label = {}

            content = []
            try:
                if input.tagrel == '0':
                    labeled = readLabeledImageSet(collection, query, rootpath=rootpath)
                    ranklist = [(x,0) for x in labeled]
                else:
                    simfile = os.path.join(simdir, '%s.txt' % query)
                    ranklist = readRankingResults(simfile)
                resp['hits'] = len(ranklist)
                for name,score in ranklist:
                    color = 'Chartreuse' if name2label.get(name,0)>0 else 'red'
                    color = 'white' if name not in name2label else color
                    res = {'id':name, 'color':color}
                    content.append(res)
                resp['perf'] = 0 if not name2label else scorer.score([name2label[x[0]] for x in ranklist if x[0] in name2label])
                resp['tagrel'] = content[:max_hits]
            except:
                None 
Example #30
Source File: bindings.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self):  # pylint: disable=arguments-differ
        """ POST request """
        msg = ""
        error = False

        user_data = self.database.users.find_one({"username": self.user_manager.session_username()})

        if not user_data:
            raise web.notfound()

        user_input = web.input()
        auth_methods = self.user_manager.get_auth_methods()

        if "auth_binding" in user_input:
            auth_binding = user_input["auth_binding"]

            if auth_binding not in auth_methods.keys():
                error = True
                msg = _("Incorrect authentication binding.")
            elif auth_binding not in user_data.get("bindings", {}):
                raise web.seeother("/auth/signin/" + auth_binding)
        elif "revoke_auth_binding" in user_input:
            auth_id = user_input["revoke_auth_binding"]

            if auth_id not in auth_methods.keys():
                error = True
                msg = _("Incorrect authentication binding.")
            elif len(user_data.get("bindings", {}).keys()) > 1 or "password" in user_data:
                user_data = self.database.users.find_one_and_update(
                    {"username": self.user_manager.session_username()},
                    {"$unset": {"bindings." + auth_id: 1}},
                    return_document=ReturnDocument.AFTER)
            else:
                error = True
                msg = _("You must set a password before removing all bindings.")

        bindings = user_data.get("bindings", {})

        return self.template_helper.get_renderer().preferences.bindings(bindings, auth_methods, msg, error)