Django request.session.save() authentication - python

Bit of a strange one and I have my reasons for doing this, I know Django does this out-of-the-box so put that to the side when I ask..... is it possible to create a authenticated session in Django for a user that does not exist in the standard user model. i.e I want a one off login (session) created for access that allows me to use request.tempUser.is_authenticated() Almost like anonymous access, but authenticated! I'm not talking about custom user models here, but I want do want use the standard auth stuff in Django, if thats possible?
This is what I have so far where I have tried request.session.save() but that won't ... log-in the user.
if member.check_password(password):
# Start new session for member???????
request.session.save()
return self.create_response(request, {
'success': True
})

I've done this before, we have a session middleware (we wrote) that looks to see if the current user logged in is a valid user or not.
On the login we do the following
def login(request, username, password):
# not the actual code, but you get the gist
logged_in_user = authenticate(username, password)
request['cur_user'] = logged_in_user.username
If that variable is not set or is not set to a proper username we bounce the user and clear out the session.
This will log in the user, essentially you just have to track that variable in your code to ensure that the session has a valid user attached to it.

Related

How to create a new user in Django using LDAP?

I'm using Django to create a REST API with LDAP. One of the endpoints gets a username (this is not the same username of the logged in user through IsAuthenticated). I want to check if that username exists in the system, even if he never logged-in. My current code was:
try:
user = User.objects.get(username=request.data['username'])
except:
return Response(data={"error": "User does not exist"}, status=status.HTTP_400_BAD_REQUEST)
This of course does not work because the database contains users that have logged in at least once. How can I create the user if he does not exist? I know I can use User.objects.create but I want it to fetch the data from LDAP and not just to pass it the username.
The logic that I'm after:
Check if the username does not belong to any user via LDAP. If so, return error message.
Otherwise, create/populate the user and do other actions (based on the purpose of the endpoint).
I'm using django_auth_ldap.

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 logins without persistence

My company has a Flask application that uses flask-login to handle user logins/logouts and sessions. We use the #login_required decorator to protect views. Our clients log via persistent users stored in a database. However, we want employees of our company to be able to log in to our clients' sites without popping up in their users lists. We verify our own authenticity by CAS login at our own CAS server and checking that the username belongs to our company.
We want the employees to simply be able to login without needing to be persisted in the database but flask-login requires a persisted user model.
Sorry for the troublesome use of words here, but I hope this is understadable.
Every authorization system should check user in some storage by some field and in usual cases return exist or has permisions.
So with flask-login you can implement it with next: user_loader/header_loader/request_loader and UserMixin with user_id.
Every request with login_required call *_loader to get UserMixin. So it can look like next:
#login_manager.request_loader
def loader(request):
identifier = get_identifier_from_request(request)
exist = check_on_cas_server(identifier)
if not exist:
return None
user = UserMixin()
user.id = get_specified_or_random_id(identifier, exist)
return user
Details you can found with https://flask-login.readthedocs.org/en/latest/.

Re-Authenticate / Confirm credentials of User

I understand how to log a user in/out as well as authenticate within django, but one thing that is mission critical to a new project of mine.
I would like to have the user logged in (which I have), and I would like to then ask the user for their credentials again on certain pages.
I have one method through a EmployeeAuthenticatedMixin that I have made, which checks the POST data for the credentials. The main problem is the Mixin does not redirect, it merely serves up a page. So a user can hit the refresh button and resubmit the form, giving them access again.
Is there any way to ask for the user credentials and allow them access to the next page? Maybe an internal Django thing? Sessions? Messages?
You can log them out forcing them to log back in, using request(logout)
pseudo-coded
def confirm_crednetials(request)
logout(request)
render 'form'
or First prompt the user with a form if they do not have a cookie, you can check and set the cookie with this built in django method resp.set_cookie(foo, cookie) but after you authenticate the user.
if 'id' in request.COOKIES:
**render page
else:
authenticate_user(username=foo, password=bar)
resp.set_cookie(foo, cookie)
I wrote a signal that would fire after login:
from django.contrib.auth.signals import user_logged_in
import datetime
def reauthentication(sender, user, request, **kwargs):
request.session['last_login_time'] = str(datetime.datetime.now())
request.session.save()
user_logged_in.connect(reauthentication)
Then I wrote middleware to catch views that require reauthentication if the sessions last_login_time is older than 3 minutes.

GAE User registry without Google Accounts, want to restric to specific domain

I am planning on creating an application for the students of my school, and I want to restrict user registration to emails of the form person#myschool.edu. I would prefer to not manually create the user table and do the password hashing and such. Are there any libraries you can recommend for this?
Thanks for the help.
Sometimes, if you just send the user to a login screen you will end in a redirect loop if the user is already logged with a Google Account.
What i have found to be a good answer to this problem is to redirect the user to a log out page so he can later login with the domain you want.
I have used this for my code
user = users.get_current_user()
#Check if the user is in #mydomain.com
if user:
emailDomain = user.email().split("#")
if emailDomain[1] == "mydomain.com":
return True
else:
self.redirect(users.create_logout_url('/startPage'))
else:
self.redirect(users.create_login_url(self.request.uri))
This way, the application logs you out automatically and asks for your domain credentials
Since you said you don't know how the email are registered, that you don't want to manage a login/password database and you just need a regexp or somethings (I quote here!), I assume you could keep it very simple.
Something like.
user = users.get_current_user()
if user:
emailDomain = user.email().split("#")
if emailDomain == "yourschool.edu":
doSomething()
That way, all the trouble of registering to your app is given to the users (who will need to get a Google Account).

Categories