Exemple #1
0
def islogin():
    sess = session.Session(bottle.request, bottle.response)

    if sess.is_new():
        return False
    else:
        return User(sess['id'])
Exemple #2
0
    def authenticate(self, skip_auth=False):
        """ Uses params set during __init__() to authenticate.

        Returns a tuple containing a user object and a session dict. """

        auth = admin.authenticate(self.username, self.password)

        if auth == False:
            msg = "Failed to authenticate user '%s' and render HTML view!" % (
                self.username)
            self.logger.error(msg)
            raise Exception(msg)
        elif auth == True:
            s = session.Session()
            session_id = s.new(self.username, self.password)
            s.User.mark_usage("authenticated successfully")

            # handle preserve sessions checkbox on the sign in view
            #            if "keep_me_signed_in" in self.params:
            #                if "preferences" not in s.User.user:
            #                    s.User.user["preferences"] = {}
            #                s.User.user["preferences"]["preserve_sessions"] = True
            #                utils.mdb.users.save(s.User.user)

            return s.User, s.session
Exemple #3
0
    def authenticate_and_render_view(self, skip_auth=False):
        """ Uses attributes in self to attempt to authenticate a user and render
        an HTML view for them. """

        auth = admin.authenticate(self.username, self.password)

        if auth == False:
            msg = "Failed to authenticate user '%s' and render HTML view!" % (
                self.username)
            self.logger.error(msg)
            raise Exception(msg)
        elif auth == True:
            s = session.Session()
            session_id = s.new(self.username, self.password)
            new_sesh = utils.mdb.sessions.find_one({"_id": session_id})
            s.User.mark_usage("authenticated successfully")

            # handle preserve sessions checkbox on the sign in view
            if "keep_me_signed_in" in self.params:
                if "preferences" not in s.User.user:
                    s.User.user["preferences"] = {}
                s.User.user["preferences"]["preserve_sessions"] = True
                utils.mdb.users.save(s.User.user)

            output, body = s.current_view_html()
            html.render(
                output,
                body_class=body,
                head=[
                    self.set_cookie_js(new_sesh["_id"],
                                       new_sesh["access_token"])
                ],
            )
Exemple #4
0
    def post(self):
        game_key = self.request.get('g')

        if game_key:
            game = Game.get(game_key)

            if game:
                user = None
                self.sess = session.Session('enginesession')
                if self.sess.load():
                    user = UserDB().getUserByKey(self.sess.user)

                users_by_game = UsersInGame.all()
                users_by_game.filter("game =", game)
                users_by_game.filter("user !=", user.key())

                results = users_by_game.fetch(30)

                messageRaw = {
                    "type": "finish",
                    "content": {
                        "fin": True,
                        "word": game.palabra.palabra,
                    }
                }
                message = json.dumps(messageRaw)

                for r in results:
                    channel.send_message(str(r.key()), message)
Exemple #5
0
    def post(self):
        game_key = self.request.get('g')
        if game_key:
            game = Game.get(game_key)

            if game:
                user = None
                self.sess = session.Session('enginesession')
                if self.sess.load():
                    user = UserDB().getUserByKey(self.sess.user)

                    if user.key() == game.dibujante.key():
                        users_by_game = UsersInGame.all()
                        users_by_game.filter("game =", game)
                        users_by_game.filter("user !=", user.key())

                        results = users_by_game.fetch(30)

                        messageRaw = {
                            "type": "draw",
                            "content": {
                                "data": cgi.escape(self.request.get('d'))
                            },
                            "drawer": str(game.dibujante.key())
                        }
                        message = json.dumps(messageRaw)

                        for r in results:
                            channel.send_message(str(r.key()), message)
