示例#1
0
文件: auth_page.py 项目: jelford/reef
    def GET(self, request):
        """
        Get a particular page.

        The handler will take anything after the base address and look for it
        in the pages folder. This folder is stored in the :mod:`config` module
        at::

            config.getSettings("server")["pagedir"]

        If a file is not found the handler will assume the address is a
        directory and try to serve the file index.html from it.

        :returns: The requested file.
        :raises: :exc:`restlite.Status` 400 if the path contains ".."

                 :exc:`restlite.Status` 404 if the file is not found.

        """

        authentication.login(request)

        if '..' in request['PATH_INFO']:
            raise restlite.Status, '400 Invalid Path'

        page_file = os.path.join(
            config.getSettings("global")["basedir"],
            config.getSettings("server")["pagedir"],
            request['PATH_INFO']
        )
        try:
            return request.response(self.getPage(page_file), self.getType(page_file))
        except restlite.Status:
            index_page = os.path.join(page_file, 'index.html')
            return request.response(self.getPage(index_page), 'text/html')
示例#2
0
文件: settings.py 项目: jelford/reef
    def GET(self, request):
        """
        Get setting data from the :mod:`config`.

        Parameters are expected to be part of the query string.

        If the base of this address handler is called:

        :returns: A list of sections in the :mod:`config`
        :rtype: ``list``

        If anything more than the base of this handler is called then the
        excess is assumed to be a section name and:

        :returns: A JSON representation of that particular section of the 
                  :mod:`config`.
        :rtype: ``json``
        :raises: :exc:`restlite.Status` 404 if the section does not exist.

        """

        authentication.login(request)
        section = getSection(request['PATH_INFO'])
        if section:
            settings = config.getSettings(section, False)
            if settings is None:
                raise restlite.Status, "404 Not Found"
            else:
                return request.response(settings)
        else:
            return request.response(config.getSections())
示例#3
0
 def POST(request,entity):
     authentication.login(request)
 
     groups = config.getSettings("groups")
 
     fields = parseMultipart(request, entity)
     if fields is None:
         raise restlite.Status, "400 Invalid SUE POST request - need parameters"
 
     # Try to find what we should label the component
     component_name = fields.getfirst("component_name")
     if not component_name:
         raise restlite.Status, "400 Must give the SUE component a name"
 
     # Try to get the SUE component
     try:
         component_f = fields['component_file']
     except KeyError:
         raise restlite.Status, "400 Must provide a file when specifying a SUE component"
 
     if component_f.file:
         component = component_f.file.read()
         saveSueComponent(component_name, component)
     else:
         raise restlite.Status, "400 The supplied \"component_file\" was not a file"
 
 
     return request.response("", "text/plain")
示例#4
0
文件: workloads.py 项目: OhBaby/reef
    def POST(request, entity):
        authentication.login(request)

        fields = parseMultipart(request, entity)
        if fields is None:
            raise restlite.Status, "400 Invalid Request"

        # Try to pull a name
        wkldname = fields.getfirst("wkld_name")
        if not wkldname:
            raise restlite.Status, "400 No Workload Name"
        # Uncomment below to ban editing old workloads
        #elif wkldname in config.getSettings("workloads")["defs"]:
        #    raise restlite.Status, "403 Name Reuse Forbidden"

        # Try to get text for the workload
        wkld = fields.getfirst("wkld_text")
        if wkld is None:
            # Couldn't so try to get text from file
            try:
                wkld_f = fields['wkld_file']
                if wkld_f.file:
                    wkld = wkld_f.file.read()
            except KeyError: pass

        # Still couldn't get text
        if wkld is None:
            raise restlite.Status, "400 No Workload Supplied"

        saveWorkload(wkldname, wkld)
        return request.response("", "text/plain")
