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.
Related
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/.
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.
Hello i am new to django,
i am creating an authentication system using django.
Once a user is logged in i am storing the value in a session.
user = authenticate(username=username, password=password)
request.session['mid'] = user.id
and when i refresh i can receive the session id
uid = request.session['mid']
But i am not sure how to get the userdatas from the user id. can any one tell me how can get the user object using the user id.
Use simple .get() query.
try:
uid = request.session['mid']
userobj = User.objects.get(id=uid)
except User.DoesNotExist:
#handle case when user with that id does not exist
...
Of course, you can store the user id in request.session, and query the id
with django ORM manually.
But after installing the SessionMiddleware and AuthenticationMiddleware middlewares, on a higher level, Django can hook this authentication framework into its system of request objects. I believe most django projects will use the code below to get authenticated user from web requests.
if request.user.is_authenticated():
user = request.user
I've successfully managed to use django-socialauth to associate an account (in this case, an instagram account) with an existing user account. I've also set up my pipeline to collect additional user details:
def update_social_auth(backend, details, response, social_user, uid, user,
*args, **kwargs):
if getattr(backend, 'name', None) in ('instagram', 'tumblr'):
social_user.extra_data['username'] = details.get('username')
social_user.save()
This works great when an account is associated for the first time. However, if the account has already been associated, the username field will not be present in extra_data.
How can I update a user's extra_data after the association has already been made? Is there a way using django-socialauth to do this without disconnecting and reconnecting, or using the account's (e.g Instagram's) API?
If it helps, this is my pipeline at the moment:
SOCIAL_AUTH_PIPELINE = (
'social_auth.backends.pipeline.social.social_auth_user',
'social_auth.backends.pipeline.social.associate_user',
'social_auth.backends.pipeline.social.load_extra_data',
'social_auth.backends.pipeline.user.update_user_details',
'apps.utils.social.utils.update_social_auth'
)
Here is a snippet of code I use to add 'admin' and 'staff' options to an existing Django user; I don't know about django-socialauth or the extra_data field, but I'm guessing something like this might be applicable:
:
userqueryset = User.objects.filter(username=user_name)
if not userqueryset:
print("User %s does not exist"%user_name, file=sys.stderr)
return am_errors.AM_USERNOTEXISTS
# Have all the details - now update the user in the Django user database
# see:
# https://docs.djangoproject.com/en/1.7/ref/contrib/auth/#django.contrib.auth.models.User
# https://docs.djangoproject.c om/en/1.7/ref/contrib/auth/#manager-methods
user = userqueryset[0]
user.is_staff = True
user.is_superuser = True
user.save()
:
FWIW, my app is using 3rd party authentication (specifically atm OpenId Connect via Google+), so I think there's some common goal here. In my case I want to be able to add Django admin privileges to a user that has already been created.
The full module containing the above code is at github.com/gklyne/annalist/blob/develop/src/annalist_root/annalist_manager/am_createuser.py#L231
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).