How do I tell Django a user is authenticated? - django

In this Django code I inherited there is a check for request.user.is_authenticated().
How do I set this authenticated attribute for a user, in particular when I am doing a registration through AJAX JSON?

To log a user in, you should django.contrib.auth.login - see the docs here: https://docs.djangoproject.com/en/1.5/topics/auth/default/#auth-web-requests
Note, though, that you should authenticate the user (i.e. check their credentials) before you do so, with django.contrib.auth.authenticate - same docs as above.
This is regardless of whether you're using AJAX or not - this code has to be in a view somewhere that gets called in order for the user to get logged in. Whether that view is called via AJAX or not is irrelevant.

The only user this will return false for is AnonymousUser; all other users have it return true via their superclass. Therefore all you need to do is authenticate the user normally.

Related

Disallow user login if email_verified is false

When a user registers for my application I handle the request through an API and send an email containing a verification link. When the link is clicked it updates the email_verified attribute to true. This is working as expected.
The problem I'm having is that a user is allowed to login even when the attribute email_verified is set to false.
I'm using amplify to login the user. How can I block user login if the email has not been verified?
I found out the answer to this myself. I was registering the user with a custom lambda function which creates the user using adminCreateUser. This API automatically sets the UserStatus to CONFIRMED which is the field that is used to determine whether a user can log in or not. I was working on the assumption that it was the email_verified field which determined this, which was incorrect.
I fixed this by instead using the signUp function of the API which instead creates the user in an UNCONFIRMED state and doesn't allow login until the sign up is confirmed.

Python-social-auth: do not reassociate existing users

I'm using python-social-auth to allow users to login via SAML; everything's working correctly, except for the fact that if a logged-in user opens the SAML login page and logs in again as a different user, they'll get an association with both of the SAML users, rather than switch login.
I understand the purpose behind this (since it's what you can normally do to associate the user with different auth services) but in this case I need to enforce a single association (ie. if you're logged in with a given SAML IdP, you cannot add another association for the same user with the same provider).
Is there any python-social-auth solution for this, or should I cobble together something (for instance, preventing logged-in users from accessing the login page)?
There's no standard way to do it in python-social-auth, there are a few alternatives:
Override the login page and if there's a user authenticated, then log them out first, or show an error, whatever fits your projects.
Add a pipeline function and set it in the top that will act if user is not None, you can raise an error, logout the user, etc.
Override the backend and extend the auth_allowed method in it return False if there's a valid user instance at self.strategy.request.user. This will halt the auth flow and AuthForbidden will be raised.

Where does Django logout user on expired/invalid session

I do some stuff on user logout, so I want to extend the method where Django does the logout on expired/invalid session but I don't find where it does it. Can you help me to point where the logout happens?
It doesn't. When a session expires, it just expires, that's all.
I think your question is based on a misunderstanding about what it means to be logged in at all. Django doesn't know who's logged in at any particular time; the web is stateless, and the only time Django knows about a user is when they make a request. At that point, Django can distinguish between a user that has a valid session cookie and one that doesn't. But if the session subsequently expires, the first Django will know about it is when that user next makes a request.
you can get the user in anyplace of view by request.user. if you get a valid user info by request.user then the user is logged in . and this is NULL then the user is not logged in.

django-auth: login with user uuid and limit permissions

I'm trying to create a kind of quick response form where a user does not need to login but is identified with his uuid (in the url). Moreover i need to restrict his permissions for this session so that he only could to a few things.
User gets url with UUID and ID of event (Where he can response)
User clicks on link and response page opens
User is identified via uuid
With the id of the event the event response form is generated
User can chose options and submit the form
Normally there are multiple other options (e.g. in the menue) available but these should only be accessible if user identifies with his username and password.
Of course i could write a special view but is there a more elegant way where i could reuse my existing view for the response?
First you'll want to use the UUID to trigger the login.
How you approach this will depend on whether you mind using a specific login url/view or you want people to arrive directly at the intended url/view (just with the UUID parameter). If you use a specific view you'll check the UUID, (presumably mark it as used/expired), then login the user. Alternatively for the UUID to checked and have users login via any url/view, you'll want a to use a custom middleware that's placed ahead of AuthenticationMiddleware in your middleware settings. In each case, once you have the logged in the user, you'll want to store in session some sort of flag to indicate they've auth'd via a temporary login UUID.
Now that you've authenticated and logged in the user via the UUID, it's time to serve them the view. At this point in your View you'll check for presence of the flag in the user session to determine their permissions.
You could go further and create another middleware class to encapsulate the session lookups and add a property, say "is_auth_temporary", to the request.User object that is a sibling to the is_anonymous and is_authenticated property.

Are there authentication examples with Django and Tastypie?

Are there basic authentication examples with Django and Tastypie?. I'm a little bit confused about how the authentication in Django works, specially with Tastypie.I wanna know how the authentication works with api keys and how to authenticate a user with the built-in User model which Django has. Any suggestion or code are really appreciated.
Thanks.
Just to answer your questions regarding authentication:
How the authentication in Django works?
Django authentication required SessionMiddleware to work. Once a session has been loaded, the Django authentication backend reads a special cookie _auth_user (IIRC) which contains currently logged in user's ID. If you have access to the django shell, you can manipulate it and make yourself logged in as any user! Once the backend notices there is a _auth_user key, it then adds a lazy User object to the request (so it delays the User.objects.get(...) until it is really needed). If there is no such key in the session dict, the user is claimed to be anonymous and an instance of AnonymousUser is added to the request object instead.
How does the authentication work in Tastypie?
Before your resource view is executed, a Resource.is_authenticated(request) method is called, which in turn calls the is_authenticated(request) method of the authentication backend of your the Resource of your choice. If the method returns False, the authentication is claimed to be failed and returns with Unauthorized error. If the method returns a HttpResponse, the response is returned instead. If the method returns True, the request is claimed to have been authenticated.
How does User model authentication work in Tastypie?
The User model authentication can be performed using SessionAuthentication backend provided by the Tastypie itself. What it does is creating a session for the current request so that the authentication middleware can then automatically insert relevant user model to the request. Notice that for this method to work, your API client has to support storing cookies and resending them in future requests.
You might find this useful. It allows you to authenticate the user based on the Django session cookie.
https://github.com/amezcua/TastyPie-DjangoCookie-Auth/blob/master/DjangoCookieAuth.py
I am using this in my application and it works!