how to retrieve password in django 2.0? - python

Im using ldap for user authentication in django 2.0, and i need to create an endpoint to authenticate user from another application just passing the username to then redirect them. Isnt yet something to retrieve the raw password?

Using the **encrypt** method imported from **django_cryptography.fields**, define a password attribute for the model LdapProfile (model related to User to store the user profile on ldap) and then, use this password attribute in ldap.authenticate(username, password).
password = encrypt(models.CharField(
max_length=255,
null=True,
blank=True
))

Related

How to create custom user in Django rest framework without a password?

I'm working on a project where I have to create a custom user with email address and other details but not a password, instead of a password, I want to use OTP. I have searched through the web and haven't found a decent source which can help me with it.
What I want is -
To create a custom user manager in DRF
To create a superuser without a password (using OTP for that instead)
Create a user similarly
Please help me figure this out.
1.First create user in the default User table or u can just create this user by dynamically after recieving the email from front end.
from django.contrib.auth.models import User
user = User()
user.email = "specific user email(user1#example.com)"
user.save()
2.Create an OTP table with OTP column and a user foriegn key column
3.When the user try to login, using AJAX recieve the email id to send the otp.After recieving email id generate an OTP and send email to the corresponding email.
4.Save the OTP generated in the OTP table by using foriegn key for user and otp column
OTP TABLE
otp user
1234 foriegnkey of user
5.After entering the OTP by the user verify it by user email with OTP in the OTP table
6.If valid login using 'login(request,user(object))'

django login using class based for custom user

here is my user model.
class User (models.Model):
username = models.CharField(max_length=50)
# token = models.CharField(max_length=50)
email_id = models.EmailField(max_length=50)
password = models.CharField(max_length=50)
is_deleted = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
updated_at = models.DateTimeField(auto_now_add=True, blank=True)
and here is my views for creating user
class UserView(APIView):
def post(self,request):
try:
# RequestOverwrite().overWrite(request, {'token':'string'})
user_data = UserDetailSerializer(data=request.data)
if not(user_data.is_valid()):
return Response(user_data.errors)
user_data.save()
return Response("user created successfully",status=status.HTTP_201_CREATED)
except Exception as err:
print(err)
return Response("Error while creating user")
now what i want to do is to create a token when i post a user and that token is used later for login.
also i want to validate user if it exist in database then make user authenticate.
what should i do..?any suggestion
below is my serializers.py
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','username','email_id','password','is_deleted','created_at','updated_at')
extra_kwargs = {
'password': {
'required':True,
'error_messages':{
'required':"Please fill this field",
}
}
}
First and foremost, it seems you are defining a custom user that is not in any way connected the Django auth user. It is a very very bad idea and will be difficult to get it work with most Django features. You can check out how to customize the existing user if you really need to.
As for user authentication, using the DRF Token Authentication, the flow is this way:
Client sends request to create user
If user is created successfully, it requests for an authentication token using the user's login and password
The backend verifies user's credentials and issues a token
Client makes subsequent requests with the token
If token expires or user logs out, repeat 2-4
Check out how to do these in DRF's TokenAuthentication documentation.
Your question is not very specific so I'm not sure what sort answer you are expecting but following these steps should get you going.
Token creation should be realized in model User. You can set default value to token field.
Add parameter default to User model token field:
token = models.CharField(default=tokenGenerator, max_length=50)
tokenGenerator should be some function that returns some generated token.
Secondly UserDetailSerializer should be edited to get token if it's necessary but not required.
class UserDetailSerializer(serializers.ModelSerializer):
# You can also provide this default function like in model field
# for this token field
# default=tokenGenerator
token = serializers.CharField(max_length=50, required=False)
class Meta:
model = User
fields = (..., 'token')
extra_kwargs = ...
Now your model gets generated token for newly created User.
User should be auto logged in after registration but it's not that simple.
You need to specify how do you want to communicate with API. You want token so i guess that front should request api and token should be used from cookies.
If you send request from browser eg. jQuery you need to get response with generated token and save it in cookies. Your post response in DRF:
return Response({'token': user_data.get('token')},status=status.HTTP_201_CREATED)
And now you have some more steps:
Attach token to every browser request which requests API
Create authentication class to validate every request checks for correct token
...
Now, if you read this you realize that it needs some work. If you know that and you intentionally want to create this, you need to create mentioned view authentication class.
Else try to use libs like oauth for django. That will provide you ready classes for token management.
Also as #Ken4scholars mentioned, try to use Django User model. It have good methods for validation etc. without make this done manually.

Django - Reference to model with 2 attributes

Currently i'm starting with a user management app.
The case is that we have models User (the default django user model) and an UserMail.
The UserMail has an OneToOneField to User with reference to the field username.
mail_username= models.OneToOneField(
User,
to_field='username',
on_delete=models.CASCADE)
Because we also use the database of UserMail for another app, I want the password to be in the same table, which would look like this:
mail_password = models.CharField(max_length=128)
But the mail_password has to be the password from the corresponding User.username. So if we choose an user from the User model, the password of that user should also be filled in the mail_password field
Is there a nice way to do this?

Django Python change user default attributes for authentication

In Django, the default attributes for user:
username
password
email
first_name
last_name
I would like to remove email, first_name, last_name
and replace it with company
Is that possible ? Can someone show me the process of performing an authentication session with these 3 modified attributes:
- company
- username
- password
Thanks.
You should read the documentation regarding customizing authentication in Django especially the part regarding User model substitution if you would like to create your own model.

Django override default functionalities

In django/django/contrib/auth/forms.py how to override the default method
and include the same in the users module ?
So my intention is that i want to change the username field length to 64 characters but this would not be correct to do this in django directories,because whenever new version is downloaded this file has to changed....
What exactly shoudl be changed to do this
class AuthenticationForm(forms.Form):
"""
Base class for authenticating users. Extend this to get a form that accepts
username/password logins.
"""
username = forms.CharField(label=_("Username"), max_length=30)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
#Deniz Dogan: You also have to convince login view to use the custom form:
login(request, authentication_form=MyAuthenticationForm)
If I understand you correctly, you may be able to change it by sub-classing AuthenticationForm into e.g. MyAuthenticationForm:
class MyAuthenticationForm(AuthenticationForm):
username = forms.CharField(label=_("Username"), max_length=64)
This way, you would keep the validators from AuthenticationForm, but still let the username be 64 characters long.

Categories