django-rest-auth password reset sending wrong domain in email - django

I'm trying to test my password reset configuration on my localhost using django-rest-auth. The email verification and registration work, and I can trigger a password reset event and send an email, but the email contains the wrong domain. Right now it is passing a link containing my-site.com as the domain instead of 0.0.0.0:8000 as the domain. I am running the app inside a docker container which is why it is 0.0.0.0:8000 instead of 127.0.0.1:8000.
Current result:
You're receiving this email because you requested a password reset for your user account at My Site.
Please go to the following page and choose a new password:
http://my-site.com/auth/password-reset/confirm/OA/55d-7dc2614593146ac3ce82/
Your username, in case you've forgotten: testaccount
Thanks for using our site!
The My Site team
Expected result
You're receiving this email because you requested a password reset for your user account at My Site.
Please go to the following page and choose a new password:
http://0.0.0.0:8000/auth/password-reset/confirm/OA/55d-7dc2614593146ac3ce82/
Your username, in case you've forgotten: testaccount
Thanks for using our site!
The My Site team
My url file for my registration is:
from django.urls import path, include
from allauth.account.views import ConfirmEmailView
from . import views
urlpatterns = [
path('registration/account-email-verification-sent/', views.null_view, name='account_email_verification_sent'),
path('registration/account-confirm-email/<key>', ConfirmEmailView.as_view(), name='account_confirm_email'),
path('registration/complete/', views.complete_view, name='account_confirm_complete'),
path('password-reset/confirm/(<uidb64>/<token>/', views.null_view, name='password_reset_confirm'),
path('', include('rest_auth.urls')),
path('registration/', include('rest_auth.registration.urls')),
]
I ran across another post that suggested changing the site id, but I'm not sure this is correct.
How do I get it to pass the currently served domain instead of the site id domain?

Easy Solution
Step 1: Go to /admin/sites/site/, You'll see something similar as below,
Step 2: Edit the existing entry with following value then save it
Domain name: 0.0.0.0:8000
Display name: Your Site Name

Related

Example.com in django password reset

I have set up my django project to enable password reset but when the password reset mail is sent, i get the line https://example.com/accounts/reset/Mg/... . Exampple.com is not in any way related to my site. I have tried to remove it such that it reads my site url but to no avail
For future reference, django contrib auth uses current site domain provided by Site model in django.contrib.sites.models.
To check which one do U have configured, enter into the shell with the desired settings and type:
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
print(current_site.domain)
This will show what domain will be used to construct absolute links like in this case, to reset the password.
Check admin. You can see site domain in 'Sites'. Default of the site domain is 'example.com', so if you change the site domain to your domain, you can resolve it.

Django All_auth/rest_auth e-mail address validation using HTTP GET request

I use Django all_auth and rest_auth for a backend service of a mobile app.
I integrated the registration and login API and all works fine.
Now I have to integrate the e-mail address validation logic.
After the registration (without social), I have to send an e-mail with the link that the user will use to validate your account.
I added this configurations into my Django settings:
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
SOCIALACCOUNT_EMAIL_VERIFICATION = 'none'
Also this works fine. I'm able to receive the e-mail after the registration of a new account. In the received e-mail I have the link to validate the account also.
I would like to have the validation of the e-mail when the user simply will click on the link.
So, I would like to use only the GET HTTP method.
I added, as suggested into the documentation, this setting also:
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
I use this url linked to the all_auth views.
from allauth.account.views import ConfirmEmailView
url(r'^account-confirm-email/', ConfirmEmailView.as_view(), name='account_email_verification_sent'),
url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', ConfirmEmailView.as_view(), name='account_confirm_email'),
But, if I try to click on the link from the received mail, I obtain this error:
KeyError at /account-confirm-email/NzU:1hjl8A:z5Riy8Bjv_h0zJQtoYKuTkKvRLk/
'key'
/allauth/account/views.py in get
self.object = self.get_object() ...
▶ Local vars
/allauth/account/views.py in get_object
key = self.kwargs['key'] ...
▶ Local vars
This seams that setting is not sufficient to have the possibility to use the e-mail validation with GET method.
Have I to overwrite the custom Django view for this?
Looks like you're using the same view two times where you should use another view class. Following change should fix it:
from allauth.account.views import ConfirmEmailView, EmailVerificationSentView
# ...
url(
r'^account-confirm-email/',
EmailVerificationSentView.as_view(), # This is changed
name='account_email_verification_sent',
),
url(
r'^account-confirm-email/(?P<key>[-:\w]+)/$',
ConfirmEmailView.as_view(),
name='account_confirm_email',
),
# ...

django-rest-auth google social auth by access token

I'm using django-rest-auth for social auth via API.
I've configured Facebook and it works perfectly but I've got some issues with Google social auth.
I've added to INSTALLED_APPS:
allauth.socialaccount.providers.google',
Created views:
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
class CustomGoogleOAuth2Adapter(GoogleOAuth2Adapter):
basic_auth = False
class GoogleLogin(SocialLoginView):
adapter_class = CustomGoogleOAuth2Adapter
client_class = OAuth2Client
Created app by admin panel
I've got access_token from https://developers.google.com/oauthplayground/
When I tried to log in by endpoint I got an error:
Reverse for 'redirect' not found. 'redirect' is not a valid view function or pattern name.
It's hard to pin point the error since you did not include the rest of your codes. The error simply means it cannot find the url with name 'redirect'. So there are 2 things you can check:
Have you put in correct urls settings for the end points as per django-rest-auth document ?
urlpatterns = [
...,
url(r'^rest-auth/', include('rest_auth.urls'))
]
Or maybe you forgot the redirect url when you specified the Google social app, as per django-all-auth document ?
Under “APIs & auth” go to “Credentials” and create a new Client ID.
Probably you will want a “Web application” Client ID. Provide your
domain name or test domain name in “Authorized JavaScript origins”.
Finally fill in http://127.0.0.1:8000/accounts/google/login/callback/
in the “Authorized redirect URI” field. You can fill multiple URLs,
one for each test domain. After creating the Client ID you will find
all details for the Django configuration on this page.

