Пример #1
0
    def post(self, request):
        if not isinstance(request.data, dict):
            return Response({"error": _("Invalid subscription data")}, status=status.HTTP_400_BAD_REQUEST)
        if "eula_accepted" not in request.data:
            return Response({"error": _("Missing 'eula_accepted' property")}, status=status.HTTP_400_BAD_REQUEST)
        try:
            eula_accepted = to_python_boolean(request.data["eula_accepted"])
        except ValueError:
            return Response({"error": _("'eula_accepted' value is invalid")}, status=status.HTTP_400_BAD_REQUEST)

        if not eula_accepted:
            return Response({"error": _("'eula_accepted' must be True")}, status=status.HTTP_400_BAD_REQUEST)
        request.data.pop("eula_accepted")
        try:
            data_actual = json.dumps(request.data)
        except Exception:
            logger.info(smart_text(u"Invalid JSON submitted for license."), extra=dict(actor=request.user.username))
            return Response({"error": _("Invalid JSON")}, status=status.HTTP_400_BAD_REQUEST)

        from awx.main.utils.common import get_licenser

        license_data = json.loads(data_actual)
        if 'license_key' in license_data:
            return Response({"error": _('Legacy license submitted. A subscription manifest is now required.')}, status=status.HTTP_400_BAD_REQUEST)
        if 'manifest' in license_data:
            try:
                json_actual = json.loads(base64.b64decode(license_data['manifest']))
                if 'license_key' in json_actual:
                    return Response({"error": _('Legacy license submitted. A subscription manifest is now required.')}, status=status.HTTP_400_BAD_REQUEST)
            except Exception:
                pass
            try:
                license_data = validate_entitlement_manifest(license_data['manifest'])
            except ValueError as e:
                return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
            except Exception:
                logger.exception('Invalid manifest submitted. {}')
                return Response({"error": _('Invalid manifest submitted.')}, status=status.HTTP_400_BAD_REQUEST)

            try:
                license_data_validated = get_licenser().license_from_manifest(license_data)
            except Exception:
                logger.warning(smart_text(u"Invalid subscription submitted."), extra=dict(actor=request.user.username))
                return Response({"error": _("Invalid License")}, status=status.HTTP_400_BAD_REQUEST)
        else:
            license_data_validated = get_licenser().validate()

        # If the license is valid, write it to the database.
        if license_data_validated['valid_key']:
            if not settings_registry.is_setting_read_only('TOWER_URL_BASE'):
                settings.TOWER_URL_BASE = "{}://{}".format(request.scheme, request.get_host())
            return Response(license_data_validated)

        logger.warning(smart_text(u"Invalid subscription submitted."), extra=dict(actor=request.user.username))
        return Response({"error": _("Invalid subscription")}, status=status.HTTP_400_BAD_REQUEST)
Пример #2
0
    def post(self, request):
        from awx.main.utils.common import get_licenser
        data = request.data.copy()
        if data.get('rh_password') == '$encrypted$':
            data['rh_password'] = settings.REDHAT_PASSWORD
        try:
            user, pw = data.get('rh_username'), data.get('rh_password')
            with set_environ(**settings.AWX_TASK_ENV):
                validated = get_licenser().validate_rh(user, pw)
            if user:
                settings.REDHAT_USERNAME = data['rh_username']
            if pw:
                settings.REDHAT_PASSWORD = data['rh_password']
        except Exception as exc:
            msg = _("Invalid License")
            if (isinstance(exc, requests.exceptions.HTTPError)
                    and getattr(getattr(exc, 'response', None), 'status_code',
                                None) == 401):
                msg = _("The provided credentials are invalid (HTTP 401).")
            elif isinstance(exc, requests.exceptions.ProxyError):
                msg = _("Unable to connect to proxy server.")
            elif isinstance(exc, requests.exceptions.ConnectionError):
                msg = _("Could not connect to subscription service.")
            elif isinstance(exc, (ValueError, OSError)) and exc.args:
                msg = exc.args[0]
            else:
                logger.exception(smart_text(u"Invalid license submitted."),
                                 extra=dict(actor=request.user.username))
            return Response({"error": msg}, status=status.HTTP_400_BAD_REQUEST)

        return Response(validated)
Пример #3
0
    def post(self, request):
        data = request.data.copy()
        pool_id = data.get('pool_id', None)
        if not pool_id:
            return Response({"error": _("No subscription pool ID provided.")}, status=status.HTTP_400_BAD_REQUEST)
        user = getattr(settings, 'SUBSCRIPTIONS_USERNAME', None)
        pw = getattr(settings, 'SUBSCRIPTIONS_PASSWORD', None)
        if pool_id and user and pw:
            from awx.main.utils.common import get_licenser

            data = request.data.copy()
            try:
                with set_environ(**settings.AWX_TASK_ENV):
                    validated = get_licenser().validate_rh(user, pw)
            except Exception as exc:
                msg = _("Invalid Subscription")
                if isinstance(exc, requests.exceptions.HTTPError) and getattr(getattr(exc, 'response', None), 'status_code', None) == 401:
                    msg = _("The provided credentials are invalid (HTTP 401).")
                elif isinstance(exc, requests.exceptions.ProxyError):
                    msg = _("Unable to connect to proxy server.")
                elif isinstance(exc, requests.exceptions.ConnectionError):
                    msg = _("Could not connect to subscription service.")
                elif isinstance(exc, (ValueError, OSError)) and exc.args:
                    msg = exc.args[0]
                else:
                    logger.exception(smart_text(u"Invalid subscription submitted."), extra=dict(actor=request.user.username))
                return Response({"error": msg}, status=status.HTTP_400_BAD_REQUEST)
        for sub in validated:
            if sub['pool_id'] == pool_id:
                sub['valid_key'] = True
                settings.LICENSE = sub
                return Response(sub)

        return Response({"error": _("Error processing subscription metadata.")}, status=status.HTTP_400_BAD_REQUEST)