示例#5
0
文件: groups.py 项目: OhBaby/reef
  def POST(request,entity):
    authentication.login(request)

    existing_groups = config.getSettings("groups")
    group_name = request['PATH_INFO']

    args = urlparse.parse_qs(entity)

    g_data = _getGroupDataFromArgs(args)

    if group_name in existing_groups:
      if "size" in g_data and g_data["size"] == 0:
        # Delete the group
        del existing_groups[group_name]
      else:
        existing_groups[group_name].update(g_data)
    else:
      # New group
      n_group = __newGroup()
      n_group["name"] = group_name
      n_group.update(g_data)
      if n_group["size"] != 0:
        existing_groups[group_name] = n_group
    
    #print config.getSettings

    try:
      return request.response(existing_groups[group_name])
    except KeyError:
      return request.response({"name":group_name, "size":0})
示例#6
0
文件: workloads.py 项目: jelford/reef
    def POST(self, request, entity):
        """
        Create a new or update an existing workload.

        Anything requested after the base address of this handler is assumed to
        be the workload name. This is expected to be called at the base address
        of this handler with multipart form data encoding.

        :param wkld_name: The name of the workload being modified.
        :type wkld_name: ``str``
        :param wkld_file: The workload file being uploaded.
        :type wkld_file: As POSTed from a HTML file upload form.
        :param wkld_text: Actual text for the workload being uploaded.
        :type wkld_text: ``str``

        Only one of ``wkld_file`` or ``wkld_text`` have to be given. If both are
        received then the text will take priority.

        :returns: The name of the modifed workload.
        :raises: :exc:`restlite.Status` 400 if the entity could not be parsed.

                 :exc:`restlite.Status` 403 if editing of workload is not
                 permitted and you have tried to reuse a name.

                 :exc:`restlite.Status` 400 if valid workload content could
                 not be found.

        """

        authentication.login(request)

        fields = parseMultipart(request, entity)
        if fields is None:
            raise restlite.Status, "400 Invalid Request"

        # Try to pull a name
        wkldname = fields.getfirst("wkld_name")
        if not wkldname:
            raise restlite.Status, "400 No Workload Name"
        # Uncomment below to ban editing old workloads
        #elif wkldname in config.getSettings("workloads")["defs"]:
        #    raise restlite.Status, "403 Name Reuse Forbidden"

        # Try to get text for the workload
        wkld = fields.getfirst("wkld_text")
        if wkld is None:
            # Couldn't so try to get text from file
            try:
                wkld_f = fields['wkld_file']
                if wkld_f.file:
                    wkld = wkld_f.file.read()
            except KeyError: pass

        # Still couldn't get text
        if wkld is None:
            raise restlite.Status, "400 No Workload Supplied"

        saveWorkload(wkldname, wkld)
        return request.response(wkldname, "text/html")
示例#7
0
文件: settings.py 项目: OhBaby/reef
    def POST(request, entity):
        authentication.login(request)
        section = getSection(request['PATH_INFO'])
        # Uncomment below to disallow editing of new sections
        #if not section:
        #    raise restlite.Status, '403 New Section Forbidden'

        # Grab arguments
        import urlparse
        parsed = urlparse.parse_qs(entity, True) # Null value is kept as ''
        used_names = [] # Names used
        new_qs = {} # Values to add
        rem_qs = [] # Values to delete

        for key in parsed:
            # Grab name and extension
            name, ext = splitName(key)
            # If name already used, ignore
            if name in used_names:
                continue
            # If theres no extension ignore
            if ext is None:
                continue
            # If there is no value at all, skip
            if parsed[key] == []:
                continue
            # Otherwise take first value
            q = parsed[key][0]
            # If up for deletion
            if ext is 'r':
                # Check used_names here as we use key when deleting
                # Or parsed name otherwise below
                rem_qs += [name]
                used_names += [name]
            # Adding value
            else:
                # Try to convert to the correct format
                func = funcFor(ext)
                if func is None:
                    raise restlite.Status, "400 Invalid Action"
                try:
                    q = func(q)
                except:
                    raise restlite.Status, "400 Invalid Format"
                new_qs[name] = q
                used_names += [name]

        # All settings are good to go
        settings = config.getSettings(section)
        # Add all new settings
        settings.update(new_qs)
        # Delete all new deletions
        for key in rem_qs:
            try:
                del settings[key]
            except KeyError: pass
        # Make it permanent
        config.saveConfig()
        return request.response(settings)