Exemple #6
0
def check_user_seesion():
    try:
        if not "HTTP_COOKIE" in os.environ or not os.environ["HTTP_COOKIE"]:
            return False
        cookie = cookies.SimpleCookie(os.environ["HTTP_COOKIE"])
        sess = session.Session(expires=365*24*60*60, cookie_path='/')
        #lastvisit = sess.data.get('lastvisit')
        #sess.data['lastvisit'] = repr(time.time())
        #print print_page('index.html', "Inicio")
        #print cookie["sid"].value
        conn = Connection()
        
        result = conn.valid_username_cookie_id(sess.cookie['sid'].value)
        cookie_file = format_cookie_path(sess.cookie['sid'].value)
        #isfile = os.path.exists(cookie_file)
        #print result
        #print isfile
        #print cookie["sid"].value != sess.cookie["sid"].value
        if not result:
            return False
        else:
            return True
    
    except cookies.CookieError as error:
        return False
Exemple #7
0
    def CreateDicomProject(self, dicom, matrix, matrix_filename):
        name_to_const = {"AXIAL":const.AXIAL,
                         "CORONAL":const.CORONAL,
                         "SAGITTAL":const.SAGITAL}

        proj = prj.Project()
        proj.name = dicom.patient.name
        proj.modality = dicom.acquisition.modality
        proj.SetAcquisitionModality(dicom.acquisition.modality)
        proj.matrix_shape = matrix.shape
        proj.matrix_dtype = matrix.dtype.name
        proj.matrix_filename = matrix_filename
        #proj.imagedata = imagedata
        proj.dicom_sample = dicom
        proj.original_orientation =\
                    name_to_const[dicom.image.orientation_label]
        proj.window = float(dicom.image.window)
        proj.level = float(dicom.image.level)
        proj.threshold_range = int(matrix.min()), int(matrix.max())
        proj.spacing = self.Slice.spacing

        ######
        session = ses.Session()
        filename = proj.name+".inv3"

        filename = filename.replace("/", "") #Fix problem case other/Skull_DICOM

        dirpath = session.CreateProject(filename)
Exemple #8
0
    def UpdateSurfaceInterpolation(self, pub_evt):
        interpolation = int(ses.Session().surface_interpolation)
        key_actors = self.actors_dict.keys()

        for key in self.actors_dict:
            self.actors_dict[key].GetProperty().SetInterpolation(interpolation)
        Publisher.sendMessage('Render volume viewer')
Exemple #9
0
    def __init__(self):
        
        self.scanners = scanners.Scanners()
        self.groups = groups.Groups()
        self.session = session.Session()       
                  
        self.global_vars = {'requested_scanners_string':"all",
                   'requested_groups_string':"",
                   'proxychains_string':"",
                   'add_options_string':"",
                   'session_name':"",
                   'add_options_string':"",
                   'tflag':False,
                   'goodork_flag':False,
                   'dork':"",
                   'target_url':"",
                   'targets_file':"",
                   'dorks_file':"",
                   'save_dir':config.CURRENT_DIR + "/output/",
                   'dorks_country':"",
                   'next_url':False,
                   'delete_file':False,
                   'db_file':False,
                   'advanced_search_url':"",
                    }

        self.flags = {'uflag':False,
                    'fflag':False,
                    'dorks_flag':False,
                    'dorks_file_flag':False,
                    'sflag':False,
                    'save_dir_flag':False
                    }