Пример #4
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     product_name = get_licenser().validate()['product_name']
     context['title'] = _('%s Upgrading' % product_name)
     context['image_alt'] = _('Logo')
     context['aria_spinner'] = _('Loading')
     context['message_upgrade'] = _('%s is currently upgrading.' % product_name)
     context['message_refresh'] = _('This page will refresh when complete.')
     return context
Пример #5
0
Файл: urls.py Проект: lp4775/awx
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     product_name = 'AWX' if isinstance(
         get_licenser(),
         OpenLicense) else 'Red Hat Ansible Automation Platform'
     context['title'] = _('%s Upgrading' % product_name)
     context['image_alt'] = _('Logo')
     context['aria_spinner'] = _('Loading')
     context['message_upgrade'] = _('%s is currently upgrading.' %
                                    product_name)
     context['message_refresh'] = _('This page will refresh when complete.')
     return context
Пример #6
0
    def get(self, request, format=None):
        '''Return various sitewide configuration settings'''

        from awx.main.utils.common import get_licenser

        license_data = get_licenser().validate()

        if not license_data.get('valid_key', False):
            license_data = {}

        pendo_state = settings.PENDO_TRACKING_STATE if settings.PENDO_TRACKING_STATE in (
            'off', 'anonymous', 'detailed') else 'off'

        data = dict(
            time_zone=settings.TIME_ZONE,
            license_info=license_data,
            version=get_awx_version(),
            eula=render_to_string("eula.md") if
            license_data.get('license_type', 'UNLICENSED') != 'open' else '',
            analytics_status=pendo_state,
            analytics_collectors=all_collectors(),
            become_methods=PRIVILEGE_ESCALATION_METHODS,
        )

        # If LDAP is enabled, user_ldap_fields will return a list of field
        # names that are managed by LDAP and should be read-only for users with
        # a non-empty ldap_dn attribute.
        if getattr(settings, 'AUTH_LDAP_SERVER_URI', None):
            user_ldap_fields = ['username', 'password']
            user_ldap_fields.extend(
                getattr(settings, 'AUTH_LDAP_USER_ATTR_MAP', {}).keys())
            user_ldap_fields.extend(
                getattr(settings, 'AUTH_LDAP_USER_FLAGS_BY_GROUP', {}).keys())
            data['user_ldap_fields'] = user_ldap_fields

        if (request.user.is_superuser or request.user.is_system_auditor
                or Organization.accessible_objects(request.user,
                                                   'admin_role').exists()
                or Organization.accessible_objects(request.user,
                                                   'auditor_role').exists()
                or Organization.accessible_objects(
                    request.user, 'project_admin_role').exists()):
            data.update(
                dict(
                    project_base_dir=settings.PROJECTS_ROOT,
                    project_local_paths=Project.get_local_path_choices(),
                    custom_virtualenvs=get_custom_venv_choices(),
                ))
        elif JobTemplate.accessible_objects(request.user,
                                            'admin_role').exists():
            data['custom_virtualenvs'] = get_custom_venv_choices()

        return Response(data)
Пример #7
0
    def post(self, request):
        if not isinstance(request.data, dict):
            return Response({"error": _("Invalid license data")},
                            status=status.HTTP_400_BAD_REQUEST)
        if "eula_accepted" not in request.data:
            return Response({"error": _("Missing 'eula_accepted' property")},
                            status=status.HTTP_400_BAD_REQUEST)
        try:
            eula_accepted = to_python_boolean(request.data["eula_accepted"])
        except ValueError:
            return Response({"error": _("'eula_accepted' value is invalid")},
                            status=status.HTTP_400_BAD_REQUEST)

        if not eula_accepted:
            return Response({"error": _("'eula_accepted' must be True")},
                            status=status.HTTP_400_BAD_REQUEST)
        request.data.pop("eula_accepted")
        try:
            data_actual = json.dumps(request.data)
        except Exception:
            logger.info(smart_text(u"Invalid JSON submitted for license."),
                        extra=dict(actor=request.user.username))
            return Response({"error": _("Invalid JSON")},
                            status=status.HTTP_400_BAD_REQUEST)
        try:
            from awx.main.utils.common import get_licenser
            license_data = json.loads(data_actual)
            license_data_validated = get_licenser(**license_data).validate()
        except Exception:
            logger.warning(smart_text(u"Invalid license submitted."),
                           extra=dict(actor=request.user.username))
            return Response({"error": _("Invalid License")},
                            status=status.HTTP_400_BAD_REQUEST)

        # If the license is valid, write it to the database.
        if license_data_validated['valid_key']:
            settings.LICENSE = license_data
            if not settings_registry.is_setting_read_only('TOWER_URL_BASE'):
                settings.TOWER_URL_BASE = "{}://{}".format(
                    request.scheme, request.get_host())
            return Response(license_data_validated)

        logger.warning(smart_text(u"Invalid license submitted."),
                       extra=dict(actor=request.user.username))
        return Response({"error": _("Invalid license")},
                        status=status.HTTP_400_BAD_REQUEST)
Пример #8
0
def _get_validated_license_data():
    return get_licenser().validate()
Пример #9
0
def _get_validated_license_data():
    from awx.main.utils.common import get_licenser
    return get_licenser().validate()