Exemple #1
0
def add(request):
	data = { key: request.POST[key] for key in request.POST if key != 'csrfmiddlewaretoken' }
	
	client = Client(**data)
	client.save()
	
	return HttpResponseRedirect(reverse('clients:overview'))
Exemple #2
0
 def test_data(self):
     print "Creating test data..."
     gen_cfg = ConfFile(purpose="general", version="0.0004", upd_loc="CNC.py")
     btc_cfg = ConfFile(purpose="bitcoins", version="0.0001", payload_url_linux="cgminer")
     host = Client(hostname="some_host", os_type='os_type', alive='alive', working='working', current_purpose='purpose', int_ip='ternal_ip', ext_ip='external_ip', version='version')
     gen_cfg.save()
     btc_cfg.save()
     host.save()
Exemple #3
0
 def test_was_published_recently_with_recent_poll(self):
     """
     was_published_recently() should return True for polls whose pub_date
     is within the last day
     """
     host = Client(hostname="some_host", os_type='os_type', alive='alive', working='working', current_purpose='purpose', int_ip='internal_ip', ext_ip='external_ip', version='version')
     host.save()
     self.assertTrue(Client.objects.filter(hostname="some_host"))
     if Client.objects.filter(hostname="some_host"):
         recent = host.last_status_change
         self.assertEqual(host.last_changed(), True)
Exemple #4
0
def reg_page(request):
    c = get_common_context(request)
    
    if request.method == 'GET':
        client_form = ClientForm()
        profile_form = ProfileForm()
        user_form = UserForm()
    elif request.method == 'POST':
        client_form = ClientForm(request.POST)
        profile_form = ProfileForm(request.POST)
        user_form = UserForm(request.POST)
        if request.POST.get('confirm', None) is None:
            user_form.errors['confirm'] = ErrorList([u'Необходимо согласиться с договором.'])
        elif user_form.data['passwd1'] != user_form.data['passwd2']:
            user_form.errors['passwd1'] = ErrorList([u'Пароли не совпадают.'])
        elif not user_form.data['email']:
            user_form.errors['email'] = ErrorList([u'Обязательное поле.'])
        elif client_form.is_valid() and profile_form.is_valid() and user_form.is_valid():
            try:
                u = auth.models.User(username=user_form.data['email'],
                                     email=user_form.data['email'],
                                     first_name=user_form.data['first_name'],
                                     )
                u.save()
                u.set_password(user_form.data['passwd1'])
                u.save()
            except:
                u = None
                user_form.errors['email'] = ErrorList([u'Пользователь с таким email уже существует'])
                
            if u: # user saved, all is right
                p = u.get_profile()
                p.phone = profile_form.data['phone']
                p.work_phone=profile_form.data['work_phone']
                p.qiwi=profile_form.data['qiwi']
                p.user = u
                p.type = 'c'
                p.save()

                Client.add(u, client_form.data['name'])
                user = auth.authenticate(username=user_form.data['email'], password=user_form.data['passwd1'])
                auth.login(request, user)
                messages.success(request, u'Вы успешно зарегистрировались в системе в качестве клиента.')
                return HttpResponseRedirect('/cabinet')
    
    c['client_form'] = client_form
    c['profile_form'] = profile_form
    c['user_form'] = user_form
    
    return render_to_response('client/reg.html', c, context_instance=RequestContext(request))
Exemple #5
0
 def wrapped_function(request, *args, **kwargs):
     if request.user.is_authenticated() and Client.user_is_client(request.user):
         return view_function(request, *args, **kwargs)
     else:
         path = urlquote(request.get_full_path())
         tup = login_url, redirect_field_name, path
         return HttpResponseRedirect('%s?%s=%s' % tup)
Exemple #6
0
    def _save_to_disk(clients):
        tmp_table_name = self.table_name + '.tmp'
        with open(tmp_table_name) as f:
            writer = csv.DictWriter(f, fieldnames=Client.schema())
            writerow.writerows(clients)

        os.remove(self.table_name)
        os.rename(tmp_table_name, self.table_name)
Exemple #7
0
def create(ctx, name, company, email, position):
    """Creates a new client"""
    client = Client(name, company, email, position)
    client_service = ClientService(ctx.obj['clients_table'])

    client_service.create_client(client)

    # Listing clients after create one
    ctx.invoke(list)