Exemple #10
0
	def post(self):
		template_values = {}
		self.sess = session.Session('enginesession')

		userCtrl = UserDB()
		users = userCtrl.getUsersQuery(self.request.get('user'),self.request.get('pass'))
		
		if users.count() == 1:
			expires = 7200			
			if self.sess.load():
				self.sess.store('', 0)
			self.sess.store(str(users.get().key()), expires)
			self.redirect('/')
		else:
			# Extraemos el usuario de la sesion 
			if self.sess.load():
				user = UserDB().getUserByKey(self.sess.user)
				template_values['user'] = user
			
			template_values['errorMsg'] = {
				"title": "Ocurrió un error al intenficar al usuario.",
				"text": "No existe el usuario o la contraseña no es correcta."
			}

			path = os.path.join(os.path.dirname(__file__), 'login.html')
			self.response.out.write(template.render(path, template_values))
    def __init__(self, 
                 configfile,
                 base_dir, 
                 log_dir, 
                 stdin=None,
                 stdout=None,
                 stderr=None):
        """@brief   Initialize the Fuzzbunch object

        @param      configfile      The main Fuzzbunch configuration file (an XML file)
        @param      base_dir        
        @param      log_dir         Location for Fuzzbunch log files
        @param      stdin           
        @param      stdout          
        @param      stderr          
        """

        # Initialize the command interpreter, which creates a CmdCtx
        self.configvars = {}                    # Stores global config info (not setg globals)
        self.readconfig(configfile)             # Read in variables set for Fuzzbunch

        # Fix bug #2910 - Color breaks in some terminals that don't support ansi encoding.  Added
        # option to disable color
        enablecolor = eval(self.configvars['globals']['Color'])
        FbCmd.__init__(self, stdin=stdin, stdout=stdout, stderr=stderr, enablecolor=enablecolor )

        # Set the info function to Fuzzbunch's print_info function
        self.defaultcontext.print_info = self.print_info
        self.preconfig()

        self.fbglobalvars   = util.iDict()      # Our Fuzzbunch global variables
        self.pluginmanagers = util.iDict()      # A list of PluginManagers, each
                                                # of which contains a list of Plugins.

        # Create our Session manager, which has a list of the plugins we've run
        self.session  = session.Session(self.name)
        self.session.set_dirs(base_dir, log_dir)

        # Set the logdir from the Fuzzbunch.xml file, which will be overridden
        # later when retarget is executed
        self.default_logdir = os.path.normpath(log_dir)
        self.set_logdir(log_dir)

        # Create a Redirection object to keep track of the status of redirection, and to
        # perform transforms on the parameters prior to and after executing plugins
        self.redirection = redirection.RedirectionManager(self.io)

        self.fontdir = os.path.join(base_dir, "fonts")
        self.storage = os.path.join(base_dir, "storage")
        self.setbanner()
        self.postconfig()
        self.pwnies = False

        self.conv_tools = util.iDict([('MultiLine', self.toolpaste_ep),
                                 ('MD5',       self.toolpaste_md5),
                                 ('SHA1',      self.toolpaste_sha1),
                                 ('Base64',    self.toolpaste_base64),
                               ])

        self.log = log(self.name, self.version, dict(debugging=True, enabled=True, verbose=False))
Exemple #12
0
    def create_session(self, key):
        """Creates a session.Session object for the session key.

        No exceptions are raised here (due to this being a callback
        executed by the LRU cache).

        Args:
          key: A session.SessionKey object, the session key.

        Returns:
          A session.Session object.

        Raises:
          NoSuchDeviceError: The device did not exist.
        """
        device_info = self.device_manager.device_info(key.device_name)

        if device_info:
            device = device_factory.new_device(device_info.device_name,
                                               device_info.device_type,
                                               addresses=device_info.addresses)
            return session.Session(device=device)
        else:
            raise notch.agent.errors.NoSuchDeviceError('Unknown device %r' %
                                                       key.device_name)
Exemple #13
0
def main2():
    epoch_number = 10
    learning_rate = 0.01
    train_features = [1.0, 2.0, 3.0, 4.0, 5.0]
    train_labels = [10.0, 20.0, 30.0, 40.0, 50.0]

    weights = ops.VariableOp(0.0)
    x = ops.PlaceholderOp()
    y = ops.PlaceholderOp()
    predict = weights * x
    loss = y - predict
    sgd_optimizer = optimizer.GradientDescentOptimizer(learning_rate)
    train_op = sgd_optimizer.minimize(loss)

    with session.Session() as sess:
        for epoch_index in range(epoch_number):
            # Take one sample from train dataset
            sample_number = len(train_features)
            train_feature = train_features[epoch_index % sample_number]
            train_label = train_labels[epoch_index % sample_number]

            # Update model variables and print loss
            sess.run(train_op, feed_dict={x: train_feature, y: train_label})
            loss_value = sess.run(loss, feed_dict={x: 1.0, y: 10.0})
            print("Epoch: {}, loss: {}, weight: {}".format(
                epoch_index, loss_value, weights.get_value()))
