def process_response(self, request, response): """ Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url """ if request.is_ajax(): queued_msgs = request.horizon['async_messages'] if type(response) == http.HttpResponseRedirect: # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag, message, extra_tags in queued_msgs: getattr(django_messages, tag)(request, message, extra_tags) if response['location'].startswith(settings.LOGOUT_URL): redirect_response = http.HttpResponse(status=401) if self.logout_reason is not None: utils.add_logout_reason(request, redirect_response, self.logout_reason) else: redirect_response = http.HttpResponse() redirect_response['X-Horizon-Location'] = response['location'] return redirect_response if queued_msgs: # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response['X-Horizon-Messages'] = json.dumps(queued_msgs) return response
def process_exception(self, request, exception): """Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully. """ if isinstance(exception, (exceptions.NotAuthorized, exceptions.NotAuthenticated)): response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = ("Session expired") LOG.debug(msg + 'for user %s', request.user.id) utils.add_logout_reason(request, response, msg) response.set_cookie('logout_reason_level', 'warning', max_age=10) if request.is_ajax(): response_401 = http.HttpResponse(status=401) response_401['X-Horizon-Location'] = response['location'] return response_401 return response # If an internal "NotFound" error gets this far, return a real 404. if isinstance(exception, exceptions.NotFound): raise http.Http404(exception) if isinstance(exception, exceptions.Http302): # TODO(gabriel): Find a way to display an appropriate message to # the user *on* the login form... return shortcuts.redirect(exception.location)
def process_response(self, request, response): """Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url """ if request.is_ajax() and hasattr(request, 'horizon'): queued_msgs = request.horizon['async_messages'] if type(response) == http.HttpResponseRedirect: # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag, message, extra_tags in queued_msgs: getattr(django_messages, tag)(request, message, extra_tags) if response['location'].startswith(settings.LOGOUT_URL): redirect_response = http.HttpResponse(status=401) if self.logout_reason is not None: utils.add_logout_reason( request, redirect_response, self.logout_reason) else: redirect_response = http.HttpResponse() redirect_response['X-Horizon-Location'] = response['location'] return redirect_response if queued_msgs: # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response['X-Horizon-Messages'] = json.dumps(queued_msgs) return response
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) api.nova.systemlogs_create(request, request.user.username, record_action.CHANGEPASSWORD) return response except Exception: msg = _('Unable to change password.') exceptions.handle(request, msg) api.nova.systemlogs_create(request, request.user.username, record_action.CHANGEPASSWORD, result=False, detail=msg) return False else: messages.error(request, _('Changing password is not supported.')) api.nova.systemlogs_create(request, request.user.username, record_action.CHANGEPASSWORD, result=False, detail=msg) return False
def _logout(self, request, login_url=None, message=None): """Logout a user and display a logout message.""" response = auth_views.logout(request, login_url) if message is not None: self.logout_reason = message utils.add_logout_reason(request, response, message) return response
def process_request(self, request): """ Adds data necessary for Horizon to function to the request. """ # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = int(time.time()) request.horizon = { 'dashboard': None, 'panel': None, 'async_messages': [] } if (isinstance(last_activity, int) and (timestamp - last_activity) > timeout): request.session.pop('last_activity') response = HttpResponseRedirect( '%s?next=%s' % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session['last_activity'] = timestamp
def process_exception(self, request, exception): """ Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully. """ if isinstance(exception, (exceptions.NotAuthorized, exceptions.NotAuthenticated)): auth_url = settings.LOGIN_URL next_url = iri_to_uri(request.get_full_path()) if next_url != auth_url: field_name = REDIRECT_FIELD_NAME else: field_name = None login_url = request.build_absolute_uri(auth_url) response = redirect_to_login(next_url, login_url=login_url, redirect_field_name=field_name) if request.is_ajax(): response_401 = http.HttpResponse(status=401) response_401['X-Horizon-Location'] = response['location'] return response_401 else: utils.add_logout_reason(request, response, _("Unauthorized.")) return response # If an internal "NotFound" error gets this far, return a real 404. if isinstance(exception, exceptions.NotFound): raise http.Http404(exception) if isinstance(exception, exceptions.Http302): # TODO(gabriel): Find a way to display an appropriate message to # the user *on* the login form... return shortcuts.redirect(exception.location)
def process_request(self, request): """ Adds data necessary for Horizon to function to the request. """ # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout timeout = 1800 try: timeout = settings.SESSION_TIMEOUT except AttributeError: pass last_activity = request.session.get('last_activity', None) timestamp = datetime.datetime.now() if last_activity and (timestamp - last_activity).seconds > timeout: request.session.pop('last_activity') response = HttpResponseRedirect(settings.LOGOUT_URL) reason = _("Session timed out.") utils.add_logout_reason(request, response, reason) return response request.session['last_activity'] = timestamp request.horizon = { 'dashboard': None, 'panel': None, 'async_messages': [] }
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) response = http.HttpResponseRedirect(settings.LOGOUT_URL) username = str(request.user) if username == "admin": msg = _("Warning: %s password changed. Please wait 5 " "minutes then log in and Lock/Unlock the " "controllers for the password change to come " "into effect") % (username) else: msg = _("Password changed. " "Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = datetime.datetime.now() request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []} if last_activity and (timestamp - last_activity).seconds > timeout: request.session.pop('last_activity') response = HttpResponseRedirect( '%s?next=%s' % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session['last_activity'] = timestamp
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) # response = http.HttpResponseRedirect(settings.LOGOUT_URL) response = http.HttpResponseRedirect('/horizon/auth/login') userid = request.user.id print "this is setting userid : '%s'" % userid print "this is setting data['new_password'] : '******'" % data['new_password'] update_user_password(userid, data['new_password']) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False return True
def handle(self, request, data): user_has_mfa = adjutant.user_has_mfa(request) if user_has_mfa: try: submit_response = adjutant.remove_user_mfa(request, data['passcode']) if submit_response.status_code == 200: response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("MFA Removed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response elif submit_response.status_code == 400: messages.error(request, _('Unable to remove MFA. This may be ' 'due to an incorrectly entered ' 'passcode.')) else: messages.error(request, _('Unable to remove MFA.')) except Exception: exceptions.handle(request, _('Unable to remove MFA.')) else: messages.error(request, _('MFA not setup on this account.')) return http.HttpResponseRedirect(reverse("horizon:settings:mfa:index"))
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) # response = http.HttpResponseRedirect(settings.LOGOUT_URL) response = http.HttpResponseRedirect('/horizon/auth/login') userid = request.user.id print "this is setting userid : '%s'" % userid print "this is setting data['new_password'] : '******'" % data[ 'new_password'] update_user_password(userid, data['new_password']) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False return True
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() user_id = request.user.id user = api.keystone.user_get(self.request, user_id, admin=False) options = getattr(user, "options", {}) lock_password = options.get("lock_password", False) if lock_password: messages.error(request, _('Password is locked.')) return False if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = datetime.datetime.now() request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []} # If we use cookie-based sessions, check that the cookie size does not # reach the max size accepted by common web browsers. if ( settings.SESSION_ENGINE == 'django.contrib.sessions.backends.signed_cookies' ): max_cookie_size = getattr( settings, 'SESSION_COOKIE_MAX_SIZE', None) session_cookie_name = getattr( settings, 'SESSION_COOKIE_NAME', None) session_key = request.COOKIES.get(session_cookie_name) if max_cookie_size is not None and session_key is not None: cookie_size = sum(( len(key) + len(value) for key, value in request.COOKIES.iteritems() )) if cookie_size >= max_cookie_size: LOG.error( 'Total Cookie size for user_id: %(user_id)s is ' '%(cookie_size)sB >= %(max_cookie_size)sB. ' 'You need to configure file-based or database-backed ' 'sessions instead of cookie-based sessions: ' 'http://docs.openstack.org/developer/horizon/topics/' 'deployment.html#session-storage' % { 'user_id': request.session.get( 'user_id', 'Unknown'), 'cookie_size': cookie_size, 'max_cookie_size': max_cookie_size, } ) if last_activity and (timestamp - last_activity).seconds > timeout: request.session.pop('last_activity') response = HttpResponseRedirect( '%s?next=%s' % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session['last_activity'] = timestamp
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get("django_timezone") if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get("last_activity", None) timestamp = int(time.time()) request.horizon = {"dashboard": None, "panel": None, "async_messages": []} if not hasattr(request, "user") or not request.user.is_authenticated(): # proceed no further if the current request is already known # not to be authenticated return None if request.is_ajax(): # if the request is Ajax we do not want to proceed, as clients can # 1) create pages with constant polling, which can create race # conditions when a page navigation occurs # 2) might leave a user seemingly left logged in forever # 3) thrashes db backed session engines with tons of changes return None # If we use cookie-based sessions, check that the cookie size does not # reach the max size accepted by common web browsers. if settings.SESSION_ENGINE == "django.contrib.sessions.backends.signed_cookies": max_cookie_size = getattr(settings, "SESSION_COOKIE_MAX_SIZE", None) session_cookie_name = getattr(settings, "SESSION_COOKIE_NAME", None) session_key = request.COOKIES.get(session_cookie_name) if max_cookie_size is not None and session_key is not None: cookie_size = sum((len(key) + len(value) for key, value in request.COOKIES.iteritems())) if cookie_size >= max_cookie_size: LOG.error( "Total Cookie size for user_id: %(user_id)s is " "%(cookie_size)sB >= %(max_cookie_size)sB. " "You need to configure file-based or database-backed " "sessions instead of cookie-based sessions: " "http://docs.openstack.org/developer/horizon/topics/" "deployment.html#session-storage" % { "user_id": request.session.get("user_id", "Unknown"), "cookie_size": cookie_size, "max_cookie_size": max_cookie_size, } ) if isinstance(last_activity, int) and (timestamp - last_activity) > timeout: request.session.pop("last_activity") response = HttpResponseRedirect("%s?next=%s" % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session["last_activity"] = timestamp
def process_response(self, request, response): """Convert HttpResponseRedirect to HttpResponse if request is via ajax. This is to allow ajax request to redirect url. """ if request.is_ajax() and hasattr(request, 'horizon'): queued_msgs = request.horizon['async_messages'] if type(response) == http.HttpResponseRedirect: # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag, message, extra_tags in queued_msgs: getattr(django_messages, tag)(request, message, extra_tags) if response['location'].startswith(settings.LOGOUT_URL): redirect_response = http.HttpResponse(status=401) # This header is used for handling the logout in JS redirect_response['logout'] = True if self.logout_reason is not None: utils.add_logout_reason(request, redirect_response, self.logout_reason, 'error') else: redirect_response = http.HttpResponse() # Use a set while checking if we want a cookie's attributes # copied cookie_keys = { 'max_age', 'expires', 'path', 'domain', 'secure', 'httponly', 'logout_reason' } # Copy cookies from HttpResponseRedirect towards HttpResponse for cookie_name, cookie in response.cookies.items(): cookie_kwargs = dict(((key, value) for key, value in cookie.items() if key in cookie_keys and value)) redirect_response.set_cookie(cookie_name, cookie.value, **cookie_kwargs) redirect_response['X-Horizon-Location'] = response['location'] upload_url_key = 'X-File-Upload-URL' if upload_url_key in response: self.copy_headers(response, redirect_response, (upload_url_key, 'X-Auth-Token')) return redirect_response if queued_msgs: # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response['X-Horizon-Messages'] = json.dumps(queued_msgs) elif type(response) == http.HttpResponseRedirect: # WRS: redirect from login page to overview page without start and # end parameters so that user can login quickly without populating # nova usage table if '/admin/?start=' in response.url: return http.HttpResponseRedirect('/admin/') return response
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = int(time.time()) request.horizon = { 'dashboard': None, 'panel': None, 'async_messages': [] } # If we use cookie-based sessions, check that the cookie size does not # reach the max size accepted by common web browsers. if (settings.SESSION_ENGINE == 'django.contrib.sessions.backends.signed_cookies'): max_cookie_size = getattr(settings, 'SESSION_COOKIE_MAX_SIZE', None) session_cookie_name = getattr(settings, 'SESSION_COOKIE_NAME', None) session_key = request.COOKIES.get(session_cookie_name) if max_cookie_size is not None and session_key is not None: cookie_size = sum( (len(key) + len(value) for key, value in request.COOKIES.iteritems())) if cookie_size >= max_cookie_size: LOG.error( 'Total Cookie size for user_id: %(user_id)s is ' '%(cookie_size)sB >= %(max_cookie_size)sB. ' 'You need to configure file-based or database-backed ' 'sessions instead of cookie-based sessions: ' 'http://docs.openstack.org/developer/horizon/topics/' 'deployment.html#session-storage' % { 'user_id': request.session.get( 'user_id', 'Unknown'), 'cookie_size': cookie_size, 'max_cookie_size': max_cookie_size, }) if (isinstance(last_activity, int) and (timestamp - last_activity) > timeout): request.session.pop('last_activity') response = HttpResponseRedirect( '%s?next=%s' % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session['last_activity'] = timestamp
def handle(self, request, data): submit_response = adjutant.signup_submit(request, data) if submit_response.ok: return True # Send the user back to the login page. msg = _("The signup service is currently unavailable. " "Please try again later.") response = http.HttpResponseRedirect(settings.LOGOUT_URL) utils.add_logout_reason(self.request, response, msg) return response
def handle(self, request, data): if not self.user_is_editable: messages.error(self.request, ('Changing password is not supported.')) return False response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = ('Password changed correctly!. Please log in again to continue.') LOG.info(msg) utils.add_logout_reason(request, response, msg) response.set_cookie('logout_reason_level', 'success', max_age=10) return response
def process_exception(self, request, exception): """Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully. """ if isinstance(exception, (exceptions.NotAuthorized, exceptions.NotAuthenticated)): auth_url = settings.LOGIN_URL next_url = None # prevent submiting forms after login and # use http referer if request.method in ("POST", "PUT"): referrer = request.META.get('HTTP_REFERER') if referrer and is_safe_url(referrer, request.get_host()): next_url = referrer if not next_url: next_url = iri_to_uri(request.get_full_path()) if next_url != auth_url: field_name = REDIRECT_FIELD_NAME else: field_name = None login_url = request.build_absolute_uri(auth_url) response = redirect_to_login(next_url, login_url=login_url, redirect_field_name=field_name) if isinstance(exception, exceptions.NotAuthorized): logout_reason = _("Unauthorized. Please try logging in again.") utils.add_logout_reason(request, response, logout_reason) # delete messages, created in get_data() method # since we are going to redirect user to the login page response.delete_cookie('messages') if request.is_ajax(): response_401 = http.HttpResponse(status=401) response_401['X-Horizon-Location'] = response['location'] return response_401 return response # If an internal "NotFound" error gets this far, return a real 404. if isinstance(exception, exceptions.NotFound): raise http.Http404(exception) if isinstance(exception, exceptions.Http302): # TODO(gabriel): Find a way to display an appropriate message to # the user *on* the login form... return shortcuts.redirect(exception.location)
def handle(self, request, data): try: submit_response = adjutant.forgotpassword_submit(request, data) if submit_response.ok: return True except Exception: pass # Send the user back to the login page. msg = _("The password reset service is currently unavailable. " "Please try again later.") response = http.HttpResponseRedirect(settings.LOGOUT_URL) utils.add_logout_reason(self.request, response, msg) return response
def process_response(self, request, response): """Convert HttpResponseRedirect to HttpResponse if request is via ajax. This is to allow ajax request to redirect url. """ if request.is_ajax() and hasattr(request, 'horizon'): queued_msgs = request.horizon['async_messages'] if type(response) == http.HttpResponseRedirect: # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag, message, extra_tags in queued_msgs: getattr(django_messages, tag)(request, message, extra_tags) if response['location'].startswith(settings.LOGOUT_URL): redirect_response = http.HttpResponse(status=401) # This header is used for handling the logout in JS redirect_response['logout'] = True if self.logout_reason is not None: utils.add_logout_reason( request, redirect_response, self.logout_reason, 'error') else: redirect_response = http.HttpResponse() # Use a set while checking if we want a cookie's attributes # copied cookie_keys = {'max_age', 'expires', 'path', 'domain', 'secure', 'httponly', 'logout_reason'} # Copy cookies from HttpResponseRedirect towards HttpResponse for cookie_name, cookie in response.cookies.items(): cookie_kwargs = dict(( (key, value) for key, value in cookie.items() if key in cookie_keys and value )) redirect_response.set_cookie( cookie_name, cookie.value, **cookie_kwargs) redirect_response['X-Horizon-Location'] = response['location'] upload_url_key = 'X-File-Upload-URL' if upload_url_key in response: self.copy_headers(response, redirect_response, (upload_url_key, 'X-Auth-Token')) return redirect_response if queued_msgs: # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response['X-Horizon-Messages'] = json.dumps(queued_msgs) return response
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data["current_password"], data["new_password"]) response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _("Unable to change password.")) return False else: messages.error(request, _("Changing password is not supported.")) return False
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get("django_timezone") if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get("last_activity", None) timestamp = int(time.time()) request.horizon = {"dashboard": None, "panel": None, "async_messages": []} # If we use cookie-based sessions, check that the cookie size does not # reach the max size accepted by common web browsers. if settings.SESSION_ENGINE == "django.contrib.sessions.backends.signed_cookies": max_cookie_size = getattr(settings, "SESSION_COOKIE_MAX_SIZE", None) session_cookie_name = getattr(settings, "SESSION_COOKIE_NAME", None) session_key = request.COOKIES.get(session_cookie_name) if max_cookie_size is not None and session_key is not None: cookie_size = sum((len(key) + len(value) for key, value in request.COOKIES.iteritems())) if cookie_size >= max_cookie_size: LOG.error( "Total Cookie size for user_id: %(user_id)s is " "%(cookie_size)sB >= %(max_cookie_size)sB. " "You need to configure file-based or database-backed " "sessions instead of cookie-based sessions: " "http://docs.openstack.org/developer/horizon/topics/" "deployment.html#session-storage" % { "user_id": request.session.get("user_id", "Unknown"), "cookie_size": cookie_size, "max_cookie_size": max_cookie_size, } ) if isinstance(last_activity, int) and (timestamp - last_activity) > timeout: request.session.pop("last_activity") response = HttpResponseRedirect("%s?next=%s" % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session["last_activity"] = timestamp
def handle(self, request, data): usable_data = self.cleaned_data user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable and usable_data: try: api.keystone.user_update_own_password( request, usable_data['current_password'], usable_data['new_password']) response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False
def process_request(self, request): path = request.META['PATH_INFO'] if _is_static_or_media_requests(self, path): return if (reverse('logout') == path or not hasattr(request, 'user') or not request.user.is_authenticated() or reverse('fiware_auth_expired_password') == path): return if (fiware_api.keystone.user_is_password_expired(request)): response = http.HttpResponseRedirect(reverse('fiware_auth_expired_password')) msg = ("It's been a long time since you haven't changed your password. Please choose a new one.") LOG.debug(msg + 'for user %s', request.user.id) utils.add_logout_reason(request, response, msg) response.set_cookie('logout_reason_level', 'warning', max_age=10) return response
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if not user_is_editable: messages.error(request, _('Activating password is not supported.')) return False try: #api.keystone.user_update_own_password(request, None, data['new_password']) api.keystone.user_update_password(request, request.user.id, data['new_password'], False) response = http.HttpResponseRedirect(reverse_lazy('logout')) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to activate password.')) return False
def process_response(self, request, response): """Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url """ if request.is_ajax() and hasattr(request, 'horizon'): queued_msgs = request.horizon['async_messages'] if type(response) == http.HttpResponseRedirect: # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag, message, extra_tags in queued_msgs: getattr(django_messages, tag)(request, message, extra_tags) if response['location'].startswith(settings.LOGOUT_URL): redirect_response = http.HttpResponse(status=401) # This header is used for handling the logout in JS redirect_response['logout'] = True if self.logout_reason is not None: utils.add_logout_reason(request, redirect_response, self.logout_reason) else: redirect_response = http.HttpResponse() # Copy cookies from HttpResponseRedirect towards HttpResponse for cookie_name, cookie in six.iteritems(response.cookies): cookie_kwargs = dict( ((key, value) for key, value in six.iteritems(cookie) if key in ('max_age', 'expires', 'path', 'domain', 'secure', 'httponly', 'logout_reason') and value)) redirect_response.set_cookie(cookie_name, cookie.value, **cookie_kwargs) redirect_response['X-Horizon-Location'] = response['location'] return redirect_response if queued_msgs: # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response['X-Horizon-Messages'] = json.dumps(queued_msgs) return response
def process_response(self, request, response): """Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url """ if request.is_ajax() and hasattr(request, "horizon"): queued_msgs = request.horizon["async_messages"] if type(response) == http.HttpResponseRedirect: # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag, message, extra_tags in queued_msgs: getattr(django_messages, tag)(request, message, extra_tags) if response["location"].startswith(settings.LOGOUT_URL): redirect_response = http.HttpResponse(status=401) # This header is used for handling the logout in JS redirect_response["logout"] = True if self.logout_reason is not None: utils.add_logout_reason(request, redirect_response, self.logout_reason) else: redirect_response = http.HttpResponse() # Copy cookies from HttpResponseRedirect towards HttpResponse for cookie_name, cookie in response.cookies.iteritems(): cookie_kwargs = dict( ( (key, value) for key, value in cookie.iteritems() if key in ("max_age", "expires", "path", "domain", "secure", "httponly", "logout_reason") and value ) ) redirect_response.set_cookie(cookie_name, cookie.value, **cookie_kwargs) redirect_response["X-Horizon-Location"] = response["location"] return redirect_response if queued_msgs: # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response["X-Horizon-Messages"] = json.dumps(queued_msgs) return response
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = ('Password changed. Please log in again to continue.') LOG.info(msg) utils.add_logout_reason(request, response, msg) response.set_cookie('logout_reason_level', 'success', max_age=10) return response except Exception: exceptions.handle(request, ('Unable to change password.')) return False else: messages.error(request, ('Changing password is not supported.')) return False
def process_request(self, request): path = request.META['PATH_INFO'] if _is_static_or_media_requests(self, path): return if (reverse('logout') == path or not hasattr(request, 'user') or not request.user.is_authenticated() or reverse('fiware_auth_expired_password') == path): return if (fiware_api.keystone.user_is_password_expired(request)): response = http.HttpResponseRedirect( reverse('fiware_auth_expired_password')) msg = ( "It's been a long time since you haven't changed your password. Please choose a new one." ) LOG.debug(msg + 'for user %s', request.user.id) utils.add_logout_reason(request, response, msg) response.set_cookie('logout_reason_level', 'warning', max_age=10) return response
def process_request(self, request): path = request.META['PATH_INFO'] if _is_static_or_media_requests(self, path): return if (reverse('logout') == path or not hasattr(request, 'user') or not request.user.is_authenticated()): return try: user_data = api.keystone.user_get(request, request.user.id) # setattr(user_data, 'username', user_data.name) for attr, value in user_data.__dict__.iteritems(): setattr(request.user, attr, value) except (kc_exceptions.Unauthorized, exceptions.NotAuthorized): response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = ("Session expired") LOG.debug(msg + 'for user %s', request.user.id) utils.add_logout_reason(request, response, msg) return response
def process_request(self, request): path = request.META['PATH_INFO'] if _is_static_or_media_requests(self, path): return if (reverse('logout') == path or not hasattr(request, 'user') or not request.user.is_authenticated()): return try: user_data = api.keystone.user_get(request, request.user.id) LOG.debug(str(user_data) + 'for user %s', request.user.id) # setattr(user_data, 'username', user_data.name) for attr, value in user_data.__dict__.iteritems(): setattr(request.user, attr, value) except (kc_exceptions.Unauthorized, exceptions.NotAuthorized): response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = ("Session expired") LOG.debug(msg + 'for user %s', request.user.id) utils.add_logout_reason(request, response, msg) return response
def handle(self, request, data): user_has_mfa = adjutant.user_has_mfa(request) if not user_has_mfa: try: submit_response = adjutant.token_submit( request, data.pop('token_id'), data) if submit_response.status_code == 200: response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("MFA Setup. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response else: messages.error(request, _('Unable to setup MFA. Your passcode ' 'may be incorrect.')) except Exception: exceptions.handle(request, _('Unable to setup MFA.')) else: messages.error(request, _('MFA already setup for this account.')) return http.HttpResponseRedirect(reverse("horizon:settings:mfa:index"))
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if not user_is_editable: messages.error(request, _('Activating password is not supported.')) return False try: api.keystone.user_update_own_password(request, None, data['new_password']) if 'REMOTE_USER' in request.META and \ (request.path.startswith('/dashboard-shib') or \ request.path.startswith('/dashboard-google')): return http.HttpResponseRedirect(reverse_lazy('login')) else: response = http.HttpResponseRedirect(reverse_lazy('logout')) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to activate password.')) return False
def single(self, data_table, request, obj_id): try: t_role_id = '' for role in request.user.roles: if role['name'] == TENANTADMIN_ROLE: t_role_id = get_admin_roleid(request) roles_obj = client_factory(request).roles arg_dict = { 'project' : request.user.tenant_id, 'user' : obj_id } users_obj = client_factory(request).users member = users_obj.get(obj_id) datum = data_table.get_object_by_id(obj_id) if datum.is_t_admin: if datum.num_of_roles == 1: missing_default = True for item in roles_obj.list(): if item.name == DEFAULT_ROLE: roles_obj.grant(item.id, **arg_dict) missing_default = False if missing_default: raise Exception('Cannot swith to member role') roles_obj.revoke(t_role_id, **arg_dict) noti_params = { 'admin_address' : users_obj.get(request.user.id).email, 'project' : request.user.tenant_name, 's_role' : _('Project manager'), 'd_role' : _('Project user') } noti_sbj, noti_body = notification_render(CHANGED_MEMBER_ROLE, noti_params) notifyUsers(member.email, noti_sbj, noti_body) else: roles_obj.grant(t_role_id, **arg_dict) noti_params = { 'admin_address' : users_obj.get(request.user.id).email, 'project' : request.user.tenant_name, 's_role' : _('Project user'), 'd_role' : _('Project manager') } noti_sbj, noti_body = notification_render(CHANGED_MEMBER_ROLE, noti_params) notifyUsers(member.email, noti_sbj, noti_body) except: LOG.error("Toggle role error", exc_info=True) messages.error(request, _('Unable to toggle the role.')) if obj_id == request.user.id: response = shortcuts.redirect(reverse_lazy('logout')) msg = _("Roles changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response return shortcuts.redirect(reverse_lazy('horizon:idmanager:member_manager:index'))
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = int(time.time()) request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []} if not hasattr(request, "user") or not request.user.is_authenticated(): # proceed no further if the current request is already known # not to be authenticated return None if request.is_ajax(): # if the request is Ajax we do not want to proceed, as clients can # 1) create pages with constant polling, which can create race # conditions when a page navigation occurs # 2) might leave a user seemingly left logged in forever # 3) thrashes db backed session engines with tons of changes return None # If we use cookie-based sessions, check that the cookie size does not # reach the max size accepted by common web browsers. if ( settings.SESSION_ENGINE == 'django.contrib.sessions.backends.signed_cookies' ): max_cookie_size = getattr( settings, 'SESSION_COOKIE_MAX_SIZE', None) session_cookie_name = getattr( settings, 'SESSION_COOKIE_NAME', None) session_key = request.COOKIES.get(session_cookie_name) if max_cookie_size is not None and session_key is not None: cookie_size = sum(( len(key) + len(value) for key, value in request.COOKIES.iteritems() )) if cookie_size >= max_cookie_size: LOG.error( 'Total Cookie size for user_id: %(user_id)s is ' '%(cookie_size)sB >= %(max_cookie_size)sB. ' 'You need to configure file-based or database-backed ' 'sessions instead of cookie-based sessions: ' 'http://docs.openstack.org/developer/horizon/topics/' 'deployment.html#session-storage' % { 'user_id': request.session.get( 'user_id', 'Unknown'), 'cookie_size': cookie_size, 'max_cookie_size': max_cookie_size, } ) if (isinstance(last_activity, int) and (timestamp - last_activity) > timeout): request.session.pop('last_activity') response = HttpResponseRedirect( '%s?next=%s' % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session['last_activity'] = timestamp
def single(self, data_table, request, obj_id): try: t_role_id = '' for role in request.user.roles: if role['name'] == TENANTADMIN_ROLE: t_role_id = get_admin_roleid(request) roles_obj = client_factory(request).roles arg_dict = {'project': request.user.tenant_id, 'user': obj_id} tmpres = EMail.objects.filter(registration__userid=obj_id) member_email = tmpres[0].email if tmpres else None tmpres = EMail.objects.filter(registration__userid=request.user.id) admin_email = tmpres[0].email if tmpres else None datum = data_table.get_object_by_id(obj_id) if datum.is_t_admin: with transaction.atomic(): PrjRole.objects.filter(registration__userid=obj_id, project__projectname=request.user. tenant_name).delete() if datum.num_of_roles == 1: missing_default = True for item in roles_obj.list(): if item.name == DEFAULT_ROLE: roles_obj.grant(item.id, **arg_dict) missing_default = False if missing_default: raise Exception('Cannot swith to member role') roles_obj.revoke(t_role_id, **arg_dict) noti_params = { 'admin_address': admin_email, 'project': request.user.tenant_name, 's_role': _('Project manager'), 'd_role': _('Project user') } notifyUser(request=request, rcpt=member_email, action=CHANGED_MEMBER_ROLE, context=noti_params, dst_project_id=request.user.project_id, dst_user_id=obj_id) else: with transaction.atomic(): prjRole = PrjRole() prjRole.registration = Registration.objects.filter( userid=obj_id)[0] prjRole.project = Project.objects.get( projectname=request.user.tenant_name) prjRole.roleid = t_role_id prjRole.save() roles_obj.grant(t_role_id, **arg_dict) noti_params = { 'admin_address': admin_email, 'project': request.user.tenant_name, 's_role': _('Project user'), 'd_role': _('Project manager') } notifyUser(request=request, rcpt=member_email, action=CHANGED_MEMBER_ROLE, context=noti_params, dst_project_id=request.user.project_id, dst_user_id=obj_id) except: LOG.error("Toggle role error", exc_info=True) messages.error(request, _('Unable to toggle the role.')) if obj_id == request.user.id: response = shortcuts.redirect(reverse_lazy('logout')) msg = _("Roles changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response return shortcuts.redirect( reverse_lazy('horizon:idmanager:member_manager:index'))
def _logout_msg_response(request, msg): response = http.HttpResponseRedirect(settings.LOGOUT_URL) utils.add_logout_reason(request, response, msg) return response
def single(self, data_table, request, obj_id): try: t_role_id = '' for role in request.user.roles: if role['name'] == TENANTADMIN_ROLE: t_role_id = get_admin_roleid(request) roles_obj = client_factory(request).roles arg_dict = { 'project' : request.user.tenant_id, 'user' : obj_id } tmpres = EMail.objects.filter(registration__userid=obj_id) member_email = tmpres[0].email if tmpres else None tmpres = EMail.objects.filter(registration__userid=request.user.id) admin_email = tmpres[0].email if tmpres else None datum = data_table.get_object_by_id(obj_id) if datum.is_t_admin: with transaction.atomic(): PrjRole.objects.filter( registration__userid=obj_id, project__projectname=request.user.tenant_name ).delete() if datum.num_of_roles == 1: missing_default = True for item in roles_obj.list(): if item.name == DEFAULT_ROLE: roles_obj.grant(item.id, **arg_dict) missing_default = False if missing_default: raise Exception('Cannot swith to member role') roles_obj.revoke(t_role_id, **arg_dict) noti_params = { 'admin_address' : admin_email, 'project' : request.user.tenant_name, 's_role' : _('Project manager'), 'd_role' : _('Project user') } notifyUser(request=request, rcpt=member_email, action=CHANGED_MEMBER_ROLE, context=noti_params, dst_project_id=request.user.project_id, dst_user_id=obj_id) else: with transaction.atomic(): prjRole = PrjRole() prjRole.registration = Registration.objects.filter(userid=obj_id)[0] prjRole.project = Project.objects.get(projectname=request.user.tenant_name) prjRole.roleid = t_role_id prjRole.save() roles_obj.grant(t_role_id, **arg_dict) noti_params = { 'admin_address' : admin_email, 'project' : request.user.tenant_name, 's_role' : _('Project user'), 'd_role' : _('Project manager') } notifyUser(request=request, rcpt=member_email, action=CHANGED_MEMBER_ROLE, context=noti_params, dst_project_id=request.user.project_id, dst_user_id=obj_id) except: LOG.error("Toggle role error", exc_info=True) messages.error(request, _('Unable to toggle the role.')) if obj_id == request.user.id: response = shortcuts.redirect(reverse_lazy('logout')) msg = _("Roles changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response return shortcuts.redirect(reverse_lazy('horizon:idmanager:member_manager:index'))