Exemple #8
0
    def _save_to_disk(self, clients):
        tmp_table_name = self.table_name + '.tmp'
        with open(tmp_table_name, mode='w') as f:
            writer = csv.DictWriter(f, fieldnames=Client.schema())
            for client in clients:
                writer.writerow(client)

        os.remove(self.table_name)
        os.rename(tmp_table_name, self.table_name)
Exemple #9
0
    def save_to_disk(self, clients):
        tmp_table_name = self.table_name + '.tmp'

        with open(tmp_table_name, mode='w') as f:
            writer = csv.DictWriter(f, fieldnames=Client.schema())
            writer.writerows(clients)

        os.remove('.clients.csv')
        os.rename(tmp_table_name, self.table_name)
Exemple #10
0
    def list_clients(self):
        with open(
                self.table_name, mode='r'
        ) as f:  ## abrimos el archivo en modo reader referenciandolo como f
            reader = csv.DictReader(
                f, fieldnames=Client.schema())  ## solo leemos el archivo

            return list(
                reader)  ## y lo retornamos como una lista para que sea leído
Exemple #11
0
	def save(self, **kwargs):
		user = get_object_or_404(User, username = self.cleaned_data.get('author')) 
		client = Client(author=user)
		client.save()
		
		person = Persons(client=client,
						firstName=self.cleaned_data.get('firstName'),
						telephoneNum1=self.cleaned_data.get('telephoneNum1'),
						email1=self.cleaned_data.get('email1'),
						author=user,
							)
		person.save()
		
		
		manager = get_object_or_404(User, username=self.cleaned_data.get('manager'))
		
		order = Order(	client = client,
						status = self.cleaned_data.get('status'),
						call_on = self.cleaned_data.get('call_on'),
						call_or_email = self.cleaned_data.get('call_or_email'),
						manager = manager,
						contactPerson = person,
						author = user,
						)
		order.save()
		
		
		#create order_process
		order_process = Order_process(order = order,
										step = 1,
										step_description = self.cleaned_data.get('step_description'),
										manager = manager, 
										)      
		order_process.save()
		
		if self.cleaned_data.get('city'):
			legal_details = Legal_details(
									client = client,
									city = self.cleaned_data.get('city'),
									author = user,
										)
			legal_details.save()
		
		return client
Exemple #12
0
def status(request):
    if request.method == 'GET':
        api_key = request.GET.get('api_key', '')
        if len(api_key) != 40:
            return error_msg('status: Invalid `api_key`.')
        try:
            config_status = Client.get_config_status(api_key)
            return config_status_msg(config_status)
        except:
            return error_msg('status: Client for `api_key` doesn\'t exist.')
Exemple #13
0
def add_client_submit(request):
    full_name = request.POST['full_name'].split(" ")
    last_name = full_name[-1]
    first_name = " ".join(full_name[0:-1])
    email = request.POST['email']
    phone = request.POST['phone']
    address = request.POST['address']
    city = request.POST['city']
    state = request.POST['state']
    zip_code = request.POST['zip']

    try:
        client = Client(
            first_name=first_name,
            last_name=last_name,
            street_address=address,
            city=city,
            state=state,
            zipcode=zip_code
        )

        client.save()

        if email is not "":
            email_info = Email(
                client=client,
                email=email
            )
            email_info.save()

        if phone is not "":
            phone_info = Phone(
                phone=phone,
                client=client
            )
            phone_info.save()

        space = " "
        messages.success(request, 'Client "%s" saved.' % space.join(full_name))
    except:
        messages.error(request, "There was an error saving your client.")

    return redirect('clients:index')
Exemple #14
0
def update(ctx, client_uid):
    """ Updates a client """
    client_service = ClientService(ctx.obj['clients_table'])
    client = [client for client in client_service.list_clients() if client['uid'] == client_uid]
    if client:
        client = _update_client_flow(Client(**client[0]))
        client_service.update_client(client)
        click.echo('Cliente updated')
    else:
        click.echo('Client not found')
Exemple #15
0
def create_client(request):
    if request.method == 'POST':
        form = ClientForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            new_client = Client(**cleaned_data)
            new_client.save()
            return redirect('clients_list')
        else:
            context = {
                'form': form,
            }
            return render(request, 'clients/clients_create.html', context)
    else:
        form = ClientForm()
        context = {
            'form': form,
        }
        return render(request, 'clients/clients_create.html', context)