示例#8
0
 def POST(request,entity):
   authentication.login(request)
   
   os_call_to_vazels = vazelsmanager.stopVazels()
   
   if os_call_to_vazels is True :
     return request.response("")
   else :
     raise restlite.Status("500 "+str(os_call_to_vazels))
示例#9
0
 def GET(request):
   authentication.login(request)
   runningState = vazelsmanager.vazelsRunning()
   if runningState is True:
     return request.response({"control_centre_status": "running"})
   elif runningState is False:
     return request.response({"control_centre_status": "ready"})
   else:
     return request.response({"control_centre_status": runningState})
示例#10
0
 def POST(request, entity):
   authentication.login(request)
     
   os_call_to_vazels = vazelsmanager.runVazels()
     
   if os_call_to_vazels :
     # Need to upadate client to handle 204 as a successful response
     return request.response("")
   else :
     raise restlite.Status("500 Vazels Control Centre failed to start")
示例#11
0
文件: settings.py 项目: OhBaby/reef
 def GET(request):
     authentication.login(request)
     section = getSection(request['PATH_INFO'])
     if section:
         settings = config.getSettings(section, False)
         if settings is None:
             raise restlite.Status, "404 Not Found"
         else:
             return request.response(settings)
     else:
         return request.response(config.getSections())
示例#12
0
文件: groups.py 项目: OhBaby/reef
  def GET(request):
    authentication.login(request)
   
    # To find info on a group call /groups/groupName
    group_name = request['PATH_INFO']

    try:
      group_settings = config.getSettings("groups",True)[group_name]
      return request.response(group_settings)
    # Return 404 if they use an invalid group name
    except KeyError:
      raise restlite.Status, "404 Group Not Found"
示例#13
0
文件: status.py 项目: jelford/reef
    def GET(self, request):
        """
        Check if the server is alive.

        :returns: Code \"200 OK\" if alive.

        Obviously if the server is down it will not respond.

        """

        authentication.login(request)
        return restlite.response("")
示例#14
0
    def cookie(self):
        request_cookie = cherrypy.request.cookie
        cookie_val = request_cookie.get(COOKIE_NAME).value.split('|')

        if len(cookie_val) == 2:
            username, cookie_id = cookie_val
            user = UserDao.get_user(username)

            if user.get('cookie_id') and user.get('cookie_expire'):
                if user['cookie_id'] == cookie_id and datetime_to_unix(user.get('cookie_expire')) > time.time():
                    authentication.login(cherrypy.session, user)
                    return OkResponse('ok')
        return ConflictResponse('error')
示例#15
0
文件: groups.py 项目: jelford/reef
    def GET(self, request):
        """
        Get the list of groups on the server.

        :returns: A list of groups.
        :rtype: ``list``

        """

        authentication.login(request)
        group_data = config.getSettings("groups").keys()

        return request.response(group_data)
