Re: how to restrict responses to a single server/domain ?

2015-12-30 Thread James Schneider
On Wed, Dec 30, 2015 at 5:14 AM, Billu  wrote:

> Wouldn't it be much easier to just check the IP (or mac) addresses of the
> request and if it matches the allowable ip(s), then allow otherwise deny?
>
> That's the super short and incomplete version of my response. My answer
went more into depth about the various methods to do so.

MAC addresses are only relevant if a) all of the machines exist within the
same Ethernet segment/VLAN and b) only if you have a host or hardware
firewall capable of making policy decisions based on MAC address. Django
will never see the MAC address, as it is stripped away by the OS prior to
the request being processed. TL;DR; You'll probably never refer to MAC
addresses and Django security in the same sentence.

"Just check the IP" is missing the vital answer of "how", which is a key
portion in the first line of the OP's question.

I suppose my answer did leave out the ability to check the IP at the Django
level and make decisions based on that information. Given the multiple ways
that an IP address may be made available to a Django application, I would
recommend a package such as django-ipware (
https://github.com/un33k/django-ipware) which handles a majority of these
situations in a DRY manner, although I've never used it myself. The IP
checking would be made part of your authorization checks that should be run
for each request cycle. That implementation is specific to your
environment, so I can't really comment further, although Django 1.9 made
some great strides in making such permission checks easy to integrate. For
<1.9, these checks would probably muddy up your code, but are still
possible, especially if django-braces is used (which is the package that
the authorization changes to 1.9 are modeled after).

I doubt I would ever do source IP checks in the application. That's what
firewalls are for. Honestly, I'd much rather go with a true API key system,
as it is much more flexible (especially if your API consumers live in
multiple IP address segments that may/probably will change over time) and
provides similar protection. If you find a trusted host is compromised, you
simply invalidate the API key. Other processes using a different API key
can continue to function from the same host. With strictly IP checking and
no other authorization, you have to block the host entirely, which may or
may not be acceptable.

Full disclosure, I'm a network administrator by trade, so I'm generally
biased towards network-level protections, and under the (usually correct)
assumption that most application developers do a poor job of securing their
applications, even when those applications cost more than a year's salary
in licensing and are backed by Fortune 500 companies. Not that all
applications are that way, but personal experience has left me a bit
cynical and distrusting. Heck, we have big-money applications that still
send service credentials across the network using straight HTTP and no
encryption. App admins get mad when they create a new service account, and
five minutes later you pull it off the network and read the password back
to them while troubleshooting. Fun for me, though. :-D

-James

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciUo2abWpuQp_q_eFJXn1bFtS2QSFr0-OnLZOTfm%2BOa_%2Bw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Working with Django signals

2015-12-30 Thread Bernardo Garcia


I have a custom users schema in Django for work with roles or users type, 
creating an application named userprofile which will be or will setup my 
custom user model.

In my settings.py I have the following configuration:

INSTALLED_APPS = [
...
'userprofile',]#Custom model Users
AUTH_USER_MODEL = 'userprofile.User'


I customize my User class (userprofile/models.py) that inherit of the 
AbstractUser class for add some fields to my User model due to my 
requirements demanded me.

I also create these another models for roles/profile users (MedicalProfile, 
PatientProfile, PhysiotherapistProfile) with their own fields or attributes


In addition MedicalProfile, PatientProfile, PhysiotherapistProfile have a 
OneToOneField relationship with my custom model/class User so:


from __future__ import unicode_literals
from django.conf import settingsfrom django.contrib.auth.models import 
AbstractUserfrom django.db import models
#from django.contrib.auth import get_user_model

from django.dispatch import receiverfrom django.db.models.signals import 
post_save

# Extending Django's default User# 
https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-django-s-default-user#
 We inherit from AbstractUser class to add some fields/attibutes to our user 
model# 
https://github.com/django/django/blob/master/django/contrib/auth/models.py#L297#
 Differentes between AbstractUser and AbstractBaseUser# 
http://stackoverflow.com/questions/21514354/difference-between-abstractuser-and-abstractbaseuser-in-djangoclass
 User(AbstractUser):
is_medical = models.BooleanField(default=False)
is_physiotherapist = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
slug = models.SlugField(max_length=100, blank=True)
photo = models.ImageField(upload_to='avatars', null = True, blank = True)


# We get the profiles user according with their type
def get_medical_profile(self):
medical_profile = None
if hasattr(self, 'medicalprofile'):
medical_profile=self.medicalprofile
return medical_profile

def get_patient_profile(self):
patient_profile = None
if hasattr(self, 'patientprofile'):
patient_profile = self.patientprofile
return patient_profile

def get_physiotherapist_profile(self):
physiotherapist_profile = None
if hasattr(self, 'physiotherapistprofile'):
physiotherapist_profile = self.physiotherapistprofile
return physiotherapist_profile

# We redefine the attributes (create db_table attribute) in class Meta to 
say to Django
# that users will save in the same table that the Django default user model
# 
https://github.com/django/django/blob/master/django/contrib/auth/models.py#L343
class Meta:

db_table = 'auth_user'
class MedicalProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)

class PatientProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)

class PhysiotherapistProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)

"""
So we’re defined a signal for the User model, that is triggered every time a 
User instance is saved

The arguments used in the create_profile_for_new_user  are:
   sender: the User model class
   created: a boolean indicating if a new User has been created
   instance: the User instance being saved
"""@receiver(post_save, sender=settings.AUTH_USER_MODEL)#def 
create_profile_for_new_user(sender, instance, created, **kwargs):def 
create_profile_for_new_user(sender, instance, created, **kwargs):
user = instance
# - Begin debug--
import ipdb
#ipdb.set_trace()
#
if created:
#ipdb.set_trace()
if user.is_medical:
ipdb.set_trace()
profile=MedicalProfile(user=instance)
profile.save()
"""
This signal checks if a new instance of the User model has been created,
and if true, it creates a Profile instance with using the new user instance.
"""


*My Question*

I want to focus my question in relation about of the post_save signal 
operation, this mean in the create_profile_for_new_user() method:


@receiver(post_save, sender=settings.AUTH_USER_MODEL)def 
create_profile_for_new_user(sender, instance, created, **kwargs):
user = instance
# - Begin debug--
import ipdb
#
if created:
if user.is_medical:
ipdb.set_trace()

Re: Migrate django project to eclipse/pydev ide

2015-12-30 Thread CLIFFORD ILKAY

On 30/12/15 02:00 PM, Gary Roach wrote:

On 12/22/2015 04:53 PM, Clifford Ilkay wrote:

On 22/12/15 07:05 PM, Andrew Farrell wrote:

Could you also tell us:
1) Why you need to switch to Eclipse specifically rather than 
PyCharm , SublimeText 
, or (the one I use) Atom 
?


Andrew, there are things Eclipse does that those three editors don't 
do. For example, the Mylyn plugin and how it integrates Eclipse with 
Trac is unparalleled. I also find debugging with Eclipse to be quite 
good for the odd time that I need to step through code as opposed to 
prototyping in iPython.


Gary, move your existing project to some directory outside of 
wherever your default workspace is and create a new Django PyDev 
project with the same name as your existing project. Look inside the 
directory that got created and you'll see a couple of hidden files, 
.project and .pydevproject. Move those somewhere safe, delete the new 
project directory, move the existing project directory to the default 
workspace, and move the hidden files to the project directory.


You can also import an existing project.

As for virtualenv or venv, all you have to do is go to the project 
properties, select "PyDev - Interpreter/Grammar", "Click here to 
configure an interpreter not listed." and add the Python binary for 
your venv.
Thanks for the help. I am still a little confused about venv. Since I 
lock the interpreter to the specific copy of python in the virtual 
environment for a specific project, do I still have to activate and 
deactivate venv on the command line or can I ignore this step.


As long as you've done the "Click here to configure an interpreter not 
listed." noted above, you don't have to activate/deactivate the venv at 
a shell. All you're doing with activate/deactivate is changing 
$PYTHONPATH on that particular shell.


Regards,

Clifford Ilkay

+1 647-778-8696

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/56845754.1020803%40dinamis.com.
For more options, visit https://groups.google.com/d/optout.


How change info about register user

2015-12-30 Thread Dariusz Mysior
In Django\contrib\auth\forms.py I have clas like below. When I use it and 
create a form to register a user with fields user, password, confirm 
password I have also info about correct characters to register user. How 
can I change this info?

class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))

class Meta:
model = User
fields = ("username",)

def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2

def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/feda6714-4e74-42f9-a1f8-1d01f028549b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate django project to eclipse/pydev ide

2015-12-30 Thread Gary Roach

On 12/22/2015 04:53 PM, Clifford Ilkay wrote:

On 22/12/15 07:05 PM, Andrew Farrell wrote:

Could you also tell us:
1) Why you need to switch to Eclipse specifically rather than PyCharm 
, SublimeText 
, or (the one I use) Atom 
?


Andrew, there are things Eclipse does that those three editors don't 
do. For example, the Mylyn plugin and how it integrates Eclipse with 
Trac is unparalleled. I also find debugging with Eclipse to be quite 
good for the odd time that I need to step through code as opposed to 
prototyping in iPython.


Gary, move your existing project to some directory outside of wherever 
your default workspace is and create a new Django PyDev project with 
the same name as your existing project. Look inside the directory that 
got created and you'll see a couple of hidden files, .project and 
.pydevproject. Move those somewhere safe, delete the new project 
directory, move the existing project directory to the default 
workspace, and move the hidden files to the project directory.