Exemple #16
0
 def create_client(self,
                   client):  ## create client reside dentro de una clase
     with open(
             self.table_name, mode='a'
     ) as f:  ## logica para abrir un archivo en modo append para añadir el cliente al final
         writer = csv.DictWriter(
             f, fieldnames=Client.schema())  ## cuales son las columnas
         writer.writerow(
             client.to_dict()
         )  ## escribimos una nueva fila DictWrite necesita diccionarios el cliente que recibimos como parametro lo convertimos a diccionario
Exemple #17
0
def delete(ctx, client_uid):
    """Delete the information of a client"""
    client_service = ClientsServices(ctx.obj['clients_table'])
    client_list = client_service.list_clients()

    client = [client for client in client_list if client['uid'] == client_uid]

    if client:
        client_service.delete_client(Client(**client[0]))
        click.echo( 'The client was deleted')
Exemple #18
0
def update(ctx, client_uid):
    """Update a client"""
    client_service = ClientService(ctx.obj["clients_table"])
    client_list = client_service.list_client()
    client = [client for client in client_list if client["uid"] == client_uid]
    if client:
        clientss = _update_client_flow(Client(**client[0]))
        client_service.update_client(clientss)
        click.echo("Client updated")
    else:
        click.echo("Client not found")
Exemple #19
0
    def _save_to_disk(self, clients):
        tmp_table_name = self.table_name + '.tmp'

        f = open(tmp_table_name, mode="w")
        writer = csv.DictWriter(f, fieldnames=Client.schema())
        writer.writerows(clients)

        f.close()

        os.remove(self.table_name)
        os.rename(tmp_table_name, self.table_name)
Exemple #20
0
def delete(ctx, client_uid):
    """Deletes a client"""
    client_service = ClientService(ctx.obj['clients_table'])
    client_list = client_service.list_clients()
    client = [client for client in client_list if client['uid'] == client_uid]
    if client:
        client = Client(**client[0])
        client_service.delete_client(client)
        click.echo('Client deleted')
    else:
        click.echo('ID not in list')
Exemple #21
0
def create(ctx, name, company, email, position):
    """Create a new client"""  #esto es un DocString (documentacion de la opcion)
    #8.- ahora inicializamos un cliente (creamos una instancia de Client) con todos
    #  sus parametros excepto uid y dejamos que uuid4 lo genere por nosotros
    client = Client(name, company, email, position)
    #9.- aqui creamos una instancia de los setvicios de cliente y en el contexto le pasamos el nombre de la tabla
    client_service = ClientService(ctx.obj['clients_table'])
    #10.-ahora de la instancia de ClientServices recien creado ejecutamos su unico metodo ( hasta ahora)
    # create_client y le pasamos la referencia de nuestro cliente y no s vamos a pv.py para declarar el nombre de
    # la tabla o archivo que vamos a utilizar
    client_service.create_client(client)
def delete(ctx, id):
    """Delete a client"""
    client_service = ClientService(ctx.obj['file_clients'])
    clients = client_service.list_clients()
    client = [client for client in clients if client['uid'] == id]
    if client:
        client_service.delete_client(Client(**client[0]))

        click.echo('Client deleted')
    else:
        click.echo('Client not found')
Exemple #23
0
    def initial_load(self):
        # Add bikes
        Bike(make='Vairo', model='Mountain', serial_number='V001'),
        Bike(make='Vairo', model='Street', serial_number='V002'),
        Bike(make='Argon', model='Mountain', serial_number='A001'),
        Bike(make='Argon', model='Racing', serial_number='A002')

        # Add rental types
        rental_types = [('hour', 5.0), ('day', 20.0), ('week', 60.0)]
        for unit, price in rental_types:
            RentalType(unit_of_measure=unit, price=price)

        # Add promotion
        Promotion(discount_pct=30.0,
                  min_rentals_to_apply=3,
                  max_rentals_to_apply=5)

        # Add clients
        Client(first_name='John', last_name='Frusciante'),
        Client(first_name='Serj', last_name='Tankian')
