In my Django project I need two type of users:
- users authenticated with login/password (django.contrib.auth.models.User)
- users authenticated with token (Django REST Framework)
What's more I wish I could keep both of them in one table and display only "User" page in admin panel.
What would you suggest will be the best solution?
The token from DRF doesn't create a new User table it just creates a Token table with a one-to-one relationship with the existing User table, so you'll always have a single table (admin page) "User"
You decide what users should have a Token. for example:
# create API Token
regular_user = User.objects.create_user(....)
api_user = User.objects.create_user(...)
Token.objects.create(user=api_user)
now regular_user can only access using login/password (since he doesn't have a Token) and api_user can do both
Hope this helps
Related
I have a custom user model
class User(models.Model):
fields...
It also has a email, password field among other detail fields. I want to use the simplejwt JWT authorization which takes email and password as input and generates JWT Tokens. Most tutorials include creating a superuser and passing username password of the superuser to get the token, But I want to do this for my custom user model.
REST implementation of Django authentication system. DJOSER
Getting Started with Djoser
Also, you need a MOD HEADER which is an Extension in Chrome
Add it from here
Once your Django project is up and running go to
localhost:8000/auth/jwt/create/ for creating access token by submitting username and password (ie: POST method)
once access token is created you need to set it in MOD HEADER in Request Header and you are good to go.
it's a JSON web token that's why you need to prefix it with JWT and then access token
django-simple-jwt generates the access and refresh tokens through the obtainTokenPairView. This views calls the authenticate function from django. Therefore if you have set up a custom user model following django guidelines, to use the email in place of the username, django-simple-jwt should work out of the box
Otherwise, you still have the option to create your own view and Generate the tokens manually
Hi there I am currently starting a new rest api project with django. Normally when I start a new project I do a lot of planning and get a idea of how I want to build my app. For this app I want to use token authentication but can't find enough resources for this topic.
Can anyone tell me these two things, how to check if a user is logged in/authenticated and how to check which user is logged in(of course with token authentication in django). Thank you in advance.
Extra info(you don't need to read this):
The reason I want to use this kind of authentication is because I don't want to use the built in django models for my user model because my User model has to have some specific fields for this web app, obviously I can work my way around this but its not very efficient so I figured I'd use token authentication.
If you will use rest_framework.authtoken https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication you can set in each view to check whether the user is authenticated for admission or not. For example:
class UserList(generics.ListAPIView):
"""List all users"""
permission_classes = [IsAuthenticated] # allowed only by authenticated
serializer_class = UserCreateSerializer
queryset = CustomUser.objects.all()
To check which user is logged in, rest_framework.authtoken creates a table in the database that contains the token, the user and the time the token was created
I have a Django API that uses JWT for authentication (see this tutorial). Currently it gets the token fine and attached to that is a user_id for React.
Example token returned from /api/auth/token/obtain:
{
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwidXNlcl9pZCI6MSwiZXhwIjoxNTI1NjgxMjU3LCJqdGkiOiJlZTk4Y2I2ZmI3ZTk0OWVlYmNiNDU4NjA2N2ZmMGYzMyJ9.-8lXUwWivg4vaucDGRj7InqDQrn8WuflvwL1ebNHlFg",
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsInVzZXJfaWQiOjEsImV4cCI6MTUyNTc2NzM1NywianRpIjoiMmM4NDBlZWI3NWE0NDFkMmFiMGQxZjViNDdkYTcyNDgifQ.G70wMPL2OdrDx06HulGdVS3KQvZvNtjKoli1rKYXbxs"
}
But if I have an endpoint that alters a model created and owned by that user (it has an model field where owner is the pk of the User), how can I compare if that model is owned by the user when using JWT for authentication?
When I was using Django views, it was just simply check if the values were the same based off the user from the request, but with JWT the user doesn't seem to actually log in to the Django auth system.
I want to do some custom auth for my users with username or email with password. At the first time of logging with email and password the api should return me the respective user token. For all other operations with the api I need to make use of token, which I get at time of login.
And I need a custom model to store all user info like username, password, phone, email, token etc.
How to achieve this in django restframework.
Please guide me to achieve this. Thanks in advance.
Django rest-framework has a built in token system which can be used to distribute and authenticate tokens. Below is a sample of how to use it.
Create TOKEN
from rest_framework.authtoken.models import Token
user = User.objects.get(pk=some_pk)
token = Token.objects.create(user=user)
Authenticate token
if Token.ojects.get(key=token) # token is sent by client side
# do some task as auth is successful
If you want to extend the default User model then create a new model and put a onetoone field in your custom model which references default User model.
class AppUserProfile(models.Model):
user = models.OneToOneField(User)
... # add other custom fields like address or phone
I have a project I am working on that requires some users to be authenticated via facebook and others to sign up using a custom model. The facebook users will not have the same sign up credentials as the custom model. For example- there will be a restaurant owner sign up and a customer signup. The customer will not have to put a street address location, they can simply login.
My intentions were to have the restaurant owners sign up via the custom profile model and the facebook users to simply login via the defualt social auth, but whenever I combine the two, social auth starts to use the custom model because I define a custom user model within settings. Is there a way to distinguish to the python social auth backend to only use the default or a way to update my current custom user model to have a facebook segment. I have searched the web for a long time for this, but can not seem to find anything that can combine the two besides (1), but it did not work successfully. I can however get one or the other working successfully depending on if I specify a user model in my settings.py file or not.
It is quite simple, but I do not know of a way to get social auth to look at its default and djangos authentication to look at my custom model.
(1)-http://code.techandstartup.com/django/profiles/
In order to distinguish one type of user from another, you can do something like this:
First, in your settings file, store the following:
FIELDS_STORED_IN_SESSION = ['type']
This will be stored in strategy parameter in every function of pipeline
Then, change the pipeline wherever necessary. For example, in your create_user pipeline function, you can do this:
user_type = strategy.session_get('type')
if user_type != 'customuser':
return {
'is_new': True,
'user': strategy.create_user(**fields)
}
else:
return {
'is_new': True,
'user': create_restaurant(**fields)
}