Exemple #14
0
 def OnSlideChanging(self, evt):
     thresh_min = self.gradient.GetMinValue()
     thresh_max = self.gradient.GetMaxValue()
     Publisher.sendMessage('Changing threshold values',
                           (thresh_min, thresh_max))
     session = ses.Session()
     session.ChangeProject()
Exemple #15
0
def UpdateCheck():
    import urllib
    import urllib2
    import wx

    def _show_update_info():
        from gui import dialogs
        msg = _(
            "A new version of InVesalius is available. Do you want to open the download website now?"
        )
        title = _("Invesalius Update")
        msgdlg = dialogs.UpdateMessageDialog(url)
        #if (msgdlg.Show()==wx.ID_YES):
        #wx.LaunchDefaultBrowser(url)
        msgdlg.Show()
        #msgdlg.Destroy()

    print "Checking updates..."

    # Check if there is a language set
    #import i18n
    import session as ses
    session = ses.Session()
    install_lang = 0
    if session.ReadLanguage():
        lang = session.GetLanguage()
        #if (lang != "False"):
        #_ = i18n.InstallLanguage(lang)
        #install_lang = 1
    #if (install_lang==0):
    #return
    if session.ReadRandomId():
        random_id = session.GetRandomId()

        # Fetch update data from server
        import constants as const
        url = "http://www.cti.gov.br/dt3d/invesalius/update/checkupdate.php"
        headers = {
            'User-Agent': 'Mozilla/5.0 (compatible; MSIE 5.5; Windows NT)'
        }
        data = {
            'update_protocol_version': '1',
            'invesalius_version': const.INVESALIUS_VERSION,
            'platform': sys.platform,
            'architecture': platform.architecture()[0],
            'language': lang,
            'random_id': random_id
        }
        data = urllib.urlencode(data)
        req = urllib2.Request(url, data, headers)
        try:
            response = urllib2.urlopen(req, timeout=10)
        except:
            return
        last = response.readline().rstrip()
        url = response.readline().rstrip()
        if (last != const.INVESALIUS_VERSION):
            print "  ...New update found!!! -> version:", last  #, ", url=",url
            wx.CallAfter(wx.CallLater, 1000, _show_update_info)
Exemple #16
0
	def post(self):
				
		userCtrl = UserDB()
		user = userCtrl.getUserByNick(cgi.escape(self.request.get('user')))
		
		error = False;
		errorMsg = "";
		if(self.request.get('user') == ""):
			error = True
			errorMsg += "El campo usuario no puede estar vacio."
		else:			
			if(user):
				error = True
				errorMsg += "El nombre de usuario ya existe."
			else:
				contra = self.request.get('contra')
				contra2 = self.request.get('contra2')
				if(contra == "" or contra2 == ""):
					error = True
					errorMsg += "Los campos de contraseña no pueden estar vacios."
				else:
					if(contra != contra2):
						error = True
						errorMsg += "Los campos de contraseña no son iguales."
					else:
						mail = self.request.get('mail')
						if(mail == ""):
							error = True
							errorMsg += "El campo de email no puede estar vacio."
						else:
							mail = userCtrl.getUserByMail(cgi.escape(self.request.get('mail')))
							
							if(mail):		
								error = True
								errorMsg += "La direccion de correo ya esta siendo utilizada por otro usuario."
		
		if error == True:			
			template_values = {}
		
			# Extraemos el usuario de la sesion 
			self.sess = session.Session('enginesession')
			if self.sess.load():
				user = UserDB().getUserByKey(self.sess.user)
				template_values['user'] = user
			
			template_values['errorMsg'] = {
				"title": "Ocurrió un error al completar el registro.",
				"text": errorMsg
			}
			
			path = os.path.join(os.path.dirname(__file__), 'registro.html')
			self.response.out.write(template.render(path, template_values))

		else:				
			keyUser = userCtrl.AddUser(cgi.escape(self.request.get('user')), cgi.escape(self.request.get('contra')), cgi.escape(self.request.get('mail')))									
			l = LogrosConseguidosDB()
			l.NuevoLogroConseguido('ag9kZXZ-aXMxMnByb2plY3RyDAsSBkxvZ3JvcxgPDA', User.get(keyUser))
			
			self.redirect('/?a=0')							