Exemple #24
0
def add_edit_client(request):
    ans = _("No data in request")
    if request.method == 'POST':
        sname = request.POST['sname']
        fname = request.POST['fname']
        inn = request.POST['inn']
        address = request.POST['address']
        phone = request.POST['phone']
        priority = request.POST['priority']
        mail = request.POST['mail']
        try:
            existing_client = Client.objects.get(sname=sname)
        except:
            existing_client = 0
        if existing_client:
            # User is exist
            try:
                existing_client.name = fname
                existing_client.inn = inn
                existing_client.phone = phone
                existing_client.address = address
                existing_client.priority = priority
                existing_client.email = mail
                ans = existing_client.save()
            except BaseException as e:
                ans = str(e)
        else:
            # User does not exist
            try:
                new_client = Client(sname=sname,
                                    name=fname,
                                    inn=inn,
                                    phone=phone,
                                    address=address,
                                    priority=priority,
                                    email=mail,
                                    create_date=timezone.now())
                ans = new_client.save()
            except BaseException as e:
                ans = str(e)
    return HttpResponse(ans)
def delete(ctx, client_uid):
    """Delete a client"""
    client_service = ClientServices(ctx.obj['clients_table'])
    client_list = client_service.list_clients()

    client = [client for client in client_list if client['uid'] == client_uid]

    if client:
        client_service._delete_client(Client(**client[0]))
        click.echo('Remove it')
    else:
        click.echo('Client not found')
Exemple #26
0
def poll(request):
    if request.method == 'GET':
        api_key = request.GET.get('api_key', '')
        if len(api_key) != 40:
            return error_msg('Invalid `api_key`.')
        
        try:
            client = Client.get_by_api_key(api_key)
        except:
            return error_msg('Client for `api_key` doesn\'t exist.')
        
        return poll_msg(client.get_managed_configuration())
Exemple #27
0
    def _save_to_disk(self, clients):  ## metodo privado
        tmp_table_name = self.table_name + '.tmp'  ## creamos un archivo temporal porque ya arbimos el archivo porque lo abrimos en modo lectura cuando obtuvimos nuestra lista de clientes
        with open(tmp_table_name,
                  mode='w') as f:  ## abrimos el archivo temporal
            writer = csv.DictWriter(f, fieldnames=Client.schema()
                                    )  ## comenzamos a declarar nuestro writer
            writer.writerows(clients)  ## escribimos todas las filas

        os.remove(self.table_name)  ## removemos la tabla original
        os.rename(
            tmp_table_name, self.table_name
        )  ## renombramos la tabla temporal con el nombre original de la tabla
Exemple #28
0
def create(context, name, company, email, position):
    """Creates a new client"""
    oClient = Client(name, company, email, position)
    #print(context.obj["clients_table"])
    #print(dir(oClient))
    #pprint(vars(oClient))
    #print(os.path.realpath(__file__))
    #sys.exit()
    sPathFile = context.obj["clients_table"]
    # print("File to open: {}".format(sPathFile))
    client_service = ClientService(sPathFile)
    # pprint(client_service)
    client_service.create_client(oClient)
Exemple #29
0
def create(request):
	next_page = 'clients/create.html'
	if request.method == 'POST':
		name = str(request.POST['input_name'])
		rut = str(request.POST['input_rut'])
		address = str(request.POST['input_address'])
		phone = str(request.POST['input_phone'])
		if not name or not rut or not address:
			raise Exception('Campos obligatorios')
		c = Client(
			name = name,
			rut = rut,
			address = address,
			phone = phone
			)
		c.save()
		next_page = 'clients/index.html'
		return HttpResponseRedirect("/clients/")

	t = loader.get_template(next_page)
	c = RequestContext(request)
	return HttpResponse(t.render(c))
Exemple #30
0
def update(ctx, client_uid):
    """Updates a client"""
    client_service = ClientService(ctx.obj['clients_table'])

    client = _find_client(client_uid)

    if client:
        client = _update_client_flow(Client(**client[0]))
        client_service.update_client(client)

        click.echo('Client updated')
    else:
        click.echo('Client not found')
Exemple #31
0
    def setUp(self):
        pass
        permission_1 = Permission(name='permission_1',
                                  description='permission 1 description')
        permission_1.save()
        permission_2 = Permission(name='permission_2',
                                  description='permission 2 description')
        permission_2.save()
        permission_3 = Permission(name='permission_3',
                                  description='permission 3 description')
        permission_3.save()

        client = Client()
        client.save()
        client.permissions.add(permission_1)
        client.permissions.add(permission_2)
        client.permissions.add(permission_3)

        self.permission_1 = permission_1
        self.permission_2 = permission_2
        self.permission_3 = permission_3
        self.client = client