You can also import an existing project.

As for virtualenv or venv, all you have to do is go to the project 
properties, select "PyDev - Interpreter/Grammar", "Click here to 
configure an interpreter not listed." and add the Python binary for 
your venv.
Thanks for the help. I am still a little confused about venv. Since I 
lock the interpreter to the specific copy of python in the virtual 
environment for a specific project, do I still have to activate and 
deactivate venv on the command line or can I ignore this step.


Thanks for your help

Gary R

--
Regards,

Clifford Ilkay

+1 647-778-8696
--
You received this message because you are subscribed to the Google 
Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 
an email to django-users+unsubscr...@googlegroups.com 
.
To post to this group, send email to django-users@googlegroups.com 
.

Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5679F095.70103%40dinamis.com 
.

For more options, visit https://groups.google.com/d/optout.


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/568429E6.4010705%40verizon.net.
For more options, visit https://groups.google.com/d/optout.


Re: how to restrict responses to a single server/domain ?

2015-12-30 Thread Billu
Wouldn't it be much easier to just check the IP (or mac) addresses of the 
request and if it matches the allowable ip(s), then allow otherwise deny?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/35e1f271-2fe6-4523-8d39-7724cc73aa96%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: wsgi.py apache segmentation fault

2015-12-30 Thread Baris Adrian
hi Eugenio,

Did you get a solution to this problem.

If so what? because i am stuck and i could appreciate the help.

Kindest REgards

On Thursday, October 8, 2015 at 5:45:40 PM UTC+3, Eugenio Trumpy wrote:
>
> Hello everybody,
>
> I'm very not so expert on django, I'm at the first experience.
> I'm using django as backhand of geonode application.
>
> Geonode works quite fine, however during a save map request from client 
> side I got this apache2 segmentation fault:
>
> [Thu Oct 08 15:30:38.037330 2015] [core:error] [pid 10101] [client 
> X.X.X.X:50787] End of script output before headers: wsgi.py, referer: 
> http://my_server_name/maps/new
> [Thu Oct 08 15:30:38.292052 2015] [core:notice] [pid 2697] AH00052: child 
> pid 10004 exit signal Segmentation fault (11)
>
> I discovered this page on similar issue:
>
> https://code.google.com/p/modwsgi/wiki/FrequentlyAskedQuestions
>
> but I checked and I have not the mod_python installed.
>
> Can somebody give me hints on how to solve this problem?
>
> Best
>
> Eugenio
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e6042667-df1e-47c2-b8dd-6ce5046ae672%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: django 1.9 - application does not

2015-12-30 Thread Fred Stakem
I had the same issue and I found it was coming from django-rest. I 
uncommented the app and it disappeared. Not sure the solution.

On Thursday, December 24, 2015 at 1:32:11 AM UTC-5, Shekar Tippur wrote:
>
> Hello,
>
> I have a application on my laptop and I am trying to move it to AWS.
> I have installed django 1.9 on aws server under a virtualhost and scp'd 
> all my local files to aws server.
>
> Under the virtualhost, when I try to run the server, I get an error.
>
>
> $ python3.4 manage.py runserver 0.0.0.0:8000
>
> Traceback (most recent call last):
>
>   File "manage.py", line 10, in 
>
> execute_from_command_line(sys.argv)
>
>   File 
> "/home/ctippur/db/dropboat_virtual/local/lib/python3.4/site-packages/django/core/management/__init__.py",
>  
> line 350, in execute_from_command_line
>
> utility.execute()
>
>   File 
> "/home/ctippur/db/dropboat_virtual/local/lib/python3.4/site-packages/django/core/management/__init__.py",
>  
> line 342, in execute
>
> self.fetch_command(subcommand).run_from_argv(self.argv)
>
>   File 
> "/home/ctippur/db/dropboat_virtual/local/lib/python3.4/site-packages/django/core/management/__init__.py",
>  
> line 176, in fetch_command
>
> commands = get_commands()
>
>   File "/home/ctippur/db/dropboat_virtual/lib64/python3.4/functools.py", 
> line 448, in wrapper
>
> result = user_function(*args, **kwds)
>
>   File 
> "/home/ctippur/db/dropboat_virtual/local/lib/python3.4/site-packages/django/core/management/__init__.py",
>  
> line 71, in get_commands
>
> for app_config in reversed(list(apps.get_app_configs())):
>
>   File 
> "/home/ctippur/db/dropboat_virtual/local/lib/python3.4/site-packages/django/apps/registry.py",
>  
> line 137, in get_app_configs
>
> self.check_apps_ready()
>
>   File 
> "/home/ctippur/db/dropboat_virtual/local/lib/python3.4/site-packages/django/apps/registry.py",
>  
> line 124, in check_apps_ready
>
> raise AppRegistryNotReady("Apps aren't loaded yet.")
>
> django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
>
>
> - Shekar
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e1bb5a61-5380-4390-973b-4873c7368a91%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: how to restrict responses to a single server/domain ?

