コード例 #1
0
    def get_user(self, user_id):
        try:
            # Fetch user.
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            user = None
        else:
            # Does the user have a current session?
            if user.vac_cookie is None or user.last_validation is None:
                user = None

            # Is a revalidation needed?
            elif user.last_validation < (
                    timezone.now() -
                    datetime.timedelta(seconds=REVALIDATION_FREQUENCY)):
                # Check session against the VAC.
                try:
                    vac = VAC(user.vac_cookie)
                    if vac.validate_session():
                        # Update VAC cookie info.
                        user.last_validation = timezone.now()
                        user.save()
                    else:
                        # Session is no longer valid.
                        user.vac_cookie = None
                        user.save()
                        user = None

                # Problems revalidating. VAC unavailable? Log out user.
                except VAC.Exception as e:
                    user = None
                    logging.getLogger('vac-templater').exception(e)

        # Done!
        return user
コード例 #2
0
    def authenticate(self, username=None, password=None):
        # Authenticate against the VAC.
        vac = VAC()
        if vac.login(username, password):
            # Recover or build user instance.
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User(username=username)

            # Update VAC cookie info.
            user.vac_cookie = vac.cookie
            user.last_validation = timezone.now()
            user.save()

            # Done!
            return user
        return None
コード例 #3
0
    def irun(self, username, group_id, vcl_commit_id, vcl_content, changes):
        deployment = None
        error = None

        try:
            try:
                user = User.objects.get(pk=username)
            except User.DoesNotExist:
                error = _('Error retrieving the current user. Reconnect and '
                          'try again.')
            else:
                if user.vac_cookie:
                    try:
                        vac = VAC(user.vac_cookie)
                        group = vac.group(group_id)
                        if group:
                            vcl = vac.vcl(group.active_vcl)
                            if vcl:
                                vcl_commit = vac.vcl_head(vcl.id)
                                if vcl_commit:
                                    if vcl_commit.id == vcl_commit_id:
                                        # Push VCL.
                                        result = vac.vcl_push(
                                            vcl.id, vcl_content, group.id,
                                            vcl_commit_id)

                                        if result['success']:
                                            # Keep track of this deployment.
                                            deployment = Deployment(
                                                user=user,
                                                group_name=group.name,
                                                group_oid=group.id,
                                                branch_name=vcl.name,
                                                branch_oid=vcl.id,
                                                old_head_oid=vcl_commit.id,
                                                new_head_oid=result['vcl'].id,
                                                vcl=result['vcl'].content,
                                                message=result['message'],
                                                changes=changes)
                                            deployment.save()

                                            # Notify by e-mail.
                                            send_templated_mail(
                                                template_name=
                                                'emails/vcl/deploy.email',
                                                from_email=settings.
                                                DEFAULT_FROM_EMAIL,
                                                to=[
                                                    admin[1] for admin in
                                                    settings.ADMINS
                                                ],
                                                bcc=settings.
                                                DEFAULT_BCC_EMAILS,
                                                context={
                                                    'base_url':
                                                    settings.BASE_URL,
                                                    'deployment': deployment,
                                                },
                                            )
                                        else:
                                            error = result['message']
                                    else:
                                        error = _(
                                            'The VCL has been modified while '
                                            'you were updating it! Please, '
                                            'redo all required changes and '
                                            'try again.')
                                else:
                                    error = _(
                                        'The VCL has been undeployed from '
                                        'this group while you were updating '
                                        'it! No changes have been made.')
                            else:
                                error = _(
                                    'The VCL has been undeployed from this '
                                    'group while you were updating it! No '
                                    'changes have been made.')
                        else:
                            error = _('The selected group no longer exists.')

                    except VAC.AuthenticationException:
                        error = _('Your session in the VAC has been '
                                  'automatically expired. Reconnect and try'
                                  'again.')

                    except VAC.Exception as e:
                        logging.getLogger('vac-templater').exception(e)
                        error = _('Failed to connect to the VAC. Is it '
                                  'running? Do you have r/w access to it?')
                else:
                    error = _('You must be authenticated to the VAC. '
                              'Reconnect and try again.')

        except Exception as e:
            error = 'Exception: %s' % e

        return {
            'deployment_id': deployment.id if deployment else None,
            'error': error,
        }
