def login_as(user, request, store_original_user=True): """ Utility function for forcing a login as specific user -- be careful about calling this carelessly :) """ # Save the original user pk before it is replaced in the login method original_user_pk = request.user.pk # Find a suitable backend. if not hasattr(user, "backend"): for backend in django_settings.AUTHENTICATION_BACKENDS: if not hasattr(load_backend(backend), "get_user"): continue if user == load_backend(backend).get_user(user.pk): user.backend = backend break else: raise ImproperlyConfigured("Could not found an appropriate authentication backend") # Add admin audit log entry if original_user_pk: change_message = "User {0} logged in as {1}.".format(request.user, user) LogEntry.objects.log_action( user_id=original_user_pk, content_type_id=ContentType.objects.get_for_model(user).pk, object_id=user.pk, object_repr=str(user), change_message=change_message, action_flag=CHANGE, ) # Log the user in. if not hasattr(user, "backend"): return if la_settings.UPDATE_LAST_LOGIN: login(request, user) else: with no_update_last_login(): login(request, user) # Set a flag on the session if store_original_user: messages.warning( request, la_settings.MESSAGE_LOGIN_SWITCH.format(username=user.__dict__[username_field]), extra_tags=la_settings.MESSAGE_EXTRA_TAGS, ) request.session[la_settings.USER_SESSION_FLAG] = signer.sign(original_user_pk)
def masquerade(request, username): if (settings.DEBUG) or request.user.is_superuser: """ Log in a user without requiring credentials (using ``login`` from``django.contrib.auth``, first finding a matching backend). THIS IS FOR DEBUGGING ONLY """ from django.contrib.auth import load_backend, login try: # user = User.objects.get(username=request.POST['userid']) user = User.objects.get(username=username) if not hasattr(user, "backend"): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, "backend"): login(request, user) request.session["_auth_user_backend"] = "django_cas.backends.CASBackend" except: messages.error(request, "That user does not exist") return HttpResponseRedirect(URL_ROOT + "/") return HttpResponseRedirect(URL_ROOT + "/")
def process_request(self, request): # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the OpenIdUserMiddleware class.") # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. if request.user.is_authenticated(): return try: userinfo = request.session['userinfo'] except Exception, e: # If specified header doesn't exist then remove any existing # authenticated remote-user, or return (leaving request.user set to # AnonymousUser by the AuthenticationMiddleware). if request.user.is_authenticated(): try: stored_backend = load_backend(request.session.get( auth.BACKEND_SESSION_KEY, '')) if isinstance(stored_backend, OpenIdUserBackend): auth.logout(request) except ImproperlyConfigured as e: # backend failed to load auth.logout(request)
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `MojAnonymousUser` is returned. """ user = None try: user_id = request.session[SESSION_KEY] token = request.session[AUTH_TOKEN_SESSION_KEY] user_data = request.session[USER_DATA_SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id, token, user_data) # Verify the session if hasattr(user, "get_session_auth_hash"): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or MojAnonymousUser()
def get(self, request): request_args = dict(getattr(settings, 'BROWSERID_REQUEST_ARGS', {})) # Only pass an email to the JavaScript if the current user was # authed with our auth backend. backend_name = self.request.session.get(auth.BACKEND_SESSION_KEY) backend = auth.load_backend(backend_name) if backend_name else None if isinstance(backend, BrowserIDBackend): email = getattr(request.user, 'email', '') else: email = '' # Different CSRF libraries (namely session_csrf) store the CSRF # token in different places. The only way to retrieve the token # that works with both the built-in CSRF and session_csrf is to # pull it from the template context processors via # RequestContext. context = RequestContext(request) csrf_token = context.get('csrf_token', None) return JSONResponse({ 'userEmail': email, 'loginUrl': reverse('browserid.login'), 'logoutUrl': reverse('browserid.logout'), 'requestArgs': request_args, 'csrfToken': csrf_token, })
def custom_on_success(request, identity_url, openid_response): # Reuse django_openidconsumer.views.default_on_success to set the # relevant session variables: consumer_views.default_on_success(request, identity_url, openid_response) # Now look up the user's identity_url to see if they exist in # the system try: user_openid = UserOpenID.objects.get(openid=identity_url) except UserOpenID.DoesNotExist: user_openid = None if user_openid: user = user_openid.user # Unfortunately we have to annotate the user with the # 'django.contrib.auth.backends.ModelBackend' backend, # or stuff breaks backend = load_backend('django.contrib.auth.backends.ModelBackend') user.backend = '%s.%s' % ( backend.__module__, backend.__class__.__name__ ) log_user_in(request, user) return on_login_ok(request, identity_url) else: return on_login_failed(request, identity_url)
def register(self, request, **kwargs): username, email, password = kwargs['email'], kwargs['email'], kwargs['password1'] if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site) # we'll secretly log the user in now from django.contrib.auth import load_backend, login for backend in settings.AUTHENTICATION_BACKENDS: if new_user == load_backend(backend).get_user(new_user.pk): new_user.backend = backend if hasattr(new_user, 'backend'): login(request, new_user) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) text = "We've sent you a verification email - please check it now!" messages.warning(request, text) return new_user
def process_request(self, request): # MOSTLY SAME CODE AS IN RemoteuserMiddleware !!! if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") # -- instead of try/except, we should ask the instance username = self.process_username(request) if not username: if request.user.is_authenticated(): try: stored_backend = load_backend(request.session.get( auth.BACKEND_SESSION_KEY, '')) if isinstance(stored_backend, ShibbolethUserBackend): auth.logout(request) except ImproperlyConfigured as e: auth.logout(request) return if request.user.is_authenticated(): if request.user.get_username() == self.clean_username(username, request): return # -- this is how it should be user = self.get_authenticated_user(username, request) # -- if user: request.user = user auth.login(request, user)
def __call__ (self, *args, **kwargs): request = args[0] request.json = json.loads(request.body) if 'token' in request.json: session = User.get_session(request.json['token']) user = None try: user_id = session[SESSION_KEY] backend_path = session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) if user: request.user = user return self.target(*args, **kwargs) return http.JsonResponse({'status': 'login-required'})
def sign_in_action(request): if request.user.is_authenticated(): return redirect(build_url('bookmark-let-page', request.POST)) else: auth = 0 username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): login(request, user) auth = 1 message = _("User is valid, active and authenticated") else: message = _("The password is valid, but the account has been disabled!") else: message = _("The username and password were incorrect.") if auth == 1: return redirect(build_url('bookmark-let-page', request.POST)) else: request.session['sign_in_message'] = message return redirect(build_url('sign-in-page', request.POST))
def login_as(user, request, store_original_user=True): """ Utility function for forcing a login as specific user -- be careful about calling this carelessly :) """ # Save the original user pk before it is replaced in the login method original_user_pk = request.user.pk # Get username field's name username_field = get_user_model().USERNAME_FIELD # Find a suitable backend. if not hasattr(user, 'backend'): for backend in django_settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break # Log the user in. if hasattr(user, 'backend'): login(request, user) else: return # Set a flag on the session if store_original_user: messages.warning(request, la_settings.MESSAGE_LOGIN_SWITCH.format(username=user.__dict__[username_field])) request.session[la_settings.USER_SESSION_FLAG] = signer.sign(original_user_pk)
def destroy_session(sender, **kwargs): """ Intercept the logout process so we can clear the Flourish session before Django's. Otherwise, the phpsessid could be used for Django URLs afterwards. Relies on `django.contrib.auth.logout` not using `send_robust`. """ try: request = kwargs['request'] except KeyError: return user = kwargs.get('user') if not user: return backend = load_backend(request.session[BACKEND_SESSION_KEY]) if not isinstance(backend, FlourishSessionBackend): return cookies = {'PHPSESSID': request.session['PHPSESSID']} session = requests.get(settings.FLOURISH_LOOPBACK_URLS['destroy'], cookies=cookies) # As long as no error was returned, the session's destroyed # (or never existed) so we can safely continue logging out. session.raise_for_status()
def openid_new_user(request): next = get_next(request) if request.method == 'POST': form = SSORegistrationForm(request.POST, request=request) if form.is_valid(): from django_openidauth.models import associate_openid from django.contrib.auth import load_backend new_user = form.save() associate_openid( new_user, request.openid ) backend = load_backend('django.contrib.auth.backends.ModelBackend') new_user.backend = '%s.%s' % ( backend.__module__, backend.__class__.__name__ ) auth_login(request, new_user) return new_user_registered_redirect(request, next or '/') else: initial = dict( next=next, ) form = SSORegistrationForm(initial=initial, request=request) return direct_to_template(request, "account/sso_registration.html", { 'form':form, })
def plugins_is_authenticated(request, sessionid): """ Given a sessionid, check whether it is authenticated and valid (not expired) Returns: bool """ engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore(sessionid) try: user_id = session[auth.SESSION_KEY] backend_path = session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_path) user = backend.get_user(user_id) except KeyError: # Fall back and check for API authentication http_auth = sessionid.decode('base64') # Simulate a request object required for FreeBasicAuthentication request = type( 'request', (object, ), {'META': {'HTTP_AUTHORIZATION': http_auth}} ) if FreeBasicAuthentication().is_authenticated(request): user = request.user else: return False if user and user.is_authenticated(): return True return False
def process_request(self, request): if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") try: username = request.META[self.header] except KeyError: # If specified header doesn't exist then remove any existing # authenticated remote-user, or return (leaving request.user set to # AnonymousUser by the AuthenticationMiddleware). if request.user.is_authenticated(): try: stored_backend = load_backend(request.session.get( auth.BACKEND_SESSION_KEY, '')) if isinstance(stored_backend, RemoteUserBackend): auth.logout(request) except ImportError: # backend failed to load auth.logout(request) return # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. # if request.user.is_authenticated(): # print request.user # if request.user.get_username() == self.clean_username(username, request): # return # We are seeing this user for the first time in this session, attempt # to authenticate the user. user = auth.authenticate(remote_user=username) if user: # User is valid. Set request.user and persist user in the session # by logging the user in. # update information from request user.first_name = request.META['HTTP_FNAME'] user.last_name = request.META['HTTP_LNAME'] user.email = request.META['HTTP_EMAIL'] user.save() # create an empty saved cde try: saved_cde = SavedCde.objects.get(user=user) except SavedCde.DoesNotExist: saved_cde = SavedCde.objects.create( id=user.id, user=user, questions='[]' ) saved_cde.save() request.user = user auth.login(request, user)
def get_backends(): from mailserver import get_setting backends = [] for backend_path in get_setting("MAIL_AUTHENTICATION_BACKENDS"): backends.append(load_backend(backend_path)) return backends
def is_worker(request): json_data = json.loads(request.raw_post_data, strict=False) engine = import_module(settings.SESSION_ENGINE) try: session = engine.SessionStore(json_data['session_key']) except KeyError: json_response = json.dumps({"success": "false", "type": "badRequest"}) return HttpResponse(json_response, mimetype='application/json') try: worker = session[SESSION_KEY] sample_path = session[BACKEND_SESSION_KEY] sample = load_backend(sample_path) user = sample.get_user(worker) or AnonymousUser() except KeyError: user = AnonymousUser() if user.is_authenticated(): try: if user.worker: json_data['worker'] = user.worker return json_data except: return False
def upload(self, request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) if 'picture' not in request.FILES: raise ValueError # Get the session. Wow. swfupload collects cookie values & # sticks them in the POST variables. We extract them & # authenticate the session manually. engine = import_module(settings.SESSION_ENGINE) session_key = request.POST.get(settings.SESSION_COOKIE_NAME) session = engine.SessionStore(session_key) if session: try: user_id = session[SESSION_KEY] backend_path = session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) user = backend.get_user(user_id) except KeyError: user = None self.request.is_widget_authenticated_by = user self.set_picture(image=request.FILES['picture']) return HttpResponse('ok')
def get_user(scope): """ Return the user model instance associated with the given scope. If no user is retrieved, return an instance of `AnonymousUser`. """ if "session" not in scope: raise ValueError( "Cannot find session in scope. You should wrap your consumer in SessionMiddleware." ) session = scope["session"] user = None try: user_id = _get_user_session_key(session) backend_path = session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, "get_session_auth_hash"): session_hash = session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: session.flush() user = None return user or AnonymousUser()
def user_login(request, user_id): user = User.objects.get(pk=user_id) CAN_LOGIN_AS = getattr(settings, "CAN_LOGIN_AS", lambda r, y: r.user.is_superuser) if isinstance(CAN_LOGIN_AS, six.string_types): can_login_as = _load_module(CAN_LOGIN_AS) elif hasattr(CAN_LOGIN_AS, "__call__"): can_login_as = CAN_LOGIN_AS else: raise ImproperlyConfigured("The CAN_LOGIN_AS setting is neither a valid module nor callable.") if not can_login_as(request, user): raise PermissionDenied("You are not allowed to login as a different user!") # Find a suitable backend. if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break # Log the user in. if hasattr(user, 'backend'): messages.info(request, 'You are logged in as "%s" now.' % user.username) login(request, user) return redirect(request.GET.get('next', '/'))
def return_(request): """Twitter OAuth return URL""" unauthed_token = request.session.get("unauthed_token", None) if not unauthed_token: return HttpResponse("No un-authed token cookie") token = oauth.OAuthToken.from_string(unauthed_token) if token.key != request.GET.get("oauth_token", "no-token"): return HttpResponse("Something went wrong! Tokens do not match") access_token = exchange_request_token_for_access_token(CONSUMER, create_connection(), token) request.session["access_token"] = access_token.to_string() # if the twitter user already exists and has a complete profile # redirect them to their profile page try: user = TwitterUser.objects.get(token=access_token.to_string()).user try: person = user.get_profile() # log in as this user from django.contrib.auth import load_backend, login for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend if hasattr(user, "backend"): login(request, user) return HttpResponseRedirect(person.get_absolute_url()) except KungfuPerson.DoesNotExist: pass except TwitterUser.DoesNotExist: pass return HttpResponseRedirect(reverse("twitter_signup"))
def user_login(request, user_id): user = User.objects.get(pk=user_id) CAN_LOGIN_AS = getattr(settings, "CAN_LOGIN_AS", lambda r, y: r.user.is_superuser) if isinstance(CAN_LOGIN_AS, six.string_types): can_login_as = _load_module(CAN_LOGIN_AS) elif hasattr(CAN_LOGIN_AS, "__call__"): can_login_as = CAN_LOGIN_AS else: raise ImproperlyConfigured("The CAN_LOGIN_AS setting is neither a valid module nor callable.") if not can_login_as(request, user): messages.error(request, "You do not have permission to do that.") return redirect(request.META.get("HTTP_REFERER", "/")) # Find a suitable backend. if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break # Log the user in. if hasattr(user, 'backend'): login(request, user) return redirect("/")
def post(self, request, *args, **kwargs): front_url = get_front_url() user = self.get_object() username_field = self.model.USERNAME_FIELD impersonator_user_id = request.user.pk if not front_url: raise Problem(_("No shop configured.")) if user == request.user: raise Problem(_("You are already logged in.")) if not getattr(request.user, "is_superuser", False): raise PermissionDenied if getattr(user, "is_superuser", False) or getattr(user, "is_staff", False): raise PermissionDenied if not getattr(user, "is_active", False): raise Problem(_("This user is not active.")) if not hasattr(user, 'backend'): for backend in django_settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break login(request, user) request.session["impersonator_user_id"] = impersonator_user_id message = _("You're now logged in as {username}").format(username=user.__dict__[username_field]) messages.success(request, message) return HttpResponseRedirect(front_url)
def get_backends(backend_paths): backends = [] for backend_path in backend_paths: backend = load_backend(backend_path) backends.append(backend) return backends
def user_login(request, user_id): user = User.objects.get(pk=user_id) CAN_LOGIN_AS = getattr(settings, "CAN_LOGIN_AS", lambda r, y: r.user.is_superuser) if isinstance(CAN_LOGIN_AS, six.string_types): can_login_as = _load_module(CAN_LOGIN_AS) elif hasattr(CAN_LOGIN_AS, "__call__"): can_login_as = CAN_LOGIN_AS else: raise ImproperlyConfigured("The CAN_LOGIN_AS setting is neither a valid module nor callable.") if not can_login_as(request, user): messages.error(request, "You do not have permission to do that.") return redirect(request.META.get("HTTP_REFERER", "/")) # Find a suitable backend. if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break # Save the original user pk before it is replaced in the login method original_user_pk = request.user.pk # Log the user in. if hasattr(user, 'backend'): login(request, user) # Set a flag on the session session_flag = getattr(settings, "LOGINAS_FROM_USER_SESSION_FLAG", "loginas_from_user") request.session[session_flag] = original_user_pk return redirect(settings.LOGIN_REDIRECT_URL)
def check_phpsessid(self, request): if request.user.is_authenticated: backend = auth.load_backend(request.session[auth.BACKEND_SESSION_KEY]) if not isinstance(backend, FlourishSessionBackend): return if not constant_time_compare(request.session['PHPSESSID'], request.COOKIES.get('PHPSESSID')): # The user has changed session or logged out without us knowing. # This should not happen. Clean up the both sessions just in case. auth.logout(request) return try: rawphpsessid = request.COOKIES['PHPSESSID'] except KeyError: return # Try to authenticate this user. It's pretty likely that # FlourishSessionBackend will succeed, but not guaranteed. # # Change the order of AUTHENTICATION_BACKENDS if this causes # you problems. user = auth.authenticate(request, rawphpsessid=rawphpsessid) if user: request.user = user auth.login(request, user)
def browserid_info(request): """ Output the HTML for the login form and the info tag. Should be called once at the top of the page just below the <body> tag. """ form = BrowserIDForm(auto_id=False) # Force request_args to be a dictionary, in case it is lazily generated. request_args = dict(getattr(settings, "BROWSERID_REQUEST_ARGS", {})) # Only pass an email to the JavaScript if the current user was authed with # our auth backend. backend_name = request.session.get(auth.BACKEND_SESSION_KEY) backend = auth.load_backend(backend_name) if backend_name else None if isinstance(backend, BrowserIDBackend): email = getattr(request.user, "email", "") else: email = "" return render_to_string( "browserid/info.html", { "email": email, "login_url": reverse("browserid_login"), "request_args": json.dumps(request_args, cls=LazyEncoder), "form": form, }, RequestContext(request), )
def login_with_facebook(req): url = 'https://graph.facebook.com/oauth/access_token?client_id='+settings.APP_ID_FACEBOOK+'&redirect_uri='+settings.URL+'/login/facebook/&client_secret='+settings.SECRET_KEY_FACEBOOK+'&code='+req.GET['code'] token = str(urllib2.urlopen(url).read()).split('=')[1] fb = facebook.GraphAPI(token) data = fb.get_object('me') user = None try: user = User.objects.create_user( username=data['username'], email=data['email'] ) profile = UserProfile.objects.create( facebook_token=token, user=user, image = 'https://graph.facebook.com/'+data['username']+'/picture' ) except: user = User.objects.get(username=data['username']) from django.contrib.auth import login, load_backend if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): login(req, user) return redirect('/home/')
def anonymous_login(request): new_username = "******" % ('anonymous', str(randint(100, 999))) if len(User.objects.filter(username=new_username)): new_username = "******" % ('anonymous', str(randint(100, 999))) creation_args = { 'username': new_username, 'email': '*****@*****.**', 'password': uuid.uuid1().hex, } this_user = User.objects.create(**creation_args) this_user.first_name = '' this_user.last_name = '' this_user.save() # we'll secretly log the user in now from django.contrib.auth import load_backend, login for backend in settings.AUTHENTICATION_BACKENDS: if this_user == load_backend(backend).get_user(this_user.pk): this_user.backend = backend if hasattr(this_user, 'backend'): login(request, this_user) request.session['firsttime'] = 1 url = reverse('home') return HttpResponseRedirect(url)
def get_current_user(self): """Get the current user using session data. """ session, user = self.current_session, None try: user_id = session[auth.SESSION_KEY] backend_path = session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_path) user = backend.get_user(user_id) except KeyError: pass if user is None: from django.contrib.auth import models if Settings.instance().auth: user = models.AnonymousUser() else: try: user = models.User.objects.get(username='******') except models.User.DoesNotExist: user = models.User(username='******') user.set_password('') user.save() return user
def _get_path_of_arbitrary_backend_for_user(user): """ Return the path to the first found authentication backend that recognizes the given user. """ for backend_path in settings.AUTHENTICATION_BACKENDS: backend = auth.load_backend(backend_path) if backend.get_user(user.id): return backend_path
def get_user_from_session(session): try: user_id = session[SESSION_KEY] backend_path = session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) return backend.get_user(user_id) or AnonymousUser() except KeyError: return AnonymousUser()
def override_login(request, user): if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): return login(request, user)
def get_backend(zone_name): zone_profile = get_zone_profile(zone_name) if not zone_profile: return None backend_path = zone_profile["AUTHENTICATION_BACKEND"] backendClazz = load_backend(backend_path) return backendClazz
def login_user(request, user): from django.contrib.auth import load_backend, login if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): return login(request, user)
def get_user_screen_name(request): #the backend is the one who knows where to look for the screen name of the user backend_path = request.session._session['_auth_user_backend'] user_backend = load_backend(backend_path) try: return user_backend.get_screen_name(request) except: return None
def socially_login(self, user): # use the backend for login from django.contrib.auth if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): return login(self.request, user)
def switch_user(request, object_id): # current/session user current_user = request.user session_user = request.session.get("original_user", { "id": current_user.id, "username": current_user.username }) # check original_user try: original_user = User.objects.get(pk=session_user["id"], is_staff=True) if not SWITCH_USER_ORIGINAL(original_user): messages.add_message(request, messages.ERROR, _("Permission denied.")) return redirect(request.GET.get("redirect")) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % { 'name': "User", 'key': escape(session_user["id"]) } messages.add_message(request, messages.ERROR, msg) return redirect(request.GET.get("redirect")) # check new user try: target_user = User.objects.get(pk=object_id, is_staff=True) if target_user != original_user and not SWITCH_USER_TARGET( original_user, target_user): messages.add_message(request, messages.ERROR, _("Permission denied.")) return redirect(request.GET.get("redirect")) except ObjectDoesNotExist: msg = _('%(name)s object with primary key %(key)r does not exist.') % { 'name': "User", 'key': escape(object_id) } messages.add_message(request, messages.ERROR, msg) return redirect(request.GET.get("redirect")) # find backend if not hasattr(target_user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if target_user == load_backend(backend).get_user(target_user.pk): target_user.backend = backend break # target user login, set original as session if hasattr(target_user, 'backend'): login(request, target_user) if original_user.id != target_user.id: request.session["original_user"] = { "id": original_user.id, "username": original_user.username } return redirect(request.GET.get("redirect"))
def get_user(request): from django.contrib.auth.models import AnonymousUser try: user_id = request.session[SESSION_KEY] backend = load_backend('django.contrib.auth.backends.ModelBackend') user = backend.get_user(user_id) or AnonymousUser() except KeyError: user = AnonymousUser() return user
def get_user_from_token(token): if token: backend_path = token.backend if backend_path in django_settings.AUTHENTICATION_BACKENDS: active_takeover_id = token.active_takeover.user.pk if token.active_takeover else None user_id = token.user.pk backend = load_backend(backend_path) return backend.get_user(active_takeover_id) or backend.get_user(user_id) or AnonymousUser() return AnonymousUser()
def get_user(request): try: user_id = request.session[SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) user = backend.get_user(user_id) or AnonymousUser() except KeyError: user = AnonymousUser() return user
def authenticate(request, **credentials): backend = load_backend( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication') try: (user, payload) = backend.authenticate(request, **credentials) except Exception: # This backend says to stop in our tracks - this user should not be allowed in at all. return None return user
def process_request(self, request): django_user = get_user(request) google_user = users.get_current_user() # Check to see if the user is authenticated with a different backend, if so, just set # request.user and bail if django_user.is_authenticated(): backend_str = request.session.get(BACKEND_SESSION_KEY) if (not backend_str) or not isinstance( load_backend(backend_str), BaseAppEngineUserAPIBackend): request.user = django_user return if django_user.is_anonymous() and google_user: # If there is a google user, but we are anonymous, log in! # Note that if DJANGAE_FORCE_USER_PRE_CREATION is True then this may not authenticate django_user = authenticate( google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) if django_user.is_authenticated(): if not google_user: # If we are logged in with django, but not longer logged in with Google # then log out logout(request) django_user = AnonymousUser() elif django_user.username != google_user.user_id(): # If the Google user changed, we need to log in with the new one logout(request) django_user = authenticate( google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) # Note that the logic above may have logged us out, hence new `if` statement if django_user.is_authenticated(): # Now make sure we update is_superuser and is_staff appropriately is_superuser = users.is_current_user_admin() resave = False if is_superuser != django_user.is_superuser: django_user.is_superuser = django_user.is_staff = is_superuser resave = True # for users which already exist, we want to verify that their email is still correct # users are already authenticated with their user_id, so we can save their real email # not the lowercased version if django_user.email != google_user.email(): django_user.email = google_user.email() resave = True if resave: django_user.save() request.user = django_user
def get_user(request): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ from django.contrib.auth.models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = (session_hash and constant_time_compare( session_hash, user.get_session_auth_hash())) if not session_hash_verified: session_hash_verified = ( session_hash and hasattr(user, '_legacy_get_session_auth_hash') and constant_time_compare( session_hash, user._legacy_get_session_auth_hash(), )) if not session_hash_verified and hasattr( settings, 'OLD_SECRET_KEY'): # noqa key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" # noqa compare_kwargs = {} if django.VERSION >= (3, 1): compare_kwargs['algorithm'] = ( settings.DEFAULT_HASHING_ALGORITHM if django.VERSION < (4, 0) else "sha256") session_hash_verified = session_hash and constant_time_compare( # noqa session_hash, salted_hmac(key_salt, user.password, secret=settings.OLD_SECRET_KEY, **compare_kwargs).hexdigest()) request.session.cycle_key() request.session[ HASH_SESSION_KEY] = user.get_session_auth_hash( ) # noqa if not session_hash_verified: request.session.flush() user = None return user or AnonymousUser()
def authenticate_new_user(request, username, password): """ Immediately after a user creates an account, we log them in. They are only logged in until they close the browser. They can't log in again until they click the activation link from the email. """ backend = load_backend(NEW_USER_AUTH_BACKEND) user = backend.authenticate(request=request, username=username, password=password) user.backend = NEW_USER_AUTH_BACKEND return user
def login_user(request, user): """Log in a user without requiring credentials with user object""" if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): return login(request, user)
def user_from_session_key(session_key): session_engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) session_wrapper = session_engine.SessionStore(session_key) user_id = session_wrapper.get(SESSION_KEY) auth_backend = load_backend(session_wrapper.get(BACKEND_SESSION_KEY)) if user_id and auth_backend: return auth_backend.get_user(user_id) else: return AnonymousUser()
def get_user_from_backend(user_id, backend_path): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ user = None if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) return user or AnonymousUser()
def get_backends(): backends = [] for backend_path in settings.AUTHENTICATION_BACKENDS: if not backend_path in settings.EXCLUDE_AUTHENTICATION_BACKENDS: backends.append(load_backend(backend_path)) if not backends: raise ImproperlyConfigured('No authentication backends have been defined. Does AUTHENTICATION_BACKENDS contain anything?') return backends
def get_zone(request): try: backend_path = request.session[BACKEND_SESSION_KEY] assert backend_path in settings.AUTHENTICATION_BACKENDS backend = load_backend(backend_path) return get_zone_profile(backend.zone_name) except (KeyError, AssertionError): return None return None
def clean_username(self, username, request): """ Allow the backend to clean the username, if the backend defines a clean_username method. """ backend_str = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_str) with suppress(AttributeError): # Backend has no clean_username method. username = backend.clean_username(username) return username
def get_user(request): try: user_id = request.session[auth.SESSION_KEY] backend_path = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_path) backend.request = request user = backend.get_user(user_id) or models.AnonymousUser() except KeyError: user = models.AnonymousUser() return user
def process_request(self, request): assert hasattr(request, 'session'), ( "The djangae.contrib.googleauth middleware requires session middleware " "to be installed. Edit your MIDDLEWARE%s setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'djangae.contrib.googleauth.middleware.AuthenticationMiddleware'." ) % ("_CLASSES" if settings.MIDDLEWARE is None else "") request.user = SimpleLazyObject(lambda: get_user(request)) backend_str = request.session.get(BACKEND_SESSION_KEY) if request.user.is_authenticated: if backend_str and isinstance(load_backend(backend_str), OAuthBackend): # The user is authenticated with Django, and they use the OAuth backend, so they # should have a valid oauth session oauth_session = OAuthUserSession.objects.filter( pk=request.user.google_oauth_id).first() # Their oauth session expired, so let's log them out if not oauth_session or not oauth_session.is_valid: logout(request) elif backend_str and isinstance(load_backend(backend_str), IAPBackend): if not IAPBackend.can_authenticate(request): logout(request) else: backends = get_backends() try: iap_backend = next( filter(lambda be: isinstance(be, IAPBackend), backends)) except StopIteration: iap_backend = None # Try to authenticate with IAP if the headers # are available if iap_backend and IAPBackend.can_authenticate(request): user = iap_backend.authenticate(request) if user and user.is_authenticated: user.backend = 'djangae.contrib.googleauth.backends.iap.%s' % IAPBackend.__name__ login(request, user)
def unassign_facebook(request): from django.contrib.auth import BACKEND_SESSION_KEY, load_backend from film20.facebook_connect.facebookAuth import FacebookBackend backend = load_backend(request.session[BACKEND_SESSION_KEY]) if isinstance(backend, FacebookBackend): return HttpResponse( "Can't remove association if you are logged in with FB") FBAssociation.objects.filter(user=request.user).delete() return HttpResponseRedirect(reverse('associations') + '?unassociated')
def get_user_from_session(session: SessionBase) -> Union[User, AnonymousUser]: """ Get User object (or AnonymousUser() if not logged in) from session. """ try: user_id = session[SESSION_KEY] backend_path = session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) return backend.get_user(user_id) or AnonymousUser() except KeyError: return AnonymousUser()
def authenticate(request, user): next_page = request.GET.get('next', '/') if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): login(request, user) return HttpResponseRedirect(next_page)
def logincode(request, code): _logincode = LoginCode.objects.get(code=code) user = _logincode.user if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): auth_login(request, user) return profileupdate(request)
def auto_login(request, user): # Auto-login bullshit because we don't want to write our own backend if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == auth.load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): auth.login(request, user) return True return False
def get_user(request): '''Retrieves the object representing the current user.''' from .models import AnonymousUser try: user_id = request.session[SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) user = backend.get_user(user_id) or AnonymousUser() except KeyError: user = AnonymousUser() return user
def login_without_password(request, user): from django.contrib.auth import load_backend import datetime user.last_login = datetime.datetime.now() user.save() backend = load_backend('django.contrib.auth.backends.ModelBackend') user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) request.session['_auth_user_id'] = user.id request.session['_auth_user_backend'] = user.backend if hasattr(request, 'user'): request.user = user