Can django_neomodel be used with the built in Django authentication system? - django-models

I'm wondering what the best approach is to store user authentication data in a neo4j database with django using the inbuilt auth system.
Has anybody got any experience of doing so?
I'm imagining that it has something to do with subclassing the AbstractBaseUser and BaseUserManager but for the life of me I can't figure it out.
Would very much appreciate a code snippet if anybody has achieved this before.
Many Thanks

If you want to extend the Django User model, first check this article. It shows different ways of extending the User model. In my last workaround I needed all the information in Neo4j so I adapt my model to have the fields of the user in my model (It was a model of Student). Whenever a new student register to the app, I have a signal to react after the save (post_save) and it stores the password and the username. You can explore the Django signals here
For the model I have:
class StudentProfile(DjangoNode):
first_name = StringProperty(max_length=30)
last_name = StringProperty(max_length=150)
email = EmailProperty()
birth = DateProperty()
username = StringProperty(max_length=150, unique=True)
password = ''
For the signal:
#receiver(post_save, sender=StudentProfile, dispatch_uid='create_user_student')
def create_user_student(sender, instance, created, **kwargs):
if created:
user = User.objects.create_user(instance.username)
user.set_password(instance.password)
user.save()
#receiver(post_delete, sender=StudentProfile, dispatch_uid='delete_user_student')
def delete_user_student(sender, instance, **kwargs):
User.objects.filter(username=instance.username).delete()
Besides the main view of the StudentProfile, I have a view that uses the built-in Django authentication system:
from django.contrib.auth import authenticate, login as do_login, logout as do_logout
...
#api_view(["POST"])
def login(request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
do_login(request, user)
return Response({'login': 'ok'}, status=status.HTTP_200_OK)
return Response({'login': 'Error on credentials'}, status=status.HTTP_403_FORBIDDEN)

Related

How to get user information from database when the only thing in client browser is the AuthToken?

Building my first app with a real backend.
In my app, when a user registers or logs in (with username and password), a token is saved to the cookies of their browser. After registration (or when logging in), I can easily return information pertaining to this particular user (name, id, etc.).
# Django REST backend for loggin in and getting user token
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(
data=request.data, context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email,
'user_type': user.user_type,
})
Next time the user accesses the app in the same device, the token will be there and I can make the http requests for which a token is necessary. However, since I won't be logging the user in again (not asking for username and password every single session), I won't get that user's additional information.
In my React app I would like to have the user set in state at all times, e.g. user = {first_name: 'john', user_type: 'p'} but I don't know how to get the user info when the only thing I have is their token.
I am more than welcome to criticism to this approach and to learning what's the best way of doing this. I don't even know if keeping the user in state is the right way to do things...
I tried this:
class UserAPI(generics.RetrieveUpdateAPIView):
serializer_class = UserSerializer
def get_object(self):
print(self.request.user)
return self.request.user
curl -H "Authorization: Token b2e33463esdf8as7d9f8j34lf98sd8a" http://localhost:8000/current-user/
but the return value from self.request.user is AnonymousUser
If it's not sensitive information, such as username, id, user type, first name, etc. you can store this in localStorage.
problem was in my settings.py file:
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
There are two parts of answer to this question. first part is criticism to your approach and little bit of guidance towards better approach, second part of the answer is about your actual question.
Lets start with second part first.
From the look of your code, you are already storing the key in Token Table along with User. You can easily get the user by first running this query token = Token.objects.get(key=key).select_related('user') and then simple user = token.user will give you token.
Coming to first part now.
Since you are using DRF, you do not need to override the class unless extremely necessary. If you want user with each approved request, what you can do is simply add your Token verification class to Settings of DRF
I had the same problem but I found how to do that this code will help you
if request.user.is_authenticated:
user = Account.objects.filter(username=request.user)
serializer = UserSerializer(user, many=True)
return Response(serializer.data)
else:
return Response('You have to login first')

How to show content to staff user only using React and DRF

I have a blog create view, where admin or staff user can only create blog, it is restricted from normal user and it is working fine.
Goal: Now I want to display the create blog button on the website to admin or staff user only if they logged in from their account.
I have user detail view that is calling on the very beginning of site loading, How can I check if the user is admin or staff user or normal user in response?
I am using React in frontend with redux.
What I have done so far
path('user/', UserDetailsView.as_view(), name='rest_user_details'),
class UserDetailsView(RetrieveUpdateAPIView):
serializer_class = UserDetailsSerializer
permission_classes = (IsAuthenticated,)
def get_object(self):
return self.request.user
def get_queryset(self):
return get_user_model().objects.none()
One possible solution is to overwrite your UserDetailsSerializer and added a field like is_admin_user.
We are going to use serializerMethodField from Django-Restframework serializers.
class UserDetailsSerializer(serializers.ModelSerializer):
is_admin_user = serializers.SerializerMethodField()
class Meta:
model = User
fields = ('is_admin_user',) // And all other necessary fields
def get_is_admin_user(self, obj):
return obj.is_staff # this will return true for self.is_staff user
Our main goal is to pass some information to frontend about user role, so that from this information we can decide whether to show create blog button or not.