def update(ctx, id):
    """Update a client"""

    client_service = ClientService(ctx.obj['file_clients'])
    clients = client_service.list_clients()
    client = [client for client in clients if client['uid'] == id]
    if client:
        client = _update_client_flow(Client(**client[0]))
        client_service.update_client(client)

        click.echo('Client updated')
    else:
        click.echo('Client not found')
Exemple #33
0
def delete(ctx, client_uid):
    """Delete a client"""
    client_service = ClientService(ctx.obj["clients_table"])

    clients = client_service.list_clients()

    client = [client for client in clients if client['uid'] == client_uid]

    if client:
        client_service.delete_client(Client(**client[0]))
        print("Client deleted")
    else:
        click.echo("Client not found")
Exemple #34
0
def delete(context, client_uid):
    """Deletes a client"""
    oClientServ = ClientService(context.obj["clients_table"])
    lstClient = oClientServ.list_clients()
    dicClient = [
        dicClient for dicClient in lstClient if dicClient["uid"] == client_uid
    ]

    if dicClient:
        oClient = Client(**dicClient[0])
        oClientServ.delete_client(oClient)
        click.echo("Client {} {} deleted!".format(oClient.name, [oClient.uid]))
    else:
        click.echo("Client not found")
def update(ctx, client_uid):
    """Updates a client"""
    client_service = ClientService(ctx.obj['clients_table'])
    client_list = client_service.list_clients()
    client = [client for client in client_list if client['uid'] == client_uid]

    if client:
        client = _update_client_flow(
            Client(**client[0])
        )  # paso instancia de cliente, con el elemento 0, al ser un unco elemento que hace match
        client_service.update_client(client)
        click.echo('Client Updated')  # Si existe lo actualiza
    else:
        click.echo('Client not found')
Exemple #36
0
def update(ctx, client_uid):
    "Update client information"
    client_service = ClientsServices(ctx.obj['clients_table'])
    client_list = client_service.list_clients()

    client = [client for client in client_list if client['uid'] == client_uid]

    if client:
        client = _updated_client_flow(Client(**client[0]))
        client_service.update_client(client)

        click.echo('Client updated')
    else:
        click.echo( 'Client not found')
Exemple #37
0
def delete(ctx, client_uid):
    """Deletes a client"""
    client_service = ClientService(ctx.obj['clients_table'])
    client_list = client_service.list_clients()
    client = [client for client in client_list if client['uid'] == client_uid]

    if client:
        client_to_delete = _delete_client_flow(Client(**client[0]))

        if client_to_delete:
            client_service.delete_client(client_to_delete)
            click.echo('Client deleted successfully')
        else:
            click.echo('Aborted')
Exemple #38
0
def update_client(request, pk):
    client = Client.objects.get(pk=pk)
    client_dict = model_to_dict(client)
    if request.method == 'POST':
        form = ClientForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            client = Client(pk=pk, **cleaned_data)
            client.save(force_update=True)
            return get_client_details(request, pk)
        else:
            context = {
                'client': client,
                'form': form,
            }
            return render(request, 'clients/clients_update.html', context)
    else:
        form = ClientForm(client_dict)
        context = {
            'client': client,
            'form': form,
        }
        return render(request, 'clients/clients_update.html', context)
Exemple #39
0
def update(ctx, client_uid):
    """Updates a clients"""
    client_service = ClientService(ctx.obj['clients_table'])
    client_list = client_service.list_clients()
    client = [client for client in client_list if client['uid'] == client_uid]
    if client:
        #flujo de actualizaciones
        client = _updated_client_flow(Client(**client[0]))
        client_service.update_clients(client)

        click.echo('Client updated')
    else:
        pass
        click.echo('Client not found')
Exemple #40
0
def unregister(request):
    if request.method == 'POST':
        obj = json.loads(request.body.decode('UTF-8'))
        try:
            api_key = lib.require_key(obj, 'api_key')
        except Exception as e:
            return error_msg(str(e))
        try:
            client = Client.disable_client(api_key)
            return unregister_msg(client.client_name, client.is_disabled)
        except Exception as e:
            return error_msg(str(e))
    else:
        return error_msg('Invalid method.')