示例#16
0
文件: groups.py 项目: jelford/reef
    def POST(self, request, entity):
        """
        Create a new or edit an existing group.

        The group name is taken to be anything in the requested path after
        the base address of the handler.        

        Parameters are expected to be part of the POST entity.

        :param size: Group size.
        :type size: ``int``
        :param workloads: Can be included any number of times, each should be
                          the name of an attached workload.
        :type workloads: ``str``
        :param filters: Can be included any number of times, each should be a
                        mapping restriction.
        :type filters: ``str``
        :returns: JSON representation of the new state of the group.
        :rtype: ``dict``
        :raises: :exc:`restlite.Status` 400 if the size is invalid.

                 :exc:`restlite.Status` 400 unrecognised parameters are
                 included.

        """

        authentication.login(request)

        existing_groups = config.getSettings("groups")
        group_name = request['PATH_INFO']

        args = urlparse.parse_qs(entity)
        g_data = _getGroupDataFromArgs(args)

        if group_name in existing_groups:
            if "size" in g_data and g_data["size"] == 0:
                # Delete the group
                del existing_groups[group_name]
            else:
                existing_groups[group_name].update(g_data)
        else:
            # New group
            n_group = Group(group_name)
            n_group.update(g_data)
            if n_group["size"] != 0:
                existing_groups[group_name] = n_group

        try:
            return request.response(existing_groups[group_name])
        except KeyError:
            return request.response({"name":group_name, "size":0})
示例#17
0
文件: auth_page.py 项目: OhBaby/reef
    def GET(request):
        authentication.login(request)

        if ".." in request["PATH_INFO"]:
            raise restlite.Status, "400 Invalid Path"

        page_file = os.path.join(
            config.getSettings("global")["basedir"], config.getSettings("server")["pagedir"], request["PATH_INFO"]
        )
        try:
            return request.response(getPage(page_file), getType(page_file))
        except restlite.Status:
            index_page = os.path.join(page_file, "index.html")
            return request.response(getPage(index_page), "text/html")
示例#18
0
 def GET(request):
     authentication.login(request)
     groups = config.getSettings("groups")
 
     #component_info = {}
 
     # For each component, build a list of groups to which it is assigned.
     #for component_name in config.getSettings("SUE")["defs"]:
     #    assigned_groups = []
     #    for group in groups:
     #        if component_name in groups[group]["sue_components"]:
     #          assigned_groups.append(group)
     #        component_info[component_name] = assigned_groups
 
     #return request.response(component_info)
     return request.response(config.getSettings("SUE")["defs"].keys(), 'text/html')
示例#19
0
def index():
    if 'username' in session:
        # If there is a next request use that.  See issue #76
        if 'next' in request.args:
            response = redirect(request.values.get('next', ''))
            return response
        response = redirect(url_for('worksheet_listing.home', username=session['username']))
        if 'remember' in request.args:
            response.set_cookie('nb_session_%s'%g.notebook.port,
                                expires=(time.time() + 60 * 60 * 24 * 14))
        else:
            response.set_cookie('nb_session_%s'%g.notebook.port)
        response.set_cookie('cookie_test_%s'%g.notebook.port, expires=1)
        return response

    from authentication import login

    if current_app.startup_token is not None and 'startup_token' in request.args:
        if request.args['startup_token'] == current_app.startup_token:
            g.username = session['username'] = '******'
            session.modified = True
            current_app.startup_token = None
            return index()

    return login()
示例#20
0
def index():
    if 'username' in session:
        # If there is a next request use that.  See issue #76
        if 'next' in request.args:
            response = redirect(request.values.get('next', ''))
            return response
        response = redirect(url_for('worksheet_listing.home', username=session['username']))
        if 'remember' in request.args:
            response.set_cookie('nb_session_%s'%g.notebook.port,
                                expires=(time.time() + 60 * 60 * 24 * 14))
        else:
            response.set_cookie('nb_session_%s'%g.notebook.port)
        response.set_cookie('cookie_test_%s'%g.notebook.port, expires=1)
        return response

    from authentication import login

    if current_app.startup_token is not None and 'startup_token' in request.args:
        if request.args['startup_token'] == current_app.startup_token:
            g.username = session['username'] = '******'
            session.modified = True
            current_app.startup_token = None
            return index()

    return login()