Allauth Django Login URL

allauth django
I would like to redirect a user to a "dynamic" login page.
I am currently being redirected to accounts/login
but I would like it to be
accounts/login/?name=Bob for user Bob
accounts/login/?name=Carl for user Carl
accounts/login/?name=Alice for user Alice
etc ...
Note that I could change the LOGIN_URL in settings.py to be e.g. accounts/login/?name=Bob but that would remain fixed and I would not get accounts/login/?name=Carl or accounts/login/?name=Alice.
Once the user has successfully login, I would need to retrieve the name from the request e.g. If user Bob has successfully login, get the name=Bob, etc.
Usually, I would do request.GET.get('name','')
but I would need to change allauth views
Is there a way to achieve the above without changing the source code of allauth.

Django Login/Session Not Sticking Over HTTPS

I'm working on a Django site hosted on an Apache server with mod_wsgi.
The site is only on https as we have Apache redirect any http requests to https.
The project I'm working on is called Skittle.
I have a custom user model called SkittleUser which inherits from AbstractBaseUser and is set as the AUTH_USER_MODEL in our settings.py file.
os.environ['HTTPS'] = "on" is set in the wsgi.py file.
SESSION_COOKIE_SECURE = True and CSRF_COOKIE_SECURE = True are both set in settings.py
The issue that we are having right now is that logging in as a user is unreliable.
When you go to the login page, some times it works while other times it doesn't.
Then while browsing the site, you will suddenly lose your session and be kicked down to an anonymous user.
We are currently running our test site here if anybody wants to take a look:
https://skittle.newlinetechnicalinnovations.com/discover/
Our production site is at www.dnaskittle.com but does not yet incorporate user logins as the feature doesn't work.
A test user:
email: test#dnaskittle.com
password: asdf
If the login does not work, you will see in the top right "Welcome, Login" in which case, just try clicking on Login again and use the same credentials.
It may take 5-6 times of doing that process before you will actually get logged in.
You will know it works when you see "Welcome Tester, Logout, My Genomes"
After you are logged in, it may stick for a while, but browsing around to other pages will eventually kick you back off.
There is no consistent amount of pages that you can go through before this happens, and it doesn't happen on any specific page.
Any insights on this would be greatly appreciated.
Also of note, going to the Django admin page (which is not our code, but base django code) has the same issue.
I've gotten this issue sorted out now.
Users can not login while on HTTPS using while using the listed setup.
What I did:
In settings.py add:
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_NAME = 'DNASkittle'
I also wiped the current django_sessions database in case that was causing issues with old lingering data.
I did not setup extra middleware or SSLRedirect, and everything is working all ship shape.
It's little longer and complex the SSL system. to handle the session/login properly with https you can set a configuration with the session_cookies.
settings.py:
ENABLE_SSL=False #in the debug mode in the production passed it to True
MIDDLEWARE_CLASSES = (
'commerce.SSLMiddleware.SSLRedirect', #)
# the session here is to use in your views when a user is connected
SESSION_COKIE_NAME='sessionid'
#the module to store sessions data
SESSION_ENGINE='django.contrib.sessions.backends.db'
#age of cookie in seconds (default: 2 weeks)
SESSION_COOKIE_AGE=7776000 # the number of seconds in 90 days
#whether a user's session cookie expires when the web browser is closed
SESSION_EXPIRE_AT_BROWSER_CLOSE=False
#whether the session cookie should be secure (https:// only)
SESSION_COOKIE_SECURE=False
SSLMiddleware is a file you going to define in your project like.
SSLMiddleware.py:
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
SSL='SSL'
class SSLRedirect:
def process_view(self,request,view_func,view_args,view_kwargs):
if SSL in view_kwargs:
secure =view_kwargs[SSL]
del view_kwargs[SSL]
else:
secure=False
if not secure == self._is_secure(request):
return self._redirect(request,secure)
def _is_secure(self,request):
if request.is_secure():
return True
if 'HTTP_X_FORWARD_SSL' in request.META:
return request.META['HTTP_X_FORWARD_SSL'] == 'on'
return False
def _redirect(self,request,secure):
protocol = secure and "https" or "http"
newurl ="%s://%s%s" % (protocol, request, request.get_full_path())
if settings.DEBUG and request.method=="POST":
raise RuntimeError, \
return HttpResponsePermanentRedirect(newurl)
Now in your urls which should handle your logins or connection add the line
urls.py:
from project import settings
urlpatterns += patterns('django.contrib.auth.views',
(r'^login/$','login',{'template_name':'registration/login.html','SSL':settings.ENABLE_SSL},'login'),
Try to adapt this to your code. and don't forget to turn ENABLE_SSL to True
For users login with HTTPS, you have to enable SSL and use code that matches your case to use it. For the user session you can use this:
First check if you have in settings.py:
INSTALLED_APPS= ('django.contrib.sessions',)
and use the request.sessions in your file.py:
request.session['id']='the_id_to_store_in_browser' or 'other_thing'
Here you use request.session like a special SessionStore class which is similar to python dictionary.
In your views.py for example before rendering a template or redirecting test the cookie with the code:
if :
# whatever you want
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return HttpResponseRedirect(up-to-you)
else:
# whatever you want
request.session.set_test_cookie()
return what-you-want
with this code, the user session will stick a wide, depending on your SESSION_COOKIE_AGE period.