How to clear cookies using Django - python

I am trying to develop login page for a web site. I am using Django 1.4.2. I stored users which logged on correctly to a cookie using set_cookie. But I didn't find clear_cookie in Django's documentation. How to clear a cookie to make a user log out?

Setting cookies :
def login(request):
response = HttpResponseRedirect('/url/to_your_home_page')
response.set_cookie('cookie_name1', 'cookie_name1_value')
response.set_cookie('cookie_name2', 'cookie_name2_value')
return response
Deleting cookies :
def logout(request):
response = HttpResponseRedirect('/url/to_your_login')
response.delete_cookie('cookie_name1')
response.delete_cookie('cookie_name2')
return response

You can simply delete whatever you've stored in the cookie - this way, even though the cookie is there, it no longer contain any information required for session tracking and the user needs to authorize again.
(Also, this seems like a duplicate of Django logout(redirect to home page) .. Delete cookie?)

Related

Authenticate an API call correctly with requests and sessions

I want to call my own API in a custom view I wrote. Normally I use JWT authentication with my API calls. In this specific view though, I'd like to use a different authentication.
I want to enable logged in users to make a successful get call (without a token). Not logged in users should not be able to make that call. I tried this with Basic Authentication and Session Authentication but don't really get it tow work.
Here is my view that makes the API call:
def visualize_buildings(request, id):
passed_id = id
endpoint = 'linktomyendpoint' + str(passed_id)
response = requests.get(endpoint)
building_group_data = response.json()
# print(building_group_data)
if 'buildings' in building_group_data:
building_data = building_group_data['buildings']
context = {'building' : building_data}
return render(request, 'building_group_visualize_api.html', context)
else:
return HttpResponseNotFound("Ups. We are sorry but no Building Group was found with that id")
Here my API view:
class BuildingGroupRetrieveAPIView(RetrieveAPIView):
authentication_classes = [JSONWebTokenAuthentication,
SessionAuthentication, BasicAuthentication]
serializer_class = BuildingGroupSerializer
queryset = BuildingGroup.objects.all()
The view works with if I send a token in the headers. But how can I use Session Authentication with that? I tried getting username and password from the request and then pass it to the API call. But that doesn't work because I can't decode the password from the request (which makes sense).
So I tried to follow this: https://2.python-requests.org/en/master/user/advanced/ but I still can't authenticate my request.
Can anyone point me into the right direction? Help is very much appreciated! Thanks in advance!
Session ids are saved as a cookie on the user's device and they will be sent to the server as a header name Cookie. So if you want to use cookies instead of the JWT token then you should send your request with the session id as a cookie header.
This is the header that lets Django know your session-id when you visit the site directly:
Cookie: csrftoken=some-csrf-token; sessionid=your-session-id
Now to make your request contain something like that:
cookies = {'sessionid': 'your-session-id'}
response = requests.get(endpoint, cookies=cookies)
Note that Django might still through an error for csrf token based on your settings.
You can find your session-id on your browser. If you don't know where and how to access them, just google it. it's different based on the browser you use.

Redirect to back to referrer page

I am building an account settings page. I was thinking of having a few routes that only accept post request then edit the records and then go back the account settings page.
The problem is that there is two account settings pages. One for users and one for an admin account.
The admin account_settings can use the same logic form the user account settings routes but If i use and post to use the user/account-settings route it returns back the user/account-settings route insted of the admin/user-account settings.
I was wondering how can flask returns back to the page it was on.
People usually solve this problem with session cookies (which you should have access to given that the user will be logged into an admin panel).
This is of course safter than using HTTP_REFERER (header sent by the client), as you control the contents of the session cookie entirely.
You could also pass a ?continue=http://... thing in the URL.
request.referrer will return back to the previous page. http://flask.pocoo.org/docs/0.11/reqcontext/

Django: Properly Setting Cookies For Login