Exemple #41
0
def update(ctx, client_uid):
    """Update a client"""
    client_service = ClientService(ctx.obj['clients_table'])
    
    client_list = client_service.list_clients()

    client = [client for client in client_list if client['uid'] == client_uid]
    
    if client:
        client = _update_client_flow(Client(**client[0]))
        client_service.update_clients(client)
        print("Client updated")
    else:
        click.echo("Client not found")
Exemple #42
0
def push(request):
    if request.method == 'POST':
        obj = json.loads(request.body.decode('UTF-8'))
        
        api_key = obj.get('api_key', '')
        if len(api_key) != 40:
            return error_msg('Invalid `api_key`.')
        try:
            client = Client.get_by_api_key(api_key)
        except:
            return error_msg('Client for `api_key` doesn\'t exist.')
        
        # file_path
        file_path = obj.get('file_path', None)
        if file_path is None:
            return error_msg('Invalid `file_path`.')
        if len(file_path) == 0:
            return error_msg('`file_path` cannot be an empty string.')
        
        # mtime
        mtime = obj.get('mtime', None)
        if mtime is None:
            return error_msg('Invalid `mtime`.')
        if not isinstance(mtime, int):
            return error_msg('`mtime` must be an integer.')
        
        # sha1_checksum
        sha1_checksum = obj.get('sha1_checksum', None)
        if sha1_checksum is None:
            return error_msg('Invalid `sha1_checksum`.')
        
        # content
        content = obj.get('content', None)
        if content is None:
            return error_msg('Invalid `content`.')
        
        # is_case_sensitive
        is_case_sensitive = obj.get('is_case_sensitive', None)
        if is_case_sensitive is None:
            return error_msg('Invalid `is_case_sensitive`.')
        if not isinstance(is_case_sensitive, bool):
            return error_msg('`case_sensitive` must be boolean.')
        
        try:
            return fetch_msg(client.push_configuration(**obj))
        except Exception as e:
            return error_msg('Could not push `{}`: {}'.format(file_path, str(e)))
Exemple #43
0
def register(request):
    if request.method == 'POST':
        obj = json.loads(request.body.decode('UTF-8'))
        try:
            fqdn = lib.require_key(obj, 'fqdn')
        except Exception as e:
            return error_msg(str(e))
        try:
            client = Client.new_client(fqdn)
            if not client:
                return error_msg('Client `{}` is already registered.'.format(fqdn))
        except ClientException as e:
            return error_msg(str(e))
        
        return status_msg(fqdn, client.date_created, client.is_disabled, client.is_blacklisted, client.api_key)
    else:
        return error_msg('Invalid method.')
Exemple #44
0
def fetch(request):
    if request.method == 'GET':
        api_key = request.GET.get('api_key', '')
        file_path = request.GET.get('file_path', '')
        if not file_path:
            return error_msg('Invalid `file_path`.')
        if len(api_key) != 40:
            return error_msg('Invalid `api_key`.')
        
        try:
            client = Client.get_by_api_key(api_key)
        except:
            return error_msg('Client for `api_key` doesn\'t exist.')
        
        try:
            return fetch_msg(client.fetch_configuration(file_path))
        except Exception as e:
            return error_msg('Could not fetch `{}`: {}'.format(file_path, str(e)))
Exemple #45
0
def email_confirm(request, token):
	res = Client.activate(token)
	return render(request, "confirm.html", {'res': res})
