File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/auth.tar
Back
handlers/__pycache__/__init__.cpython-310.pyc 0000644 00000000270 15030037112 0015003 0 ustar 00 o �h � @ s d S )N� r r r �[/usr/local/CyberPanel/lib/python3.10/site-packages/django/contrib/auth/handlers/__init__.py�<module> s handlers/__pycache__/modwsgi.cpython-310.pyc 0000644 00000002537 15030037112 0014725 0 ustar 00 o �h� � @ s4 d dl mZ d dlmZ e�� Zdd� Zdd� ZdS )� )�db)�authc C sn t �� z-ztj�|�}W n tjy Y W t �� dS w |js(W t �� dS |�|�W t �� S t �� w )z� Authenticate against Django's auth database. mod_wsgi docs specify None, True, False as return value depending on whether the user exists and authenticates. N) r � reset_queries� UserModel�_default_manager�get_by_natural_key�DoesNotExist�close_old_connections� is_active�check_password)�environ�username�password�user� r �Z/usr/local/CyberPanel/lib/python3.10/site-packages/django/contrib/auth/handlers/modwsgi.pyr s � �r c C sz t �� z3ztj�|�}W n tjy g Y W t �� S w |js)g W t �� S dd� |j� � D �W t �� S t �� w )z* Authorize a user based on groups c S s g | ]}|j �� �qS r )�name�encode)�.0�groupr r r � <listcomp>) s z#groups_for_user.<locals>.<listcomp>) r r r r r r r r �groups�all)r r r r r r �groups_for_user s � �r N)�djangor �django.contribr �get_user_modelr r r r r r r �<module> s handlers/modwsgi.py 0000644 00000002340 15030037112 0010356 0 ustar 00 from django import db from django.contrib import auth UserModel = auth.get_user_model() def check_password(environ, username, password): """ Authenticate against Django's auth database. mod_wsgi docs specify None, True, False as return value depending on whether the user exists and authenticates. """ # db connection state is managed similarly to the wsgi handler # as mod_wsgi may call these functions outside of a request/response cycle db.reset_queries() try: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return None if not user.is_active: return None return user.check_password(password) finally: db.close_old_connections() def groups_for_user(environ, username): """ Authorize a user based on groups """ db.reset_queries() try: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return [] if not user.is_active: return [] return [group.name.encode() for group in user.groups.all()] finally: db.close_old_connections() handlers/__init__.py 0000644 00000000000 15030037112 0010433 0 ustar 00 views.py 0000644 00000034156 15030037112 0006254 0 ustar 00 import warnings from urllib.parse import urlparse, urlunparse from django.conf import settings # Avoid shadowing the login() and logout() views below. from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model from django.contrib.auth import login as auth_login from django.contrib.auth import logout as auth_logout from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm, ) from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured, ValidationError from django.http import HttpResponseRedirect, QueryDict from django.shortcuts import resolve_url from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.utils.deprecation import RemovedInDjango50Warning from django.utils.http import url_has_allowed_host_and_scheme, urlsafe_base64_decode from django.utils.translation import gettext_lazy as _ from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters from django.views.generic.base import TemplateView from django.views.generic.edit import FormView UserModel = get_user_model() class RedirectURLMixin: next_page = None redirect_field_name = REDIRECT_FIELD_NAME success_url_allowed_hosts = set() def get_success_url(self): return self.get_redirect_url() or self.get_default_redirect_url() def get_redirect_url(self): """Return the user-originating redirect URL if it's safe.""" redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name) ) url_is_safe = url_has_allowed_host_and_scheme( url=redirect_to, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) return redirect_to if url_is_safe else "" def get_success_url_allowed_hosts(self): return {self.request.get_host(), *self.success_url_allowed_hosts} def get_default_redirect_url(self): """Return the default redirect URL.""" if self.next_page: return resolve_url(self.next_page) raise ImproperlyConfigured("No URL to redirect to. Provide a next_page.") class LoginView(RedirectURLMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None template_name = "registration/login.html" redirect_authenticated_user = False extra_context = None @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): if self.redirect_authenticated_user and self.request.user.is_authenticated: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def get_default_redirect_url(self): """Return the default redirect URL.""" if self.next_page: return resolve_url(self.next_page) else: return resolve_url(settings.LOGIN_REDIRECT_URL) def get_form_class(self): return self.authentication_form or self.form_class def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["request"] = self.request return kwargs def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update( { self.redirect_field_name: self.get_redirect_url(), "site": current_site, "site_name": current_site.name, **(self.extra_context or {}), } ) return context class LogoutView(RedirectURLMixin, TemplateView): """ Log out the user and display the 'You are logged out' message. """ # RemovedInDjango50Warning: when the deprecation ends, remove "get" and # "head" from http_method_names. http_method_names = ["get", "head", "post", "options"] template_name = "registration/logged_out.html" extra_context = None # RemovedInDjango50Warning: when the deprecation ends, move # @method_decorator(csrf_protect) from post() to dispatch(). @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): if request.method.lower() == "get": warnings.warn( "Log out via GET requests is deprecated and will be removed in Django " "5.0. Use POST requests for logging out.", RemovedInDjango50Warning, ) return super().dispatch(request, *args, **kwargs) @method_decorator(csrf_protect) def post(self, request, *args, **kwargs): """Logout may be done via POST.""" auth_logout(request) redirect_to = self.get_success_url() if redirect_to != request.get_full_path(): # Redirect to target page once the session has been cleared. return HttpResponseRedirect(redirect_to) return super().get(request, *args, **kwargs) # RemovedInDjango50Warning. get = post def get_default_redirect_url(self): """Return the default redirect URL.""" if self.next_page: return resolve_url(self.next_page) elif settings.LOGOUT_REDIRECT_URL: return resolve_url(settings.LOGOUT_REDIRECT_URL) else: return self.request.path def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update( { "site": current_site, "site_name": current_site.name, "title": _("Logged out"), "subtitle": None, **(self.extra_context or {}), } ) return context def logout_then_login(request, login_url=None): """ Log out the user if they are logged in. Then redirect to the login page. """ login_url = resolve_url(login_url or settings.LOGIN_URL) return LogoutView.as_view(next_page=login_url)(request) def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Redirect the user to the login page, passing the given 'next' page. """ resolved_url = resolve_url(login_url or settings.LOGIN_URL) login_url_parts = list(urlparse(resolved_url)) if redirect_field_name: querystring = QueryDict(login_url_parts[4], mutable=True) querystring[redirect_field_name] = next login_url_parts[4] = querystring.urlencode(safe="/") return HttpResponseRedirect(urlunparse(login_url_parts)) # Class-based password reset views # - PasswordResetView sends the mail # - PasswordResetDoneView shows a success message for the above # - PasswordResetConfirmView checks the link the user clicked and # prompts for a new password # - PasswordResetCompleteView shows a success message for the above class PasswordContextMixin: extra_context = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update( {"title": self.title, "subtitle": None, **(self.extra_context or {})} ) return context class PasswordResetView(PasswordContextMixin, FormView): email_template_name = "registration/password_reset_email.html" extra_email_context = None form_class = PasswordResetForm from_email = None html_email_template_name = None subject_template_name = "registration/password_reset_subject.txt" success_url = reverse_lazy("password_reset_done") template_name = "registration/password_reset_form.html" title = _("Password reset") token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { "use_https": self.request.is_secure(), "token_generator": self.token_generator, "from_email": self.from_email, "email_template_name": self.email_template_name, "subject_template_name": self.subject_template_name, "request": self.request, "html_email_template_name": self.html_email_template_name, "extra_email_context": self.extra_email_context, } form.save(**opts) return super().form_valid(form) INTERNAL_RESET_SESSION_TOKEN = "_password_reset_token" class PasswordResetDoneView(PasswordContextMixin, TemplateView): template_name = "registration/password_reset_done.html" title = _("Password reset sent") class PasswordResetConfirmView(PasswordContextMixin, FormView): form_class = SetPasswordForm post_reset_login = False post_reset_login_backend = None reset_url_token = "set-password" success_url = reverse_lazy("password_reset_complete") template_name = "registration/password_reset_confirm.html" title = _("Enter new password") token_generator = default_token_generator @method_decorator(sensitive_post_parameters()) @method_decorator(never_cache) def dispatch(self, *args, **kwargs): if "uidb64" not in kwargs or "token" not in kwargs: raise ImproperlyConfigured( "The URL path must contain 'uidb64' and 'token' parameters." ) self.validlink = False self.user = self.get_user(kwargs["uidb64"]) if self.user is not None: token = kwargs["token"] if token == self.reset_url_token: session_token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN) if self.token_generator.check_token(self.user, session_token): # If the token is valid, display the password reset form. self.validlink = True return super().dispatch(*args, **kwargs) else: if self.token_generator.check_token(self.user, token): # Store the token in the session and redirect to the # password reset form at a URL without the token. That # avoids the possibility of leaking the token in the # HTTP Referer header. self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token redirect_url = self.request.path.replace( token, self.reset_url_token ) return HttpResponseRedirect(redirect_url) # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) def get_user(self, uidb64): try: # urlsafe_base64_decode() decodes to bytestring uid = urlsafe_base64_decode(uidb64).decode() user = UserModel._default_manager.get(pk=uid) except ( TypeError, ValueError, OverflowError, UserModel.DoesNotExist, ValidationError, ): user = None return user def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["user"] = self.user return kwargs def form_valid(self, form): user = form.save() del self.request.session[INTERNAL_RESET_SESSION_TOKEN] if self.post_reset_login: auth_login(self.request, user, self.post_reset_login_backend) return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.validlink: context["validlink"] = True else: context.update( { "form": None, "title": _("Password reset unsuccessful"), "validlink": False, } ) return context class PasswordResetCompleteView(PasswordContextMixin, TemplateView): template_name = "registration/password_reset_complete.html" title = _("Password reset complete") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["login_url"] = resolve_url(settings.LOGIN_URL) return context class PasswordChangeView(PasswordContextMixin, FormView): form_class = PasswordChangeForm success_url = reverse_lazy("password_change_done") template_name = "registration/password_change_form.html" title = _("Password change") @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["user"] = self.request.user return kwargs def form_valid(self, form): form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(self.request, form.user) return super().form_valid(form) class PasswordChangeDoneView(PasswordContextMixin, TemplateView): template_name = "registration/password_change_done.html" title = _("Password change successful") @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) password_validation.py 0000644 00000022240 15030037112 0011162 0 ustar 00 import functools import gzip import re from difflib import SequenceMatcher from pathlib import Path from django.conf import settings from django.core.exceptions import ( FieldDoesNotExist, ImproperlyConfigured, ValidationError, ) from django.utils.functional import cached_property, lazy from django.utils.html import format_html, format_html_join from django.utils.module_loading import import_string from django.utils.translation import gettext as _ from django.utils.translation import ngettext @functools.lru_cache(maxsize=None) def get_default_password_validators(): return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) def get_password_validators(validator_config): validators = [] for validator in validator_config: try: klass = import_string(validator["NAME"]) except ImportError: msg = ( "The module in NAME could not be imported: %s. Check your " "AUTH_PASSWORD_VALIDATORS setting." ) raise ImproperlyConfigured(msg % validator["NAME"]) validators.append(klass(**validator.get("OPTIONS", {}))) return validators def validate_password(password, user=None, password_validators=None): """ Validate that the password meets all validator requirements. If the password is valid, return ``None``. If the password is invalid, raise ValidationError with all error messages. """ errors = [] if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: try: validator.validate(password, user) except ValidationError as error: errors.append(error) if errors: raise ValidationError(errors) def password_changed(password, user=None, password_validators=None): """ Inform all validators that have implemented a password_changed() method that the password has been changed. """ if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: password_changed = getattr(validator, "password_changed", lambda *a: None) password_changed(password, user) def password_validators_help_texts(password_validators=None): """ Return a list of all help texts of all configured validators. """ help_texts = [] if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: help_texts.append(validator.get_help_text()) return help_texts def _password_validators_help_text_html(password_validators=None): """ Return an HTML string with all help texts of all configured validators in an <ul>. """ help_texts = password_validators_help_texts(password_validators) help_items = format_html_join( "", "<li>{}</li>", ((help_text,) for help_text in help_texts) ) return format_html("<ul>{}</ul>", help_items) if help_items else "" password_validators_help_text_html = lazy(_password_validators_help_text_html, str) class MinimumLengthValidator: """ Validate that the password is of a minimum length. """ def __init__(self, min_length=8): self.min_length = min_length def validate(self, password, user=None): if len(password) < self.min_length: raise ValidationError( ngettext( "This password is too short. It must contain at least " "%(min_length)d character.", "This password is too short. It must contain at least " "%(min_length)d characters.", self.min_length, ), code="password_too_short", params={"min_length": self.min_length}, ) def get_help_text(self): return ngettext( "Your password must contain at least %(min_length)d character.", "Your password must contain at least %(min_length)d characters.", self.min_length, ) % {"min_length": self.min_length} def exceeds_maximum_length_ratio(password, max_similarity, value): """ Test that value is within a reasonable range of password. The following ratio calculations are based on testing SequenceMatcher like this: for i in range(0,6): print(10**i, SequenceMatcher(a='A', b='A'*(10**i)).quick_ratio()) which yields: 1 1.0 10 0.18181818181818182 100 0.019801980198019802 1000 0.001998001998001998 10000 0.00019998000199980003 100000 1.999980000199998e-05 This means a length_ratio of 10 should never yield a similarity higher than 0.2, for 100 this is down to 0.02 and for 1000 it is 0.002. This can be calculated via 2 / length_ratio. As a result we avoid the potentially expensive sequence matching. """ pwd_len = len(password) length_bound_similarity = max_similarity / 2 * pwd_len value_len = len(value) return pwd_len >= 10 * value_len and value_len < length_bound_similarity class UserAttributeSimilarityValidator: """ Validate that the password is sufficiently different from the user's attributes. If no specific attributes are provided, look at a sensible list of defaults. Attributes that don't exist are ignored. Comparison is made to not only the full attribute value, but also its components, so that, for example, a password is validated against either part of an email address, as well as the full address. """ DEFAULT_USER_ATTRIBUTES = ("username", "first_name", "last_name", "email") def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes if max_similarity < 0.1: raise ValueError("max_similarity must be at least 0.1") self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return password = password.lower() for attribute_name in self.user_attributes: value = getattr(user, attribute_name, None) if not value or not isinstance(value, str): continue value_lower = value.lower() value_parts = re.split(r"\W+", value_lower) + [value_lower] for value_part in value_parts: if exceeds_maximum_length_ratio( password, self.max_similarity, value_part ): continue if ( SequenceMatcher(a=password, b=value_part).quick_ratio() >= self.max_similarity ): try: verbose_name = str( user._meta.get_field(attribute_name).verbose_name ) except FieldDoesNotExist: verbose_name = attribute_name raise ValidationError( _("The password is too similar to the %(verbose_name)s."), code="password_too_similar", params={"verbose_name": verbose_name}, ) def get_help_text(self): return _( "Your password can’t be too similar to your other personal information." ) class CommonPasswordValidator: """ Validate that the password is not a common password. The password is rejected if it occurs in a provided list of passwords, which may be gzipped. The list Django ships with contains 20000 common passwords (lowercased and deduplicated), created by Royce Williams: https://gist.github.com/roycewilliams/226886fd01572964e1431ac8afc999ce The password list must be lowercased to match the comparison in validate(). """ @cached_property def DEFAULT_PASSWORD_LIST_PATH(self): return Path(__file__).resolve().parent / "common-passwords.txt.gz" def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH): if password_list_path is CommonPasswordValidator.DEFAULT_PASSWORD_LIST_PATH: password_list_path = self.DEFAULT_PASSWORD_LIST_PATH try: with gzip.open(password_list_path, "rt", encoding="utf-8") as f: self.passwords = {x.strip() for x in f} except OSError: with open(password_list_path) as f: self.passwords = {x.strip() for x in f} def validate(self, password, user=None): if password.lower().strip() in self.passwords: raise ValidationError( _("This password is too common."), code="password_too_common", ) def get_help_text(self): return _("Your password can’t be a commonly used password.") class NumericPasswordValidator: """ Validate that the password is not entirely numeric. """ def validate(self, password, user=None): if password.isdigit(): raise ValidationError( _("This password is entirely numeric."), code="password_entirely_numeric", ) def get_help_text(self): return _("Your password can’t be entirely numeric.") decorators.py 0000644 00000005525 15030037112 0007262 0 ustar 00 from functools import wraps from urllib.parse import urlparse from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import PermissionDenied from django.shortcuts import resolve_url def user_passes_test( test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME ): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def _wrapper_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if (not login_scheme or login_scheme == current_scheme) and ( not login_netloc or login_netloc == current_netloc ): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login(path, resolved_login_url, redirect_field_name) return _wrapper_view return decorator def login_required( function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None ): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name, ) if function: return actual_decorator(function) return actual_decorator def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ def check_perms(user): if isinstance(perm, str): perms = (perm,) else: perms = perm # First check if the user has the permission (even anon users) if user.has_perms(perms): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url) __pycache__/decorators.cpython-310.pyc 0000644 00000005306 15030037112 0013616 0 ustar 00 o �hU � @ st d dl mZ d dlmZ d dlmZ d dlmZ d dlm Z d dl mZ defdd �Zdedfd d�Z dd d�ZdS )� ��wraps)�urlparse)�settings)�REDIRECT_FIELD_NAME)�PermissionDenied)�resolve_urlNc s � ��fdd�}|S )z� Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. c s t � ����� fdd��}|S )Nc s� �| j �r�| g|�R i |��S | �� }t� ptj�}t|�d d� \}}t|�d d� \}}|r5||kr?|r;||kr?| �� }ddlm} | ||��S )N� r )�redirect_to_login) �user�build_absolute_urir r � LOGIN_URLr � get_full_path�django.contrib.auth.viewsr ) �request�args�kwargs�path�resolved_login_url�login_scheme�login_netloc�current_scheme�current_netlocr )� login_url�redirect_field_name� test_func� view_func� �T/usr/local/CyberPanel/lib/python3.10/site-packages/django/contrib/auth/decorators.py� _wrapper_view s �z:user_passes_test.<locals>.decorator.<locals>._wrapper_viewr )r r �r r r )r r � decorator s z#user_passes_test.<locals>.decoratorr )r r r r! r r r �user_passes_test s r"