示例#21
0
文件: actors.py 项目: jelford/reef
    def GET(self, request):
        """
        Get either the list of actors or actor details.

        If the base address of the handler is requested:

        :returns: List of actors on the server.

        If the base / actorname is requested:

        :returns: JSON representation of the actor called actorname
        :raises: :exc:`restlite.Status` 404 if the actor does not exist.

        If the base / actorname.tar.gz is requested:

        :returns: The contents of the actor file.
        :raises: :exc:`restlite.Status` 404 if the actor does not exist.

                 :exc:`restlite.Status` 410 if the actor exists but the
                 file is missing.

                 :exc:`restlite.Status` 500 if the actor file could not
                 be read.

        """

        authentication.login(request)

        actor = request['PATH_INFO']
        namemap = config.getSettings("actors")["defs"]

        # Asking for names of actors
        if not actor:
            return request.response(namemap.keys())

        # Asking for the file
        if actor.endswith(".tar.gz"):
            actorname = actor[:len(actor)-len(".tar.gz")]
            return self.showActorFile(request, actorname)

        # Asking for the actor info
        if actor not in namemap:
            raise restlite.Status, "404 Not Found"

        actordata = namemap[actor].copy()
        del actordata['file']
        return request.response(actordata)
示例#22
0
    def POST(request, entity):
        authentication.login(request)

        import urlparse

        args = urlparse.parse_qs(entity, True)

        # Only accept a single value for any parameter
        for key in args:
            if len(args[key]) > 1:
                raise restlite.Status, "400 Duplicate Arguments"
            args[key] = args[key][0]

        # Check for action
        if "do" not in args:
            raise restlite.Status, "400 Missing Action"

        # Check for workload
        if "workload" not in args:
            raise restlite.Status, "400 Missing Workload"

        # Check for actor
        if "actor" not in args:
            raise restlite.Status, "400 Missing Actor"

        do = args["do"].lower()
        workload = args["workload"]
        actor = args["actor"]

        # Validate workload
        if workload not in config.getSettings("workloads")["defs"]:
            raise restlite.Status, "404 Workload Not Found"

        # Validate actor
        if actor not in config.getSettings("actors")["defs"]:
            raise restlite.Status, "404 Actor Not Found (" + actor + ")"

        workload = config.getSettings("workloads")["defs"][workload]

        try:
            {"add": addActor, "rem": remActor}[do](workload, actor)
        except KeyError:
            raise restlite.Status, "400 Invalid Action"

        config.saveConfig()

        return request.response(workload)
示例#23
0
    def GET(self, request):
        """
        Get the status of the vazels control centre.

        :returns: The current control centre status, either

                  * ``"{'control_centre_status': 'running'}"``
                  * ``"{'control_centre_status': 'ready'}"``
                  * ``"{'control_centre_status': <somethingelse>}"``

                  where ``<somethingelse>`` is a return value of
                  :func:`vazelsmanager.vazelsRunning()`

        """

        authentication.login(request)
        return request.response({"control_centre_status": commandclient.vazelsPhase()})
示例#24
0
    def GET(self, request):
        """
        Grab the latest output from the vazels experiment.

        .. todo:: Make this POST!
        .. todo:: Allow 204 as success in the client.

        :raises: :exc:`restlite.Status` 400 if we could not start to
                 retrieve data.

        """

        authentication.login(request)

        if commandclient.getalloutput():
            return request.response("")
        else:
            raise restlite.Status, "400 Failed to get output from Vazels - don't call this before starting the Control Center"
示例#25
0
    def POST(self, request, entity):
        """
        Try to start a vazels experiment.

        .. todo:: Make this POST!
        .. todo:: Allow 204 as success in the client.

        :raises: :exc:`restlite.Status` 400 if the attempt to start an
                 experiment failed immediately.

        """

        authentication.login(request)

        if commandclient.startexperiment():
            return request.response("")
        else:
            raise restlite.Status, "400 Failed to start experiment - don't call this before starting the Control Center"
