Facebook authentication using angular JS and Django - django

I'm a beginner in both angular JS and django. I was following this particular tutorial in making a facebook authentication app.
http://cbdev.blogspot.in/2014/02/facebook-login-with-angularjs-django.html
I've followed the tutorial exactly. And when I start the server I get the error.
NameError at /
name 'strategy' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.3.1
Exception Type: NameError
Exception Value:
name 'strategy' is not defined
Exception Location: /root/Documents/django/clueless/clueless_engine/../clueless_engine/views.py in <module>, line 1
Python Executable: /root/Documents/django/clueless/bin/python
Python Version: 2.7.13
Python Path:
['/root/Documents/django/clueless/clueless_engine',
'/root/Documents/django/clueless/lib/python2.7',
'/root/Documents/django/clueless/lib/python2.7/plat-x86_64-linux-gnu',
'/root/Documents/django/clueless/lib/python2.7/lib-tk',
'/root/Documents/django/clueless/lib/python2.7/lib-old',
'/root/Documents/django/clueless/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/root/Documents/django/clueless/local/lib/python2.7/site-packages',
'/root/Documents/django/clueless/lib/python2.7/site-packages']
Server time: Thu, 1 Jun 2017 07:30:14 +0530
my views.py file is
#strategy()
def auth_by_token(request, backend):
backend = request.strategy.backend
user=request.user
user = backend.do_auth(
access_token=request.DATA.get('access_token'),
user=user.is_authenticated() and user or None
)
if user and user.is_active:
return user# Return anything that makes sense here
else:
return None
#csrf_exempt
#api_view(['POST'])
#permission_classes((permissions.AllowAny,))
def social_register(request):
auth_token = request.DATA.get('access_token', None)
backend = request.DATA.get('backend', None)
if auth_token and backend:
try:
user = auth_by_token(request, backend)
except Exception, err:
return Response(str(err), status=400)
if user:
strategy = load_strategy(request=request, backend=backend)
_do_login(strategy, user)
return Response( "User logged in", status=status.HTTP_200_OK )
else:
return Response("Bad Credentials", status=403)
else:
return Response("Bad request", status=400)

I have created Social Auth authentication using python scocial auth. you can check:
https://github.com/ranvijay-sachan/django-rest-login-and-social_auth/tree/master/profiles
POST: http://localhost:8000/api/v1/login/2/
Content-Type : application/json
{ "accessToken": "alert token" }

The problem was that I forgot to import modules.
from social.apps.django_app.utils import load_strategy strategy = load_strategy(request)

Related

What did mean by AttributeError at /login_user/?