2015-12-30 Thread James Schneider
>
> I'm trying to build something similar to a microservice using Django and
> can't figure out how to setup the authentication part.
>
> When I say 'microservice' I mean, we have a bunch of systems like -
> example.com  , test.com  , another.com and another.test.com (a
> subdomain). I'm going to build a REST API on test.com which needs to be
> consumed by another.com. How can I enforce this restriction? And if
> later, I wanted to allow example.com to use the API (or even allow
> general public access), how can I do this?
>
> My instincts tell me that I'm missing something obvious, but I can't seem
> to figure out what to search for.
>
> Puzzled,
> Abraham V.
>

Seems like a simple question, but as with most things relating to computer
security, the answer is "it depends (on a lot of things)".

There are dozens of ways to handle this problem, and many of them have
nothing to do with Django. You have two primary lines of defense: network
controls and authentication controls. The answers aren't necessarily
obvious, although any bit of reading on how other people have approached
the problem shouldn't be difficult to track down with a quick Google.

Network controls should be where you start, if you can, since you can
filter a majority of the Internet noise here without much effort (usually).
I'll assume that you have a host firewall such as iptables or Windows
Firewall, or a hardware firewall, that is configured to only allow the
Internet to access your server on the necessary ports for serving your web
application (likely tcp/80 and/or tcp/443). If you can narrow down the
source IP addresses or IP ranges that example.com and others will be using,
you can add these as exceptions in your firewalls instead of the broad
port-based exception I just described (or better yet as a combination of
the port-based exceptions and source IP's), while dropping requests from
anywhere else. Moving up the stack, most HTTP servers will also allow you
to specify the range of source IP's that are valid when responding to
requests, but may provide a slightly weaker security posture since I would
assume the web server would not be protected by firewalls, and could be
subject to buffer-overflows, bad request exploits, etc. I'd recommend using
both strategies concurrently, keeping them in sync with a configuration
management tool. You would still be exposed if a service/host at another.com
were compromised (which is exactly how Target was compromised by an
attacker pivoting through a 3rd party vendor), but at least you've
significantly lowered your attack surface. Another option would be to hide
the entire set of microservices behind a VPN and require the consumer to
first connect to the VPN in order to gain access, which may or may not be
feasible. Plenty of permanent branch VPN solutions are available so that
individual users don't need to be bothered with setting up VPN access.
Network control is primary about controlling where and how users are
connecting at a low (network) level.

Your HTTP server should support the recommended versions of TLS (I believe
the SSL protocol is now totally deprecated and should be avoided, although
the term SSL is still commonly used to refer to TLS). I personally believe
it should just be assumed that TLS services are used by default. There's
not really any excuse not to use encrypted connections for any sort of
publicly available service over the Internet, even between two known
entities.

Moving further up the stack, we find authentication, authorization, and
accounting controls. There are two common ways to authenticate/authorize
web requests to microservices: via service account user/pass, or via an API
key/token that is given to those services. User/pass is common where a
human is directly controlling a local app that will consume those services
(and usually on an infrequent basis), and the API token is common where
there is no clear logical connection between a human and the request
(standalone services pulling data for reporting on a regular basis, etc.).
Sometimes the user credentials are only used to retrieve an API token, and
then that token is used for all API calls by an end-user application. Of
course, either method can be employed for most scenarios. Token
authentication will be a likely path for you.

Your microservices should not respond with anything other than error
messages unless the requester has validated credentials (unless you have
some API calls that are publicly accessible, in which case those calls
should succeed regardless of whether or not the requester provides
credentials). Each authentication type has it's own implementation strategy
and limitations, and will be determined by your HTTP server choice (if
using basic authentication via the HTTP server) and/or Django
authentication strategy. For example, Django REST Framework supports either
method (along with session authentication), and has library calls to
generate and assign API tokens to users, or can simply 

how to restrict responses to a single server/domain ?

2015-12-30 Thread Abraham Varricatt
I'm trying to build something similar to a microservice using Django and 
can't figure out how to setup the authentication part. 

When I say 'microservice' I mean, we have a bunch of systems like - 
example.com  , test.com  , another.com and another.test.com (a subdomain). 
I'm going to build a REST API on test.com which needs to be consumed by 
another.com. How can I enforce this restriction? And if later, I wanted to 
allow example.com to use the API (or even allow general public access), how 
can I do this?

My instincts tell me that I'm missing something obvious, but I can't seem 
to figure out what to search for.

Puzzled,
Abraham V.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/93f24cbb-3ab5-4903-ba78-89446b629e30%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.