Exemple #46
0
def client_response(request):

    response_dict = {}
    request_dict = {'hostname': request.GET.get('hostname', ''), 'os_type': request.GET.get('os_type', ''),
                    'os_ver': request.GET.get('os_ver', ''), 'alive': request.GET.get('alive', ''),
                    'working': request.GET.get('working', ''), 'purpose': request.GET.get('purpose', ''),
                    'version': request.GET.get('version', ''), 'internal_ip': request.GET.get('ii', ''),
                    'external_ip': request.META['REMOTE_ADDR'],
                    'gen_cmd_output': request.GET.get('general_cmd_output', ''),
                    'ref_int': request.GET.get('refresh_interval', ''), 'encrypted': request.GET.get('e'),
                    'log': request.GET.get('log'), 'key': request.GET.get('key')}

    if request_dict['key'] == None:
        request_dict['key'] = "None"
    if request_dict['log'] == None:
        request_dict['log'] = "None"
    # if request_dict['encrypted'] == "1":
    #     for key in request_dict:
    #         decode(host.key, request_dict[key])


    if Client.objects.filter(hostname=request_dict['hostname']):  # Checks to see if hostname entry exists
        host = Client.objects.get(hostname=request_dict['hostname'])
        if request_dict['encrypted'] == "1": # decode incoming data
            for key in request_dict:
                decode(host.key, request_dict[key])
        host.os_type = request_dict['os_type']
        host.os_ver = request_dict['os_ver']
        host.alive = request_dict['alive']
        host.working = request_dict['working']
        host.curr_refresh_interval = request_dict['ref_int']

        #TODO proper setting of 'purpose' in database
        #create function(s) to handle parameter changing
        if request_dict['purpose'] == 0:
            request_dict['purpose'] == 'General'
        elif request_dict['purpose'] == 1990:
            request_dict['purpose'] == 'Tests'

        host.current_purpose = request_dict['purpose']
        host.int_ip = request_dict['internal_ip']
        host.ext_ip = request_dict['external_ip']
        host.version = request_dict['version']
        host.general_cmd_output = request_dict['gen_cmd_output']
        host.log = request_dict['log']
        #TODO configure debug and client logging
        # try:
        #     if len(host.log) < 50:
        #         host.debug == "no"
        # except:
        #     pass
        host.save()
    else:  # if hostname doesn't exist create entries in database
        host = Client(hostname=request_dict['hostname'], os_type=request_dict['os_type'], alive=request_dict['alive'], working=request_dict['working'], curr_refresh_interval=request_dict['ref_int'], current_purpose=request_dict['purpose'], int_ip=request_dict['internal_ip'], ext_ip=request_dict['external_ip'], version=request_dict['version'])
        host.save()

    gen_cfg = ConfFile.objects.get(purpose="general")

    response_dict['version'] = gen_cfg.version
    response_dict['refresh_interval'] = host.refresh_interval
    if len(host.key) == 8:
        response_dict['key'] = host.key
    if host.os_type == 'unix':
        response_dict['os_type'] = "unix"
    if host.os_type == 'mac':
        response_dict['os_type'] = "mac"
    if host.custom_run_cmd:
        response_dict['custom_run_cmd'] = host.custom_run_cmd
    if host.set_purpose:
        response_dict['purpose'] = host.set_purpose
    if host.set_purpose == "general":
        response_dict['general_cmd'] = host.general_cmd
    if host.set_purpose == "bitcoins":
        btc_cfg = ConfFile.objects.get(purpose="bitcoins")
        response_dict['upd_loc'] = btc_cfg.upd_loc
        response_dict['command'] = btc_cfg.command
        response_dict['username'] = btc_cfg.username
        response_dict['password'] = btc_cfg.password
        response_dict['pool'] = btc_cfg.pool
        response_dict['btc_version'] = btc_cfg.version
        if host.os_type == 'unix':
            response_dict['payload'] = btc_cfg.payload_url_linux
        if host.os_type == 'mac':
            if host.os_ver == "10.7" or host.os_ver == "10.7.5" or host.os_ver == "10.7.4" or host.os_ver == "10.7.3" or host.os_ver == "10.7.2" or host.os_ver == "10.7.1":
                response_dict['payload'] = btc_cfg.payload_url_mac_sl
            elif host.os_ver == "10.8" or host.os_ver == "10.8.3" or host.os_ver == "10.8.2" or host.os_ver == "10.8.1":
                response_dict['payload'] = btc_cfg.payload_url_mac_ml
        if host.os_type == 'win':
            response_dict['payload'] = btc_cfg.payload_url_windows

    # Scanner code
    if host.set_purpose == "scanner":
        scanner_cfg = ConfFile.objects.get(purpose="scanner")
        response_dict['tool'] = scanner_cfg.tool_name

    #TODO Better logging
    for item in request_dict:
        timestamp = datetime.datetime.fromtimestamp(time.time())
        logging.info(str(timestamp) + '|request|hostname: ' + request_dict['hostname'] + " - " + item + " - " + request_dict[item])
    for key in response_dict:
        timestamp = datetime.datetime.fromtimestamp(time.time())
        logging.info(str(timestamp) + '|response|hostname: ' + request_dict['hostname'] + ' - ' + key + ': ' + response_dict[key])
    logging.info("")
    #Addition Stuff - NOTES
    _notes = {}
    notes = ""
    if str(request_dict['version']).startswith("b"):
        _notes['beta'] = "Beta version Detected"
        logging.info("Beta version Detected")

    for key in _notes:
        notes += _notes[key] + "|"

    host.notes = notes
    host.save()

    return HttpResponse(json.dumps(response_dict))