My target is to get all the products a user added to the cart, that's why I decided to fetch the ShopingCart model from the context processor. And I added it to the context processor, and it worked well. But the problem is when I try to log out, then I get an error. Where did the actual problem occur? 😢...
models.py:
class ShopingCart(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserShoppingCartRelatedName',on_delete=models.CASCADE)
Product = models.ForeignKey(Products, related_name='ShoppingCartRelatedName',on_delete=models.CASCADE)
context_processors:
def ShoppingCart(request):
return {"ShoppingCart":request.user.UserShoppingCartRelatedName.all()}
error:
AttributeError at /login_user/
'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName'
Request Method: GET
Request URL: http://127.0.0.1:8000/login_user/
Django Version: 4.0.4
Exception Type: AttributeError
Exception Value:
'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName'
Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\utils\functional.py, line 259, in inner
Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe
Python Version: 3.9.5
Python Path:
['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce '
'site\\env\\lib\\site-packages']
Server time: Tue, 09 Aug 2022 11:48:23 +0000
Check if user is not none and authenticated.
def ShoppingCart(request):
if request.user is not None and request.user.is_authenticated():
return {"ShoppingCart":request.user.UserShoppingCartRelatedName.all()}
else:
return {}
It looks as if you are not logged in!
You must login before you can access the user atrubute.
If you are not loged in it says you are 'AnonymousUser'
'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName'
Login and then try it!!

Django Azure AD Integration

I'm currently integrating SSO using Azure AD for a Django Project. I'm currently using the package: https://github.com/leibowitz/django-azure-ad-auth . I have followed the docs to setup the Azure AD Authentication . On entering the application url, it takes me to the microsoft login page and after entering the credentials it's redirected to the application. But on redirection to the application after the Azure Auth, the code checks in the session for 'nonce' & 'state' variables , which are strangely returned as None and hence the application redirects to the failure url.
#never_cache
def auth(request):
backend = AzureActiveDirectoryBackend()
redirect_uri = request.build_absolute_uri(reverse(complete))
nonce = str(uuid.uuid4())
request.session['nonce'] = nonce
state = str(uuid.uuid4())
request.session['state'] = state
login_url = backend.login_url(
redirect_uri=redirect_uri,
nonce=nonce,
state=state
)
return HttpResponseRedirect(login_url)
#never_cache
#csrf_exempt
def complete(request):
backend = AzureActiveDirectoryBackend()
method = 'GET' if backend.RESPONSE_MODE == 'fragment' else 'POST'
original_state = request.session.get('state')
state = getattr(request, method).get('state')
if original_state == state:
token = getattr(request, method).get('id_token')
nonce = request.session.get('nonce')
user = backend.authenticate(token=token, nonce=nonce)
if user is not None:
login(request, user)
return HttpResponseRedirect(get_login_success_url(request))
return HttpResponseRedirect('failure')
This is the code used for authentication.
Settings.py sample is given below:
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'azure_ad_auth.backends.AzureActiveDirectoryBackend',
)
LOGIN_REDIRECT_URL = '/login_successful/'
AAD_TENANT_ID = 'd472b4f4-95c5-4eb3-8a9a-3615c837eada'
AAD_CLIENT_ID = '75e38b53-8174-4dc6-a8f6-bb7a913f1565'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = True
Traceback
TypeError at /TypeError at /project/azure/complete/
must be str, not NoneType
Request Method: POST
Request URL: http://testdomain.com/project/azure/complete/
Django Version: 2.2.4
Exception Type: TypeError
Exception Value:
must be str, not NoneType
Exception Location: /home/project/azure_auth/views.py in complete, line 57
Python Executable: /home/project/app/venv/bin/python3
Python Version: 3.6.8
Python Path:
['/home/project/app/project',
'/home/project/app/venv/bin',
'/home/project/app/venv/lib64/python36.zip',
'/home/project/app/venv/lib64/python3.6',
'/home/project/app/venv/lib64/python3.6/lib-dynload',
'/usr/lib64/python3.6',
'/usr/lib/python3.6',
'/home/project/app/venv/lib/python3.6/site-packages']
Server time: Tue, 19 Nov 2019 05:21:10 +0000/azure/complete/
must be str, not NoneType
Request Method: POST
Request URL: http://testdomain.com/project/azure/complete/
Django Version: 2.2.4
Exception Type: TypeError
Exception Value:
must be str, not NoneType
Exception Location: /home/project/app/project/azure_auth/views.py in complete, line 57
Python Executable: /home/project/app/venv/bin/python3
Python Version: 3.6.8
Python Path:
['/home/project/app/project',
'/home/project/app/venv/bin',
'/home/project/app/venv/lib64/python36.zip',
'/home/project/app/venv/lib64/python3.6',
'/home/project/app/venv/lib64/python3.6/lib-dynload',
'/usr/lib64/python3.6',
'/usr/lib/python3.6',
'/home/project/app/venv/lib/python3.6/site-packages']
Server time: Tue, 19 Nov 2019 05:21:10 +0000
/home/project/app/project/azure_auth/views.py in complete
f.write("nonce -->"+nonce+"\n") …
â–¼ Local vars
Variable Value
backend
<azure_auth.backends.AzureActiveDirectoryBackend object at 0x7f5c688dce80>
data
['82aff4f9-2cc0-4521-aea7-ad3281d20774\n',
'ba821364-86c9-4233-881f-bdc772f7c488\n']
f
<_io.TextIOWrapper name='t1.txt' mode='w' encoding='UTF-8'>
method
'POST'
n
'82aff4f9-2cc0-4521-aea7-ad3281d20774'
nonce
None
original_state
None
request
<WSGIRequest: POST '/project/azure/complete/'>
state
'fd93da6a-9009-4363-9640-9364df7f64df'
token
'eyJ0eXAiOiJKV1Qi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2ZXIiOiIxLjAifQ.Rvc6xcPRZ01iebYtEyAWeyDnQEUVtqV1L1mapr658jLog-_yIASyEm3kMrkt6dIWWEO3dJSe3k05xOJlbnHqcjaR5LKAwOZzGR_oBmyIyB8-IvuEankNVpwYtcz8mY7kFr6AqQmIsx7xLLgv4grp-bSy4eRqjk36VeLX_LwMBuM_U6V70w0gXN1vvFCj0tjsv-VtTAmNgvdxS0ltzdD3rzZ87DoXbPWmoozLtO9WBRsJvMuvn-frBtYUYkIhs3I-eVAO9ZG2IWEuLQx6k7RBmzX6HgFi9SVpyEhNru7fmwO-qj5uRj9FQa45lCZluUV25o_AV1NQ94d5lnFyeMh7uw'
user
None
I got the above error while trying to write the session variables to file (for debugging.)
I know this question is a bit old, but the session won't be able to be retrieved (and with it the original state and nonce), and will fail the comparison if the cookie is not being sent by the browser.
The cookie is not sent by default in django 2.1+, since the default settings add SameSite=Lax
The cookies used for django.contrib.sessions, django.contrib.messages,
and Django’s CSRF protection now set the SameSite flag to Lax by
default. Browsers that respect this flag won’t send these cookies on
cross-origin requests. If you rely on the old behavior, set the
SESSION_COOKIE_SAMESITE and/or CSRF_COOKIE_SAMESITE setting to None.
https://docs.djangoproject.com/en/3.0/releases/2.1/#samesite-cookies
In theory this should still send the cookie (from what I understand), but for some reason chrome doesn't seem to. There's something I clearly do not understand, so if anyone knows better please comment.
Anyway, changing the setting via SESSION_COOKIE_SAMESITE = None should work.