コード例 #4
0
ファイル: vac.py プロジェクト: allenta/vac-templater
    def irun(self, username, group_id, vcl_commit_id, vcl_content, changes):
        deployment = None
        error = None

        try:
            try:
                user = User.objects.get(pk=username)
            except User.DoesNotExist:
                error = _("Error retrieving the current user. Reconnect and " "try again.")
            else:
                if user.vac_cookie:
                    try:
                        vac = VAC(user.vac_cookie)
                        group = vac.group(group_id)
                        if group:
                            vcl = vac.vcl(group.active_vcl)
                            if vcl:
                                vcl_commit = vac.vcl_head(vcl.id)
                                if vcl_commit:
                                    if vcl_commit.id == vcl_commit_id:
                                        # Push VCL.
                                        result = vac.vcl_push(vcl.id, vcl_content, group.id, vcl_commit_id)

                                        if result["success"]:
                                            # Keep track of this deployment.
                                            deployment = Deployment(
                                                user=user,
                                                group_name=group.name,
                                                group_oid=group.id,
                                                branch_name=vcl.name,
                                                branch_oid=vcl.id,
                                                old_head_oid=vcl_commit.id,
                                                new_head_oid=result["vcl"].id,
                                                vcl=result["vcl"].content,
                                                message=result["message"],
                                                changes=changes,
                                            )
                                            deployment.save()

                                            # Notify by e-mail.
                                            send_templated_mail(
                                                template_name="emails/vcl/deploy.email",
                                                from_email=settings.DEFAULT_FROM_EMAIL,
                                                to=[admin[1] for admin in settings.ADMINS],
                                                bcc=settings.DEFAULT_BCC_EMAILS,
                                                context={"base_url": settings.BASE_URL, "deployment": deployment},
                                            )
                                        else:
                                            error = result["message"]
                                    else:
                                        error = _(
                                            "The VCL has been modified while "
                                            "you were updating it! Please, "
                                            "redo all required changes and "
                                            "try again."
                                        )
                                else:
                                    error = _(
                                        "The VCL has been undeployed from "
                                        "this group while you were updating "
                                        "it! No changes have been made."
                                    )
                            else:
                                error = _(
                                    "The VCL has been undeployed from this "
                                    "group while you were updating it! No "
                                    "changes have been made."
                                )
                        else:
                            error = _("The selected group no longer exists.")

                    except VAC.AuthenticationException:
                        error = _(
                            "Your session in the VAC has been " "automatically expired. Reconnect and try" "again."
                        )

                    except VAC.Exception as e:
                        logging.getLogger("vac-templater").exception(e)
                        error = _("Failed to connect to the VAC. Is it " "running? Do you have r/w access to it?")
                else:
                    error = _("You must be authenticated to the VAC. " "Reconnect and try again.")

        except Exception as e:
            error = "Exception: %s" % e

        return {"deployment_id": deployment.id if deployment else None, "error": error}
コード例 #5
0
ファイル: vcl.py プロジェクト: allenta/vac-templater
    def _process(self, request):
        cache_group_form = None
        deploy_form = None

        try:
            vac = VAC(request.user.vac_cookie)

            # Cache group selected?
            cache_group_form = CacheGroupForm(
                vac, prefix='cache-group', data=request.POST or None)
            if cache_group_form.is_bound and cache_group_form.is_valid():
                # Deploying?
                deploying = (request.POST.get('op') == 'deploy')
                deploy_form = DeployForm(
                    vac,
                    cache_group_form.cleaned_data['group'],
                    request.user,
                    prefix='settings',
                    data=request.POST if deploying else None)
                if deploy_form.is_bound:
                    if deploy_form.is_valid():
                        if deploy_form.changes:
                            deploy_form.execute()
                            token = tasks.enqueue(
                                request,
                                PushVCLTask,
                                request.user.username,
                                deploy_form.group.id,
                                deploy_form.vcl_commit.id,
                                deploy_form.new_vcl,
                                deploy_form.changes,
                                callback={
                                    'fn': (
                                        'vac_templater.views.vcl.Deploy',
                                        'callback',
                                    ),
                                    'context': {},
                                })

                            return HttpResponseAjax([
                                commands.show_progress(token),
                            ], request)
                        else:
                            messages.warning(
                                request,
                                _('No changes have been done to the settings. '
                                  'There is no new VCL to be deployed.'))
                    else:
                        if deploy_form.non_field_errors():
                            for error in deploy_form.non_field_errors():
                                messages.error(request, error)
                        else:
                            messages.error(
                                request,
                                _('There are some errors in the values you '
                                  'supplied. Please, fix them and try again.'))

        # Unauthenticated VAC request.
        except VAC.AuthenticationException:
            messages.error(request, _(
                'Your session has automatically expired. Please, log in '
                'again.'))

            # Clear VAC cookie info.
            request.user.vac_cookie = None
            request.user.save()

            # Logout locally.
            auth.logout(request)
            return HttpResponseRedirect(reverse('home'))

        # Failed VAC request.
        except VAC.Exception as e:
            logging.getLogger('vac-templater').exception(e)
            messages.error(request, _(
                'Failed to connect to the VAC. Is it running? Do you have r/w '
                'access to it?'))

        return {
            'template': 'vac-templater/vcl/deploy.html',
            'context': {
                'cache_group_form': cache_group_form,
                'deploy_form': deploy_form,
            },
        }