示例#26
0
    def POST(self, request, entity):
        """
        Stop the control centre.

        :raises: :exc:`restlite.Status` 500 if something went immediately
                 wrong while stopping the control centre.

        .. todo:: Update client to handle 204 as a successful response.
                  Then we dont have to send 200 with a blank response.

        """

        authentication.login(request)

        if commandclient.stopVazels():
            return request.response("")
        else :
            raise restlite.Status("500 Cannot Stop Non Running Control Centre")
示例#27
0
    def GET(self, request):
        """
        Update the groups with host statuses.

        .. todo:: Make this POST!
        .. todo:: Allow 204 as success in the client.

        :raises: :exc:`restlite.Status` 400 if we cannot initiate an attempt
                 to update.

        """

        authentication.login(request)

        if commandclient.updateStatuses():
            return request.response("")
        else:
            raise restlite.Status, "400 Failed to send getallstatus request - don't call this before starting the Control Center"
示例#28
0
    def POST(self, request, entity):
        """
        Start the control centre.

        :raises: :exc:`restlite.Status` 500 if something went immediately
                 wrong while starting the control centre.

        .. todo:: Update client to handle 204 as a successful response.
                  Then we dont have to send 200 with a blank response.

        """

        authentication.login(request)

        if not controlcentre.startVazels():
            raise restlite.Status("500 Vazels Control Centre failed to start")
    
        vazelsintegration.setupWhenReady()
        return request.response("")
示例#29
0
文件: app.py 项目: ayrton-sy/ITM
def auth():
    username = request.form.get('username')
    password = request.form.get('password')
    is_successful, user = authentication.login(username, password)
    app.logger.info('%s', is_successful)
    if (is_successful):
        session["user"] = user
        return redirect('/')
    else:
        return render_template('login.html', error=True)
示例#30
0
    def GET(request):
        authentication.login(request)

        # We want the proper experiment path that vazelsmanager tells us
        exp_dir = vazelsmanager.getExperimentPath()
        path = os.path.join(exp_dir,"Output_Folder")

	# Make a temporary file, fill it with the Output_Folder's contents.
	with tempfile.SpooledTemporaryFile(1024) as temp:
		tar = tarfile.open(fileobj=temp, mode="w:gz")
		tar.add(name=path, arcname="Output_Folder")
		tar.close()

		temp.seek(0)
		return_data = temp.read()

		return request.response(return_data, "application/x-gzip")

	raise restlite.Status, "500 Could Not Serve Data File"
示例#31
0
def auth():
    # replace with request.form in deployment
    username = request.values["username"]
    password = request.values["password"]
    if authentication.login(username, password):
        session['authenticated'] = True
        session['username'] = username.lower()
        return jsonify({"success": True, "username": username})
    else:
        return jsonify({"success": False})
示例#32
0
def login():
    if(request.method == "POST"):                                       
        success = authentication.login(server.usersCSVReader, request.form["username"], request.form["password"])       # Pass form information to authentication module
        if (success):                                
            userString = authentication.user_role.title()+"("+request.form["username"]+")"
            server.user = eval(userString)                                                                              # Create a User() object based on read-in role          
            coursesToUser(server.enrolmentsCSVReader, server.coursesCSVReader, server.user)                             # Load the course objects and survey forms associated to user
            return redirect(url_for("landing"))
        else:
            flash("Incorrect Username or Password")
    return render_template("login.html")
示例#33
0
def auth():
    username = request.form.get('username')
    password = request.form.get('password')

    is_successful, user = authentication.login(username, password)
    app.logger.info('%s', is_successful)
    if (is_successful):
        session["user"] = user
        return redirect('/')
    else:
        return "Invalid username or password please <a href='/login'>enter again</a>"
示例#34
0
    def GET(self, request):
        """
        Grab the experiment output data.

        :returns: JSON representation of the experiment output data.
        :rtype: ``json``
        :raises: :exc:`restlite.Status` 500 if the output could not be parsed.

        """

        authentication.login(request)

        # We want the proper experiment path that vazelsmanager tells us
        exp_dir = controlcentre.getExperimentPath()
        path = os.path.join(exp_dir,"Output_Folder")
        parsed = pbparser.scan_output(path)
        # If the parsing broke in any way we get back None
        if parsed is None:
            raise restlite.Status, "500 Could Not Read Output Data"
        return request.response(parsed)