How do I fix this error in Python Django involving request.user.is_authenticated() and bool object not callable?

I am trying to make profile pages for each user. I added a code that checks if the user is logged in and does a redirect (see line 12 of the code below).
from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from .models import Account, ForSale, WTB
from mysite.forms import MyRegistrationForm
def signup(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/user/')
else:
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/user/')
context = {}
context.update(csrf(request))
context['form'] = MyRegistrationForm()
return render(request, 'signup.html', context)
def index(request):
return render(request, 'index.html')
However, upon accessing /signup/ on the site I get the following debug message:
TypeError at /signup/
'bool' object is not callable
Request Method: GET
Request URL: http://url:8000/signup/
Django Version: 2.0
Exception Type: TypeError
Exception Value:
'bool' object is not callable
Exception Location: /www/mysite.com/mysite/views.py in signup, line 13
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/www/mysite.com',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/lib/python3.5/site-packages',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sun, 3 Dec 2017 18:07:54 -0800
In older versions of Django request.user.is_authenticated was a method. It's now an attribute and no longer requires parenthesis. If you change your code to:
if request.user.is_authenticated:
It should be work as expected.
For more info see the docs here: https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated
you forget to import csrf module please try to add this line and make sure to avoid hardcoded urls try to use url names
from django.core.context_processors import csrf

Django login doesn't work

I tried to create a login view like the following:
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('rango/index.html')
else:
return HttpResponse('Your Rango account is disabled!')
else:
print("Invalid login details: {0}, {1}".format(username, password))
return HttpResponse("Invalid login details supplied!")
else:
return render(request, 'rango/login.html', {})
This seems to be the correct way to do so, but when I try to open the page in my browser, I get the following error:
TypeError at /rango/login/
login() missing 1 required positional argument: 'user'
Request Method: GET
Request URL: http://localhost:8000/rango/login/
Django Version: 1.9.10
Exception Type: TypeError
Exception Value:
login() missing 1 required positional argument: 'user'
Exception Location: C:\Users\Johannes\tangowithdjango\lib\site-packages\django\core\handlers\base.py in get_response, line 147
Python Executable: C:\Users\Johannes\tangowithdjango\Scripts\python.exe
Python Version: 3.6.0
Python Path:
['C:\\Users\\Johannes\\tangowithdjango\\tango_with_django_project',
'C:\\Users\\Johannes\\tangowithdjango\\Scripts\\python36.zip',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\lib',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36',
'C:\\Users\\Johannes\\tangowithdjango',
'C:\\Users\\Johannes\\tangowithdjango\\lib\\site-packages']
Server time: Thu, 12 Jan 2017 17:56:38 +0100
Has anyone encountered something similar or knows a solution to the problem? I already searched and tried around for a bit but couldn't find an answer.
Your code looks good, make sure that you are importing this
from django.contrib.auth import authenticate, login
Also check your views
This is the first url:
url(r'^login', example_views.login, name='log'),
And you have to change to this:
url(r'^log', example_views.log, name='log'),
I followed that tutorial and came across the same error.
I solved it by correcting one line in urls.py
urlpatterns = patterns(
...
url(r'^login/$', views.login, name='login'),
)
into this:
urlpatterns = patterns(
...
url(r'^login/$', views.user_login, name='login'),
)
It should be the name of the login view you created, which is 'user_login' in your case.

Django - Social_Auth - Facebook Logout - NotAllowedToDisconnect

I have used django package social_auth to implement facebook login on my website. I am able to log in correctly and get all the data. But I am not able to logout.
I am not using django.user.login and logout. I am using socialauth_begin and socialauth_disconnect
I am able to login, go in the social auth pipeline, get the necessary information, but I am not able to logout. What is the fix to this problem?
When I click on "Logout" in Logout
I get the following error
NotAllowedToDisconnect at /tomonotomo/auth/disconnect/facebook/
No exception supplied
Request Method: GET
Request URL: http://localhost:8000/tomonotomo/auth/disconnect/facebook/
Django Version: 1.5.1
Exception Type: NotAllowedToDisconnect
Exception Location: /tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/local/lib/python2.7/site-packages/social_auth/backends/__init__.py in disconnect, line 435
Python Executable: /tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/bin/python2.7
Python Version: 2.7.3
Python Path:
['/tmp/guest-onyOH9/pratik/tomonotomo_project',
'/tmp/guest-onyOH9/Desktop/pycharm-2.7.3/helpers/pydev',
'/tmp/guest-onyOH9/pratik/tomonotomo_project',
'/tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/lib/python2.7',
'/tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/lib/python2.7/plat-linux2',
'/tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/lib/python2.7/lib-tk',
'/tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/lib/python2.7/lib-old',
'/tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/local/lib/python2.7/site-packages',
'/tmp/guest-onyOH9/pratik/virtualenv-1.10/tomonotomo/lib/python2.7/site-packages']
Server time: Sat, 10 Aug 2013 22:27:42 -0500
The settings I have is this:
AUTHENTICATION_BACKENDS = (
'social_auth.backends.facebook.FacebookBackend',
'django.contrib.auth.backends.ModelBackend',
)
FACEBOOK_EXTENDED_PERMISSIONS= ['email', 'user_birthday']
SOCIAL_AUTH_PIPELINE = (
'social_auth.backends.pipeline.social.social_auth_user',
'social_auth.backends.pipeline.associate.associate_by_email',
'social_auth.backends.pipeline.user.get_username',
'social_auth.backends.pipeline.user.create_user',
'tomonotomo.social_auth_pipeline.create_custom_user',
'social_auth.backends.pipeline.social.associate_user',
'social_auth.backends.pipeline.user.update_user_details',
)
SOCIAL_AUTH_CREATE_USERS = True
SOCIAL_AUTH_FORCE_RANDOM_USERNAME = False
SOCIAL_AUTH_DEFAULT_USERNAME = 'socialauth_user'
SOCIAL_AUTH_ENABLED_BACKENDS = ('facebook',)
SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
SOCIAL_AUTH_ASSOCIATE_URL_NAME = 'socialauth_associate_complete'
SOCIAL_AUTH_ASSOCIATE_BY_EMAIL = True
SOCIAL_AUTH_ERROR_KEY = 'socialauth_error'
SOCIAL_AUTH_REDIRECT_IS_HTTPS = False
LOGIN_URL = '/tomonotomo/login/'
LOGIN_REDIRECT_URL = '/tomonotomo/'
LOGIN_ERROR_URL = '/tomonotomo/login-error/'
Please Help. Thanks
The code I used to Login was:
<h3 style="color:white">Connect via Facebook</h3>
I just have the same problem but with twitter.
This error is generated because the user has not another way to connect/disconnect from the system, and the API in some way think it would be dangerous.
How I resolve the problem was calling a custom logout form like in the example:
https://github.com/omab/django-social-auth/blob/master/example/app/views.py#L39