Using webapp2 session as namespace name. How?

I have an application which is school based. Each tenant is a different school and to access the application all users for each school have the same password.
Alongside this each school user has to have a google email if they want access to the application. So the application first checks they are a google user, checks wether they are a school user and finally checks that their google email is in the school user list before they are allowed access to any page.
The school user part is using session data from webapp2 sessions to ensure each request they have appropriate access
class Handler(webapp2.RequestHandler):
def dispatch(self):
# Get a session store for this request.
self.session_store = sessions.get_store(request=self.request)
try:
# Dispatch the request.
webapp2.RequestHandler.dispatch(self)
finally:
# Save all sessions.
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
# Returns a session using the default cookie key.
return self.session_store.get_session()
When a user logins I check the password then create a session which checks their password / user combination every request.
def check_u(self):
try:
uid = self.session.get('user')
parent = self.session.get('school-id')
udl = m.models.User.by_id(int(uid),parent)
if uid and udl:
return udl
else:
return False
except (TypeError,AttributeError):
return False
A parent datastore entity for each different school is used called MetaSchool which I have been currently using to ensure that there is no data leak across schools. Each datastore entry uses this parent session key as a way of setting the datastore entry with MetaSchool as parent then using this session key again to read back this data.
This method works but is onerous. I would like to use namespace as a way of separating the data but would like to use the Metaschool id as the name.
def namespace_manager_default_namespace_for_request():
### Here I need to get ------ parent = self.session.get('school-id')
### use this session to gain the MetaSchool key id
### Set this as the namespace name
Basically trying to emulate from the docs the below scenario
from google.appengine.api import users
def namespace_manager_default_namespace_for_request():
# assumes the user is logged in.
return users.get_current_user().user_id()
I am having difficulty getting the session data from Handler object???
Any thoughts
This is what I came up with.
from google.appengine.api import namespace_manager
from webapp2_extras import sessions
def namespace_manager_default_namespace_for_request():
session = sessions.get_store()
s = session.get_session()
name = s.get('key')
if name:
return name
else:
return namespace_manager.set_namespace('string')

How to Refer a Parent table's key instead of the complete object instance in Django