示例#35
0
def auth():
    username = request.form.get('username')
    password = request.form.get('password')

    is_successful, user = authentication.login(username, password)
    app.logger.info('%s', is_successful)
    if (is_successful):
        session["user"] = user
        return redirect('/')
    else:
        flash("Invalid username or password. Please try again.")
        return redirect('/login')
示例#36
0
文件: actors.py 项目: OhBaby/reef
    def GET(request):
        authentication.login(request)

        actor = request['PATH_INFO']
        namemap = config.getSettings("actors")["defs"]

        # Asking for names of actors
        if not actor:
            return request.response(namemap.keys())

        # Asking for the file
        if actor.endswith(".tar.gz"):
            actorname = actor[:len(actor)-len(".tar.gz")]
            return showActorFile(request, actorname)

        # Asking for the actor info
        if actor not in namemap:
            raise restlite.Status, "404 Not Found"

        actordata = namemap[actor].copy()
        del actordata['file']
        return request.response(actordata)
示例#37
0
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        json_data = request.form
        email = json_data.get('email')
        password = json_data.get('password')
        status = authentication.login(email, password)
        if status:
            session['logged_in'] = True
            session['user'] = email
            return redirect(url_for('main'))
        else:
            # TODO: Give message that login was incorrect
            return redirect(url_for('login'))
示例#38
0
def create_or_login(resp):
    username = sanitize_openid(resp.identity_url)
    if g.notebook.user_manager().user_exists(username):
        session['username'] = g.username = username
        session.modified = True
    else:
        from sagenb.notebook.user import User
        new_user = User(username, '', email = resp.email, account_type='user') 
        try: 
            g.notebook.user_manager().add_user_object(new_user)
            session['username'] = g.username = username
            session.modified = True
        except ValueError:
            #add creation_error=True to the render dict somehow 
            from authentication import login
            return login({'creation_error': True})
    return redirect(request.values.get('next', url_for('base.index')))
示例#39
0
def login():
    if (request.method == "POST"):
        if (request.form["bt"] == "login"):
            # Pass form information to the authentication module.
            success = authentication.login(request.form["username"],
                                           request.form["password"])
            if (success != 0 and success != -1):
                # Create a User() object based on the read-in role.
                server.user = success
                return redirect(url_for("landing"))
            elif (success == 0):
                flash("Account Still Pending Approval")
            else:
                flash("Incorrect Username or Password")
        if (request.form["bt"] == "requestaccess"):
            return redirect(url_for("requestAccess"))
    return render_template("login.html")
示例#40
0
			print("\n")
			print("  HTTP Status Code - " + r.status_code)
			d_sync_smartaccount_error_message = json.loads(r.content.decode('utf8'))
			print(json.dumps(d_sync_smartaccount_error_message, indent=2, sort_keys=True))
			exit()
		d_sync_smart_account_status = json.loads(r.content.decode('utf8'))

		for s_vss in d_sync_smart_account_status['data']:
			if 'Success' in s_vss['status'] or 'Fail' in s_vss['status']:
				c_tasks_status += 1
			os.system("clear")
			l_status_char_len = []
			l_status_char_len.append(len(s_vss['action']))
			l_status_char_len.append(len(s_vss['currentActivity']))
			l_status_char_len.append(len(s_vss['status']))
			l_status_char_len = sorted(l_status_char_len, reverse=True)
			print(2 * '\n')
			print('  ========= ', l_status_char_len[0] * '=')
			print('  action:   ', s_vss['action'])
			print('  activity: ', s_vss['currentActivity'])
			print('  status:   ', s_vss['status'])
			print('  ========= ', l_status_char_len[0] * '=')
			del l_status_char_len[:]
	print("\n")

