Django request.user is empty - python

Using django, I am authenticating the user through Google. I get the initial request tokens & redirect the user to google for auth. After which google redirects the user back to my website (using the redirect_url I provide).
At this point the request.user.id is None so is request.user.username why is this happening? I need the user ID to enter the access_tokens (that google sends me) into the DB.
Under what conditions can request.user object in Django be empty?
UPDATE1: When I get redirected back from Google with the url pattern as http://mywebsite.com/lserv?s=goog control comes back to my django views function, but django gives me the request.user object user as Anonymous user with no username or id. why?
UPDATE2:
all this is running on python manage.py runserver for now...
UPDATE3: Anybody faced anythn similar to this? basically, out of no reason the user in request clears out automatically & I get assigned as Anonymous user. All this happens between url requests from the user (from browser). Why?

Django's auth mechanism has nothing to do with Google's or any other auth service. If you want to integrate third party auth service with your Django site, you should do it youself.
If you're using oauth2 library, it's README has a section named "Logging into Django w/ Twitter" may help you.

If you are using oauth api from google. To get the user you have to do something like this
from google.appengine.api import oauth
# ...
try:
# Get the db.User that represents the user on whose behalf the
# consumer is making this request.
user = oauth.get_current_user()
except oauth.OAuthRequestError, e:
# The request was not a valid OAuth request.
# ...

Related

Azure Python Flask Get Email id of the user logged in

I created the sample Python Flask Webapp by following the below link.
https://learn.microsoft.com/en-us/azure/app-service/containers/quickstart-python?tabs=bash
I also added the AD Authentication for the Flask application by enabling Authentication in the Settings of the App Services. Now the app works only when the user is logged in and cannot access otherwise.
I would want to fetch the email id if the user who is logged in. I tried checking online but unable to find a way to get the email address of the user.
Any help is really appreciated.
App Service passes user claims to your application by using special headers. So you can get user information from the request header. Some example headers include:
X-MS-CLIENT-PRINCIPAL-NAME
X-MS-CLIENT-PRINCIPAL-ID
You can use res.headers to see all the values.
Reference:
Access user claims

django rest auth facebook code for login

On project I use django-rest-auth for user registration and authentication. Also i added code for facebook login:
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from rest_auth.registration.views import SocialLoginView
class FacebookOAuth2AdapterFixed(FacebookOAuth2Adapter):
def __init__(self):
pass
class FacebookLogin(SocialLoginView):
adapter_class = FacebookOAuth2Adapter
And in my project urls.py I add
url(r'^rest-auth/facebook/$', FacebookLogin.as_view(), name='fb_login'),
But on url localhost:8000/rest-auth/facebook I see form with 2 parameters: Access token(already have) and code.
My question is next: Can I login via facebook without this code, and if not, how can I get this code without frontend? How can I check work user authentication/registration or not?
PS: SocialApp created, facebook app created, app id and app secret added to social app.
Only one of "Access Token" or "Code" field is required. (I have not tested the Code field but the Access Token field works, with the Code field left blank)
To use Access Token, after the user performs the "Login to Facebook" step on the client side using Facebook javascript SDK, you will receive a response from Facebook which includes "accessToken" for accessing data on Facebook. Simply paste this accessToken into the "Access Token" field and it will automatically login and/or create the user's account from data retrieved from Facebook.
Obviously you can then perform the same process by posting the access token to the form all in javascript.
In the field of Access Token, Pass the User Access Token that you will get from Facebook developer dashboard(generate and debug), code field you can leave as blank. It will create user in your application and will return JWT token with user details.

Why is Django User being AnonymousUser when I make a request from a JS client but it is properly set when using Django Rest Framework ?

I'm having an issue when trying to get the information of the user that is logged in in Django. My Login service looks like this:
username = request.data['username']
password = request.data['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
It's currently working properly at least when using Django Rest Framework
(It even appears at the top right the user that is logged in).
I'm trying to bring the profile of the user that is logged in so I developed a profile service which tries to get the user logged in which is working perfectly when using Django Rest Framework.
The issue comes when I try to call the same endpoint from a JS client. I think it might be an issue with setting something in the header after the Django login is executed. Currently, I am not doing anything in my JS client but to call to the login endpoint which is returning properly. Should I set a cookie or something in the header of each request so Django knows which user am I? If so, how should it be that ?
Thanks in advance
Should I set a cookie or something in the header of each request so Django knows which user am I? If so, how should it be that ?
You definitively need the session cookie to be passed.
By default, it'll be sessionid

django register user with django-facebook

Ok I see everyone saying use django-facebook, and it says it can do everything I want.
I have it installed on my app and the example page works, but how do I actually register a user with it?
Apart from the installation all the rest of the docs seem autogenerated and I have yet to find a step by step guide as to how to register a user on my site using django-facebook.
Here is a working example of facebook auth with django.
Facebook uses OAuth2 to federate user logins. An OAuth2 authorization step-by-step consists of
Create an authorization token by calling the request-token url with your consumer keys
Send the user to the authorize url with the token that you created and a callback url
Once authorized the user will be redirected to your callback url with an auth-token
Convert the auth-token to an access token at the request-token url
Save the access token and use it to make authorized requests

Using Flask-Social with Oauth Provider(s) Only, No Local Registration/Login Forms

Is it possible to use Flask-Social and Flask-Security if I only want to use Facebook Login, for example, for user registration and login, i.e. no local registration/login forms?
I looked through the Flask-Social example application and documentation but couldn't tell if this is possible. In the example application, users cannot login with Facebook unless they've previously registered. After registering with the example application, they can associate their Facebook account with their local account.
When I tried to call social.facebook.get_connection() I got an AttributeError 'AnonymousUser' object has no attribute 'id' because there's no current_user, which is defined by flask-security after registration/login.
This is doable without too much extra work using the #login_failed.connect_via decorator. With app as your instance of a Flask app, it would look like
#login_failed.connect_via(app):
def on_login_failed(sender, provider, oauth_response):
connection_values = get_connection_values_from_oauth_response(provider, oauth_response)
ds = current_app.security.datastore
user = ds.create_user( ... ) #fill in relevant stuff here
ds.commit()
connection_values['user_id'] = user.id
connect_handler(connection_values, provider)
login_user(user)
db.commit()
return render_template('success.html')
As for filling in the relevant stuff for creating the user, I just create a random string for the password, and haven't had issues leaving the email null. I also just included the exact same answer on the Flask-Social github page.

Categories

Resources