I have just started working on Django, angularjs , The issue currently i am facing is I have created a model in django as following
**class Car_Booking(models.Model):
owner = models.ForeignKey('auth.User', related_name='booking_user')
car_id=models.IntegerField(max_length=4,default=1)
extra_field1=models.CharField(max_length=100,null=True)
extra_field2=models.CharField(max_length=50,null=True)
extra_field3=models.CharField(max_length=50,null=True)**
The Serializer is as following
**class CarBookingSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Car_Booking
fields = ('car_id','owner','extra_field1','extra_field2','extra_field3')**
And view is as following
**class CarBookingViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = Car_Booking.objects.all()
serializer_class = CarBookingSerializer
permission_classes = (permissions.AllowAny,
def perform_create(self, serializer):
serializer.save(owner=self.request.user)**
Now i developed a front end on Angularjs, the templelates i built were on the same server say localhost:8000 so when i call the view to insert the data by passing car_id, extra_field1, extra_field2 and extra_field 3 it gets saved successfully because i already get logged in and saved the user information into the cookies so i guess the Owner field is resolved automatically. Now when i call the same view from the IONIC framework on server localhost:5000(port is differnt) it give me the error, "Owner must be a user instance". I have searched a lot but can not find how to send the user authentication information, or save it accross the domains. Secondly i have tried to pass the owner_id but when i write the owner_id into the serializer it says "Owner_id is not a valid modlebase" but while calling throught the command prompt i can set the owner_id, Any Help on the following questions
***1. How can i send the username and password along the Post URL
How can i set the owner_id instead of OWNER object instance.***
Regards

Detecting first time login of user into application (Google Appengine)

My app requires users to login using their google account.
I have this set in my App.yamp file:
url: /user/.*
script: user.py
login: required
Now when any user tries to access files under /user/secret.py he will need to authenticate via google, which will redirect the user back to /user/secret.py after successful authentication. Now the problem I am facing is when the user is redirected back to the app, I cannot be sure if this is the first time the user has logged in or is it a regular user to my site who has come back again from just the user object which google passes using users.get_current_user() .
I thus need to maintain state in the datastore to check if the user already exists or not everytime. If he does not exist i need to create a new entry with other application specific settings.
My question is: Is there some easier way to handle this? without having to query the datastore to figure if this is a first time user or a regular one?
No, Google doesn't keep track of if a user has logged in to your app before. Since you presumably need to store some sort of state against the user, the simplest way is to try and retrieve the user's record from the datastore. If they don't have one, you can send them to the registration screen to gather this information. You can use memcache to cache a user's information and avoid extra datastore round-trips.
I tend to use my own user and session manangement
For my web handlers I will attach a decorator called session and one called authorize. The session decorator will attach a session to every request, and the authorize decorator will make sure that the user is authorised
(A word of caution, the authorize decorator is specific to how I develop my applications - the username being the first parameter in most requests)
So for example a web handler may look like:
class UserProfile(webapp.RequestHandler):
#session
#authorize
def get(self, user):
# Do some funky stuff
# The session is attached to the self object.
someObjectAttachedToSession = self.SessionObj.SomeStuff
self.response.out.write("hello %s" % user)
In the above code, the session decorator attaches some session stuff that I need based on the cookies that are present on the request. The authorize header will make sure that the user can only access the page if the session is the correct one.
The decorators code are below:
import functools
from model import Session
import logging
def authorize(redirectTo = "/"):
def factory(method):
'Ensures that when an auth cookie is presented to the request that is is valid'
#functools.wraps(method)
def wrapper(self, *args, **kwargs):
#Get the session parameters
auth_id = self.request.cookies.get('auth_id', '')
session_id = self.request.cookies.get('session_id', '')
#Check the db for the session
session = Session.GetSession(session_id, auth_id)
if session is None:
self.redirect(redirectTo)
return
else:
if session.settings is None:
self.redirect(redirectTo)
return
username = session.settings.key().name()
if len(args) > 0:
if username != args[0]:
# The user is allowed to view this page.
self.redirect(redirectTo)
return
result = method(self, *args, **kwargs)
return result
return wrapper
return factory
def session(method):
'Ensures that the sessions object (if it exists) is attached to the request.'
#functools.wraps(method)
def wrapper(self, *args, **kwargs):
#Get the session parameters
auth_id = self.request.cookies.get('auth_id', '')
session_id = self.request.cookies.get('session_id', '')
#Check the db for the session
session = Session.GetSession(session_id, auth_id)
if session is None:
session = Session()
session.session_id = Session.MakeId()
session.auth_token = Session.MakeId()
session.put()
# Attach the session to the method
self.SessionObj = session
#Call the handler.
result = method(self, *args, **kwargs)
self.response.headers.add_header('Set-Cookie', 'auth_id=%s; path=/; HttpOnly' % str(session.auth_token))
self.response.headers.add_header('Set-Cookie', 'session_id=%s; path=/; HttpOnly' % str(session.session_id))
return result
return wrapper
def redirect(method, redirect = "/user/"):
'When a known user is logged in redirect them to their home page'
#functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
if self.SessionObj is not None:
if self.SessionObj.settings is not None:
# Check that the session is correct
username = self.SessionObj.settings.key().name()
self.redirect(redirect + username)
return
except:
pass
return method(self, *args, **kwargs)
return wrapper
Can you not just set a Cookie the first time the user logs in and check for this? If they're a new user it won't be there and but if they're an old user it will be. It's not 100% accurate since some users might clear their cookies but it might do depending on what it is you want to achieve.
If you're using Django in your application managing Cookies is pretty straightforward.
I agree that managing your own authenticated users is the best way to approach this problem. Depending on your application scope obviously but at the very least an AuthUser(Model) class that contains the UserProperty for the users that have logged in with your account.
...
class AuthUser(db.Model):
user = UserProperty(required=True)
...
Then when a user logs in just
...
user = users.get_current_user()
user_exists = AuthUser.gql('where user = :1', user) # or easy check db.GqlQuery("select __key__ from AuthUser where user = :1", user)
if user_exists:
# do user has been before stuff
else:
# do first time user stuff
...
Alternately a super easy way to do this is have a Model for your site that has a ListProperty(users.User) and then you can easily check the list to see if the user has been into your app before.
...
class SiteStuff(db.Model):
auth_users = ListProperty(users.User)
...
and when they log in: check if they are in the list; if not, you add them to the list, put() it and do whatever you need to do for first time users. If you find them in there then do the other stuff.

Resources