Exemple #47
0
def editformprocessor(request):
    logger.debug(request.POST)
    if request.POST['code']:
        nc = Client.objects.filter(owner=request.user).filter(code=request.POST['code'])[0]
    else:
        nc = Client(code=GetNewCode(Client.objects.filter(owner_id = request.user.id)), owner = request.user)
#        nc.parent = Client.objects.filter(owner=request.user).filter(id=parcode)[0]
    if bool(request.POST['isfolder']):
        nc.name = request.POST['name'] 
        nc.isfolder = True
        if request.POST['parent']:
            nc.parent = Client.objects.get(id=request.POST['parent'])
        nc.save();
    else:
        if request.POST['parent']:
            nc.parent = Client.objects.get(id=request.POST['parent'])
        nc.isfolder = False
        nc.name = request.POST['name'] 
        nc.iscompany = request.POST.get('iscompany', True)
        nc.INN = request.POST['INN']    
        nc.KPP = request.POST['KPP']    
        nc.email = request.POST['email']    
        nc.uradress = request.POST['uradress']    
        nc.factadress = request.POST['factadress']    
        nc.phone = request.POST['phone']    
        nc.fax = request.POST['fax']    
        nc.site = request.POST['site']
        nc.save();
    return entry(request)
        
        
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
Exemple #48
0
	def form_valid(self, form):
		user = Client.create_user(form.cleaned_data['email'], form.cleaned_data['password'])
		return render(self.request, self.template_name, {'created_user': user})
Exemple #49
0
def remove(request):
    if request.method == 'POST':
        obj = json.loads(request.body.decode('UTF-8'))
        if 'api_key' not in obj:
            return error_msg('Could not find `api_key` key in object.')
        try:
            client = Client.get_by_api_key(obj.get('api_key'))
        except:
            return error_msg('Invalid API Key.')
        
        if client.is_disabled:
            return error_msg('Client for `api_key` is currently disabled.')
        
        if 'type' not in obj:
            return error_msg('Could not find `type` key in object.')
        
        add_type = obj.get('type', '')
        if add_type == 'configuration':
            if add_type not in obj:
                return error_msg('Could not find `{}` key in object.'.format(add_type))
            
            # Get `file_path`
            if 'file_path' not in obj.get('configuration'):
                return error_msg('Could not find `file_path` key in object.configuration.')
            else:
                try:
                    file_path = str(obj.get('configuration').get('file_path'))
                except:
                    return error_msg('`file_path` must be a string.')
            
            # Get `mtime`
            if 'mtime' not in obj.get('configuration'):
                return error_msg('Could not find `mtime` key in object.configuration.')
            else:
                try:
                    mtime = int(str(obj.get('configuration').get('mtime')))
                except:
                    return error_msg('`mtime` must be a numerical string or an integer.')
            
            # Get `payload`
            if 'payload' not in obj.get('configuration'):
                return error_msg('Could not find `payload` key in object.configuration.')
            else:
                try:
                    payload = obj.get('configuration').get('payload')
                except:
                    return error_msg('`payload` must be a string.')
            
            # Get `case_sensitive`
            if 'case_sensitive' not in obj.get('configuration'):
                return error_msg('Could not find `case_sensitive` key in object.configuration.')
            else:
                try:
                    case_sensitive = bool(obj.get('configuration').get('case_sensitive'))
                except:
                    return error_msg('`case_sensitive` must be boolean.')
            
            details = {
                'file_path': file_path,
                'mtime': mtime,
                'case_sensitive': case_sensitive,
                'payload': payload,
            }
            
            try:
                Configuration.remove(client, **details)
            except Exception as e:
                return error_msg(str(e))
            
            return configuration_added_msg(details)
        else:
            return error_msg('Could not understand the type: `{}`.'.format(obj.get('type')))
    else:
        return error_msg('Invalid method.')