I am new to Django's sessions, and i tried to make a login cookie for my website. User's on my website register via social website ( steam in this case ), For that i have different functions: Index view, Login, LoginProcess.
Information:
Index view is a homepage (127.0.0.1), Login function redirects user to LoginProcess, in this process, i have set a cookie.
request.set_cookie(key='logged', value=True)
request is instance that all 3 functions have in my code, I have set the logged in key to True, which should be read by Index function.
Index Function:
def index(request):
if request.COOKIES.get('logged') == True:
return HttpResponse("1 - User is logged in")
else:
return HttpResponse("0 - User is not logged in)
Unfortunately, this brings up statement 0 (User is not logged in), even if i am logged in the website, the value of logged key is None.
Problem:
Index function cannot detect that logged cookie was registered in LoginProcess function.
Question:
I am going to save the username in cookie as well, so system can determine which users data should it use, i know it is very bad for the client-side cookies, What's the best way of doing it?
How could i fix this problem? Is there any better way to set up login cookie? Is there any other better way to set up login session?
So basically, how could i set cookie in the first function and get it's value from the second function?
Note: There is no problem with authentication, my main concerns are to properly set cookies.
Maybe I am still reading it wrong, but it is impossible to set the value on a request's cookie.
'WSGIRequest' object has no attribute 'set_cookie'
but if I assume you meant response.set_cookie(key='logged', value=True) (note response), then this works for me.
# sets the cookie if not set.
print request.COOKIES
if request.COOKIES.get('logged'):
return HttpResponse("1 - User is logged in")
else:
response = HttpResponse("0 - User is not logged in")
response.set_cookie('logged', True)
return response
I'm not entirily sure about your question, but if you want to set a cookie besides the session_id, WHEN the user is logged in you can also use middleware. Like also suggested here:
How to set a login cookie in django?

Flask: How to prevent to go to login page when already logged in?

I have been doing the Flask Web Development Book by Miguel Grinberg, and just finished up with the authorization blueprint. Though, I am having an issue that if I am already logged in, I can still put the url of the login page and go there. How can I prevent this in Flask?
While using Django, I came up with django-braces library which helps to do this, any such alternative available in Flask?
Redirect users who are logged in navigating to the login page.
To check if they are already logged in, examine the current_user proxy. Note that logged-in users will have current_user.is_authenticated() equal True, while users who aren't logged in will have the method return False.
You have two options for the destination: back to their previous page with redirect(request.referrer) or to one of your other pages with redirect(url_for('view_name')).
Use current_user.is_authenticated().

How do I redirect an user back to the page they were trying to access once they log in? (Django)

So currently I'm using #login_required to block certain pages from users and redirect them, telling them they need to log in. but what I can't understand is how do I "let them" go to the page they were trying to go to once they log in. Currently I'm just using a typical render_to_response('with a certain view') but what if i want that response to be anywhere where they were trying to access. How do i code that?
The #login_required will generally pass you back the redirect_field_name (default is "next") for example: /accounts/login/?next=/polls/3/. So in your login view after authenticating and logging in the user you can do something like
response = HttpResponseRedirect(next)
# Do whatever else you need to do here with the response object
return response
See the docs at https://docs.djangoproject.com/en/1.3/topics/auth/#the-login-required-decorator
You can pass a url parameter back to your login page and use that to direct the user once they complete the login successfully.
from the login requiered decorator docs it says:
By default, the path that the user should be redirected to upon
successful authentication is stored in a query string parameter called
"next".
and usually when the login is done it take to the "next" url
Here's what django.contrib.auth.views.login does:
If called via GET, it displays a login form that POSTs to the same
URL. More on this in a bit.
If called via POST, it tries to log the
user in. If login is successful, the view redirects to the URL
specified in next. If next isn't provided, it redirects to
settings.LOGIN_REDIRECT_URL (which defaults to /accounts/profile/). If
login isn't successful, it redisplays the login form.

Categories