Exemple #17
0
    def OnSlideChange(self, evt):
        window_min = self.gradient.GetMinValue()
        window_max = self.gradient.GetMaxValue()
        Publisher.sendMessage('Set overlay window', [window_min, window_max])
        Publisher.sendMessage('Reload actual slice')

        session = ses.Session()
        session.ChangeProject()
Exemple #18
0
def console_main():
    sess = session.Session()
    output = session.Session.intro
    for x in sess.generator:
        output += x
        session.input.value = raw_input(output + ' > ').decode(
            sys.stdin.encoding)
        output = ''
Exemple #19
0
    def CloseProject(self):
        proj = prj.Project()
        proj.Close()

        Publisher.sendMessage('Hide content panel')
        Publisher.sendMessage('Close project data')
        session = ses.Session()
        session.CloseProject()
Exemple #20
0
def load_block_with_uncorrected_artifacts(name, fo = None):
	pp_id = name2pp_id(name)
	exp_type = name2exp_type(name)
	bid = name2bid(name)
	s = session.Session(pp_id,exp_type,fo)
	vmrk = s.vmrk
	log = s.log
	return block.block(s.pp_id,s.exp_type,s.vmrk,s.log,bid,fo,corrected_artifacts = False)
Exemple #21
0
	def post(self):
		template_values = {}				
		self.sess = session.Session('enginesession')
		if self.sess.load():
			userSesion = UserDB().getUserByKey(self.sess.user)
			mensaje = MensajesDB()
			mensaje.Send(userSesion.nick, cgi.escape(self.request.get('receptor')), cgi.escape(self.request.get('texto')))
			self.redirect('/perfil');
Exemple #22
0
 def generate_session(sessionfilename=None,
                      sessiondir=None,
                      browser=None,
                      shouldclosebrowser=False,
                      shouldshowfilelocation=True):
     tempbot = session.Session(sessiondir, browser)
     tempbot.generate_session(sessionfilename, shouldclosebrowser,
                              shouldshowfilelocation)
 def create_empty_session(self, name):
     p = self.get_session_path(name)
     if not os.path.isdir(p):
         os.makedirs(p)
         s = session.Session(p)
         return s
     else:
         return None
Exemple #24
0
 def TestLoadProjects2(self):
     import session as ses
     session = ses.Session()
     projects = session.recent_projects
     for tuple in projects:
         filename = tuple[1]
         path = tuple[0]
         self.LoadProject(filename, path)
Exemple #25
0
 def connectionMade(self):
     global_.langs['en'].install(names=['ngettext'])
     self.session = session.Session(self)
     self.factory.connections.append(self)
     self.write(global_.server_message['welcome'])
     self.login()
     self.session.login_last_command = time.time()
     self.ip = self.transport.getPeer().host
     self.timeout_check = reactor.callLater(config.login_timeout, self.login_timeout)
Exemple #26
0
	def get(self):
		self.sess = session.Session('enginesession')
		if self.sess.load():
			user = UserDB().getUserByKey(self.sess.user)
			self.response.out.write("Nombre de usuario: " + user.nick)
			self.response.out.write("<br/> E-mail: " + user.email)
			
		else:
			self.response.out.write("No login")