# --- main menu --- #
os.system("clear")
if __name__ == "__main__":
	gs_session, gd_conf = authentication.login()
	smart_account_sync_vmanage_with_cisco__sync_smart_account(gs_session, gd_conf)
示例#41
0
 def test_login_bad_creds(self, mock_open):
     #   wrong arguments
     mock_open.return_value.read.return_value = \
         'netease|password'
     self.assertFalse(auth.login('netease', 'badpassword'))
示例#42
0
 def test_login_error(self, mock_open):
     #   exceptions
     mock_open.side_effect = IOError()
     self.assertFalse(auth.login('netease', 'badpassword'))
示例#43
0
 def test_login(self, mock_open):
     #   correct arguments
     mock_open.return_value.read.read_value = \
         'netease|password\n'
     self.assertTrue(auth.login('netease', 'password'))
def test_login1():
    result = authentication.login('ABC','1234')
    assert result =={'result': True,'message': "authentication failed, password incorrect."} 
def test_login():
    result = authentication.login('ABC','123')
    assert result =={'result': True,'message': "User is successfully login."}
示例#46
0
import authentication as a
input_id = input("Please insert your ID. \n아이디를 입력해주세요. \n")
if a.login(input_id):
    print('Welcome ' + input_id + "\n")
    input_pw = input("password: "******"Wrong login ID or password, please check")

#Version 3
# input_id = input("Please insert your ID. \n아이디를 입력해주세요. \n")
# def login(_id):
#     members = ['mdoubleu', 'egoing', 'flamewndls']
#     for member in members:
#         if member == _id:
#             return True
#     return False
# if login(input_id): #since the function "login" is already a boolean type, we can directly use in the if/else
#     print ('Welcome, ' + input_id)
# else:
#     print("Wrong login ID or password, please check")

#Version 2
# input_id = input("아이디를 입력해주세요.\n")
# members = ['mdoubleu', 'egoing', 'flamewndls']
#
# for member in members:
#     if member == input_id:
#         print("Welcome!, " + member)
#         import sys
#         sys.exit()
示例#47
0
    print("4. Install Requirements")
    print("5. Check for updates\n")
    print("0. Exit\n")

    choice = input("> ").lower().strip()

    if choice == "1":  # TODO catch KeyboardInterrupt at search
        series = search(
        )  # BUG Searching for 'one punc' causes a keyerror when reading the 'data' key
        if series != None:
            download(series)
        wait()
    elif choice == "2":
        clear_screen()
        clear_downloads()
        wait()
    elif choice == "3":  # TODO add a printout that tells the user who is currently logged in
        clear_screen()
        login()
        wait()
    elif choice == "4":
        # installReqs()
        print("Not implemented")
        wait()
    elif choice == "5":
        # update()
        print("Not implemented")
        wait()
    elif choice == "0":
        exit()
示例#48
0
 def test_login_error(self, mock_open):
     """Test the login function when an error happens."""
     mock_open.side_effect = IOError()
     self.assertFalse(auth.login('george', 'bosco')) 
示例#49
0
 def test_login_bad_creds(self, mock_open):
     """Test the login function when bad creds are passed."""
     mock_open.return_value.read.return_value = "george|bosco"
     self.assertFalse(auth.login('george', 'marbleRye'))
示例#50
0
 def test_login_success(self, mock_open):
     """Test the login function when things go right."""
     mock_open.return_value.read.return_value = "george|bosco"
     self.assertTrue(auth.login('george', 'bosco'))
示例#51
0
文件: main.py 项目: pmdbt/RobinhoodAI
import logging
import authentication as auth
import configuration as config

# logging config
logging.basicConfig(format='%(levelname)s: main.py %(message)s',
        level=config.LOGGING_LEVEL)


if __name__ == "__main__":
    # create auth obj
    auth = auth.Authentication()
    # login
    auth.login()
    # logout
    auth.logout()