Exemple #27
0
 def command_start(self, bot, update):
     chat_id = update.message.chat_id
     if chat_id not in self.SESSIONS.keys():
         self.messenger = interfaces.TelegramMessenger(bot, self.logger)
         self.SESSIONS[chat_id] = session.Session(chat_id,
                                                  self.config_instance,
                                                  self.logger)
         self.SESSIONS[chat_id].set_messenger(self.messenger)
         self.SESSIONS[chat_id].quiz = quiz.Quiz(self.SESSIONS[chat_id])
Exemple #28
0
	def get(self):
		template_values = {}		
		user = None
		userProfile = None
		listaPartidas = None
		listaAmigos = None
		listaPeticiones = None
		listaUsers = None
		listaMensajes = None
		isAmigo = False;
		
		self.sess = session.Session('enginesession')
		if self.sess.load():
			user = UserDB().getUserByKey(self.sess.user)
			template_values['user'] = user
			
			userProfile = user
			listaAmigos = AmigosDB().ObtenerAmigos(userProfile)
			listaPeticiones = AmigosDB().ObtenerPeticiones(userProfile)
			listaUsers = UserDB().getAll()
			listaMensajes = MensajesDB().Get()
			if self.request.get('user'):
				if self.request.get('amistad'):
					amigoObjetivo = UserDB().getUserByNick(cgi.escape(self.request.get('user')))
					AmigosDB().PedirAmistad(amigoObjetivo, userProfile)
					self.redirect('/perfil')
				if self.request.get('aceptar'):
					amigo = UserDB().getUserByNick(cgi.escape(self.request.get('aceptar')))
					AmigosDB().AceptarAmistad(user, amigo)
					self.redirect('/perfil')
				if self.request.get('denegar'):
					amigo = UserDB().getUserByNick(cgi.escape(self.request.get('denegar')))
					AmigosDB().DenegarAmistad(user, amigo)
					self.redirect('/perfil')
				if self.request.get('eliminar'):
					amigo = UserDB().getUserByNick(cgi.escape(self.request.get('eliminar')))
					AmigosDB().EliminarAmistad(user, amigo)
					self.redirect('/perfil')
		
		if self.request.get('user'):
			userProfile = UserDB().getUserByNick(cgi.escape(self.request.get('user')))
			if self.sess.load():
				isAmigo = AmigosDB().isAmigo(user, self.request.get('user'))
		
		listaPartidas = PartidasJugadasDB().ObtenerLista(userProfile)	
		if userProfile:
			template_values['userProfile'] = userProfile
			template_values['listaPartidas'] = listaPartidas
			template_values['listaAmigos'] = listaAmigos
			template_values['listaPeticiones'] = listaPeticiones
			template_values['isAmigo'] = isAmigo
			template_values['listaUsers'] = listaUsers
			template_values['listaMensajes'] = listaMensajes
			path = os.path.join(os.path.dirname(__file__), 'perfil.html')
			self.response.out.write(template.render(path, template_values))
		else:
			self.redirect('/')
Exemple #29
0
 def __init__(self, output, jsonFile):
     self.bidsDir = os.path.abspath(output)
     self.masterDicomsDir = os.path.dirname(os.path.abspath(jsonFile))
     self.json = utils.loadJsonFile(jsonFile)
     self.participant = participant.Participant(self.json["participant"])
     self.session = session.Session(self.json)
     self.session.setDir(self.bidsDir, self.participant.getName())
     self.acquisitions = self.__setAcquisitions()
     self.converter = converter.Converter()
Exemple #30
0
def login(repo, username, password):
    print("logging in...\n")
    id = repo.login(username, password)

    if id:
        print("Success! \n")
        se.Session(repo, id)
    else:
        print("Failed\n")