<commit_before>"""
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""
import sys
import os
import logging
from datetime import timedelta
from django.urls import reverse
from urllib.parse import quote, unquote_plus
from minio import Minio
from gwells.settings.base import get_env_variable

logger = logging.getLogger(__name__)

class MinioClient():
    """ Load a minio client to handle public and/or private file requests

    Requires environment variables:
        S3_HOST: hostname for public document storage
        S3_ROOT_BUCKET: public Wells document storage bucket
        S3_AQUIFER_BUCKET: public Aquifers document storage buck
        MINIO_ACCESS_KEY: private storage account
        MINIO_SECRET_KEY: private storage secret
        S3_PRIVATE_HOST: private storage host (must be specified even if same as public storage)
        S3_PRIVATE_BUCKET: private storage bucket

    The optional "request" param can be set to the request that requires the minio client.
    This allows generation of full URIs including domain name.
    This is only required for generating private, local links.

    e.g.:
    def get(self, request, **kwargs):
        client = MinioClient(request)

    """

    def __init__(self, request=None, disable_public=False, disable_private=False):
        self.request = request

        if not disable_public:
            self.public_host = get_env_variable('S3_HOST', strict=True)
            self.public_bucket = get_env_variable(
                'S3_ROOT_BUCKET', strict=True)
            self.public_aquifers_bucket = get_env_variable('S3_AQUIFER_BUCKET', default_value="aquifer-docs")
            self.public_drillers_bucket = get_env_variable('S3_REGISTRANT_BUCKET', default_value="driller-docs")
            self.public_access_key = get_env_variable(
                'S3_PUBLIC_ACCESS_KEY', warn=False)
            self.public_secret_key = get_env_variable(
                'S3_PUBLIC_SECRET_KEY', warn=False)
            self.use_secure = int(get_env_variable(
                'S3_USE_SECURE', 1, warn=False))

            self.public_client = Minio(
                self.public_host,
                access_key=self.public_access_key,
                secret_key=self.public_secret_key,
                secure=self.use_secure
            )

        if not disable_private:
            self.private_client = self.create_private_client()

        self.disable_private = disable_private

    def create_private_client(self):
        self.private_access_key = get_env_variable('MINIO_ACCESS_KEY')
        self.private_secret_key = get_env_variable('MINIO_SECRET_KEY')
        self.private_host = get_env_variable('S3_PRIVATE_HOST')
        self.private_bucket = get_env_variable('S3_PRIVATE_BUCKET')
        self.private_aquifers_bucket = get_env_variable('S3_PRIVATE_AQUIFER_BUCKET', default_value="aquifer-docs")
        self.private_drillers_bucket = get_env_variable('S3_PRIVATE_REGISTRANT_BUCKET', default_value="driller-docs")

        return Minio(
            self.private_host,
            access_key=self.private_access_key,
            secret_key=self.private_secret_key,
            secure=self.use_secure
        )

    def get_private_file(self, object_name: str, bucket_name):
        """ Generates a link to a private document with name "object_name" (name includes prefixes) """
        return self.private_client.presigned_get_object(
            bucket_name,
            unquote_plus(object_name),
            expires=timedelta(minutes=12))

    def create_url(self, obj, host, bucket_name, private=False):
        """Generate a URL for a file/document

        obj: the file object returned by Minio.list_objects()
        host: the host where the file was found
        tag: well tag number
        private: private file permissions are handled by externally. when private=True,
            an external link will be generated.
        """

        if private:
            return self.get_private_file(obj.object_name, bucket_name)

        return 'https://{}/{}/{}'.format(
            host,
            quote(obj.bucket_name),
            quote(unquote_plus(obj.object_name))
        )

    def create_url_list(self, objects, host, bucket_name, private=False):
        """Generate a list of documents with name and url"""
        urls = list(
            map(
                lambda document: {
                    'url': self.create_url(document, host, bucket_name, private),

                    # split on last occurrence of '/' and return last item (supports any or no prefixes)
                    'name': unquote_plus(document.object_name).rsplit('/', 1)[-1]
                }, objects)
        )
        return urls

    def get_bucket_folder(self, document_id, resource='well'):
        """Helper function to determine the folder for a given resource"""
        if resource == 'well':
            folder = str(str('{:0<6}'.format('{:0>2}'.format(document_id // 10000))))
        elif resource == 'aquifer':
            folder = str(str('{:0<5}'.format('{:0>3}'.format(document_id // 100))))
        elif resource == 'driller':
            folder = ""
        else:
            folder = ""

        return folder

    def get_prefix(self, document_id, resource='well'):
        """Helper function to determine the prefix for a given resource"""
        folder = self.get_bucket_folder(document_id, resource)

        if resource == 'well':
            prefix = str(folder + '/WTN ' + str(document_id) + '_')
        elif resource == 'aquifer':
            prefix = str(folder + '/AQ_' + str('{:0<5}'.format('{:0>5}'.format(document_id))) + '_')
        elif resource == 'driller':
            prefix = "P_%s" % str(document_id)
        else:
            prefix = ""

        return prefix

    def format_object_name(self, object_name: str, document_id: int, resource='well'):
        """Wrapper function for getting an object name, with path and prefix, for an object and resource type"""
        return self.get_prefix(document_id, resource) + object_name

    def get_documents(self, document_id: int, resource='well', include_private=False):
        """Retrieves a list of available documents for a well or aquifer"""

        # prefix well tag numbers with a 6 digit "folder" id
        # e.g. WTA 23456 goes into prefix 020000/
        prefix = self.get_prefix(document_id, resource)

        if resource == 'well':
            public_bucket = self.public_bucket
        elif resource == 'aquifer':
            public_bucket = self.public_aquifers_bucket
        elif resource == 'driller':
            public_bucket = self.public_drillers_bucket

        objects = {}

        # provide all requests with a "public" collection of documents
        if self.public_client:
            pub_objects = []
            try:
                pub_objects = self.create_url_list(
                    self.public_client.list_objects(
                        public_bucket, prefix=prefix, recursive=True),
                    self.public_host, public_bucket)
            except Exception:
                logger.error(
                    "Could not retrieve files from public file server", exc_info=True)

            objects['public'] = pub_objects

        # authenticated requests also receive a "private" collection
        if include_private and not self.disable_private:
            if resource == 'well':
                private_bucket = self.private_bucket
            elif resource == 'aquifer':
                private_bucket = self.private_aquifers_bucket
            elif resource == 'driller':
                private_bucket = self.private_drillers_bucket

            priv_objects = []
            try:
                priv_objects = self.create_url_list(
                    self.private_client.list_objects(
                        private_bucket, prefix=prefix, recursive=True),
                    self.private_host, private_bucket, private=True)
            except:
                logger.error(
                    "Could not retrieve files from private file server", exc_info=sys.exc_info())

            objects['private'] = priv_objects

        return objects

    def get_presigned_put_url(self, object_name, bucket_name=None, private=False):
        """Retrieves the a presigned URL for putting objects into an S3 source"""
        if private:
            if bucket_name is None:
                bucket_name = self.private_bucket

            key = self.private_client.presigned_put_object(
                bucket_name, object_name, expires=timedelta(minutes=5))
        else:
            if bucket_name is None:
                bucket_name = self.public_bucket

            key = self.public_client.presigned_put_object(
                bucket_name, object_name, expires=timedelta(minutes=5))

        return key

    def delete_document(self, object_name, bucket_name=None, private=False):
        if private:
            if bucket_name is None:
                bucket_name = self.private_bucket

            self.private_client.remove_object(bucket_name, object_name)
        else:
            if bucket_name is None:
                bucket_name = self.public_bucket

            self.public_client.remove_object(bucket_name, object_name)
<commit_msg>Resolving error from sonar Cloud code scan (#1886)<commit_after>"""
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""
import sys
import os
import logging
from datetime import timedelta
from django.urls import reverse
from urllib.parse import quote, unquote_plus
from minio import Minio
from gwells.settings.base import get_env_variable

logger = logging.getLogger(__name__)

class MinioClient():
    """ Load a minio client to handle public and/or private file requests

    Requires environment variables:
        S3_HOST: hostname for public document storage
        S3_ROOT_BUCKET: public Wells document storage bucket
        S3_AQUIFER_BUCKET: public Aquifers document storage buck
        MINIO_ACCESS_KEY: private storage account
        MINIO_SECRET_KEY: private storage secret
        S3_PRIVATE_HOST: private storage host (must be specified even if same as public storage)
        S3_PRIVATE_BUCKET: private storage bucket

    The optional "request" param can be set to the request that requires the minio client.
    This allows generation of full URIs including domain name.
    This is only required for generating private, local links.

    e.g.:
    def get(self, request, **kwargs):
        client = MinioClient(request)

    """

    def __init__(self, request=None, disable_public=False, disable_private=False):
        self.request = request

        if not disable_public:
            self.public_host = get_env_variable('S3_HOST', strict=True)
            self.public_bucket = get_env_variable(
                'S3_ROOT_BUCKET', strict=True)
            self.public_aquifers_bucket = get_env_variable('S3_AQUIFER_BUCKET', default_value="aquifer-docs")
            self.public_drillers_bucket = get_env_variable('S3_REGISTRANT_BUCKET', default_value="driller-docs")
            self.public_access_key = get_env_variable(
                'S3_PUBLIC_ACCESS_KEY', warn=False)
            self.public_secret_key = get_env_variable(
                'S3_PUBLIC_SECRET_KEY', warn=False)
            self.use_secure = int(get_env_variable(
                'S3_USE_SECURE', 1, warn=False))

            self.public_client = Minio(
                self.public_host,
                access_key=self.public_access_key,
                secret_key=self.public_secret_key,
                secure=self.use_secure
            )

        if not disable_private:
            self.private_client = self.create_private_client()

        self.disable_private = disable_private

    def create_private_client(self):
        self.private_access_key = get_env_variable('MINIO_ACCESS_KEY')
        self.private_secret_key = get_env_variable('MINIO_SECRET_KEY')
        self.private_host = get_env_variable('S3_PRIVATE_HOST')
        self.private_bucket = get_env_variable('S3_PRIVATE_BUCKET')
        self.private_aquifers_bucket = get_env_variable('S3_PRIVATE_AQUIFER_BUCKET', default_value="aquifer-docs")
        self.private_drillers_bucket = get_env_variable('S3_PRIVATE_REGISTRANT_BUCKET', default_value="driller-docs")

        return Minio(
            self.private_host,
            access_key=self.private_access_key,
            secret_key=self.private_secret_key,
            secure=self.use_secure
        )

    def get_private_file(self, object_name: str, bucket_name):
        """ Generates a link to a private document with name "object_name" (name includes prefixes) """
        return self.private_client.presigned_get_object(
            bucket_name,
            unquote_plus(object_name),
            expires=timedelta(minutes=12))

    def create_url(self, obj, host, bucket_name, private=False):
        """Generate a URL for a file/document

        obj: the file object returned by Minio.list_objects()
        host: the host where the file was found
        tag: well tag number
        private: private file permissions are handled by externally. when private=True,
            an external link will be generated.
        """

        if private:
            return self.get_private_file(obj.object_name, bucket_name)

        return 'https://{}/{}/{}'.format(
            host,
            quote(obj.bucket_name),
            quote(unquote_plus(obj.object_name))
        )

    def create_url_list(self, objects, host, bucket_name, private=False):
        """Generate a list of documents with name and url"""
        urls = list(
            map(
                lambda document: {
                    'url': self.create_url(document, host, bucket_name, private),

                    # split on last occurrence of '/' and return last item (supports any or no prefixes)
                    'name': unquote_plus(document.object_name).rsplit('/', 1)[-1]
                }, objects)
        )
        return urls

    def get_bucket_folder(self, document_id, resource='well'):
        """Helper function to determine the folder for a given resource"""
        if resource == 'well':
            folder = str(str('{:0<6}'.format('{:0>2}'.format(document_id // 10000))))
        elif resource == 'aquifer':
            folder = str(str('{:0<5}'.format('{:0>3}'.format(document_id // 100))))
        elif resource == 'driller':
            folder = ""
        else:
            folder = ""

        return folder

    def get_prefix(self, document_id, resource='well'):
        """Helper function to determine the prefix for a given resource"""
        folder = self.get_bucket_folder(document_id, resource)

        if resource == 'well':
            prefix = str(folder + '/WTN ' + str(document_id) + '_')
        elif resource == 'aquifer':
            prefix = str(folder + '/AQ_' + str('{:0<5}'.format('{:0>5}'.format(document_id))) + '_')
        elif resource == 'driller':
            prefix = "P_%s" % str(document_id)
        else:
            prefix = ""

        return prefix

    def format_object_name(self, object_name: str, document_id: int, resource='well'):
        """Wrapper function for getting an object name, with path and prefix, for an object and resource type"""
        return self.get_prefix(document_id, resource) + object_name

    def get_documents(self, document_id: int, resource='well', include_private=False):
        """Retrieves a list of available documents for a well or aquifer"""

        # prefix well tag numbers with a 6 digit "folder" id
        # e.g. WTA 23456 goes into prefix 020000/
        prefix = self.get_prefix(document_id, resource)

        if resource == 'well':
            public_bucket = self.public_bucket
        elif resource == 'aquifer':
            public_bucket = self.public_aquifers_bucket
        elif resource == 'driller':
            public_bucket = self.public_drillers_bucket

        objects = {}

        # provide all requests with a "public" collection of documents
        if self.public_client:
            pub_objects = []
            try:
                pub_objects = self.create_url_list(
                    self.public_client.list_objects(
                        public_bucket, prefix=prefix, recursive=True),
                    self.public_host, public_bucket)
            except Exception as e:
                logger.error(
                    "Could not retrieve files from public file server", exc_info=e)

            objects['public'] = pub_objects

        # authenticated requests also receive a "private" collection
        if include_private and not self.disable_private:
            if resource == 'well':
                private_bucket = self.private_bucket
            elif resource == 'aquifer':
                private_bucket = self.private_aquifers_bucket
            elif resource == 'driller':
                private_bucket = self.private_drillers_bucket

            priv_objects = []
            try:
                priv_objects = self.create_url_list(
                    self.private_client.list_objects(
                        private_bucket, prefix=prefix, recursive=True),
                    self.private_host, private_bucket, private=True)
            except:
                logger.error(
                    "Could not retrieve files from private file server", exc_info=sys.exc_info())

            objects['private'] = priv_objects

        return objects

    def get_presigned_put_url(self, object_name, bucket_name=None, private=False):
        """Retrieves the a presigned URL for putting objects into an S3 source"""
        if private:
            if bucket_name is None:
                bucket_name = self.private_bucket

            key = self.private_client.presigned_put_object(
                bucket_name, object_name, expires=timedelta(minutes=5))
        else:
            if bucket_name is None:
                bucket_name = self.public_bucket

            key = self.public_client.presigned_put_object(
                bucket_name, object_name, expires=timedelta(minutes=5))

        return key

    def delete_document(self, object_name, bucket_name=None, private=False):
        if private:
            if bucket_name is None:
                bucket_name = self.private_bucket

            self.private_client.remove_object(bucket_name, object_name)
        else:
            if bucket_name is None:
                bucket_name = self.public_bucket

            self.public_client.remove_object(bucket_name, object_name)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import datetime
import requests
from django.contrib.auth import get_user_model
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import get_template
from django.template import Context
from django.contrib.auth.forms import (UserCreationForm, UserChangeForm,)
from allauth.account.forms import SignupForm

User = get_user_model()

from .models import School, City, Occupation, Discipline, EducationLevel

class MultipleChoiceFieldNoValidation(forms.MultipleChoiceField):
    def validate(self, value):
        pass

class ProfileEditForm(forms.ModelForm):
    disciplines = MultipleChoiceFieldNoValidation()
    education_levels = MultipleChoiceFieldNoValidation()

    class Meta:
        model = User
        fields = ('picture', 'first_name', 'occupations','city', 'site', 'biography', 'cpf', 'rg', 'phone')

    def clean_cpf(self):
        cpf = self.cleaned_data['cpf']
        cpf = cpf.replace('.', '')
        digits = cpf.split('-')
        soma = 0
        all_eq = True

        if len(cpf) == 0:
            return None

        for d in cpf.replace('-', ''):
            if d != cpf[0]:
                all_eq = False
                break

        if all_eq:
            raise forms.ValidationError(_("CPF invalido!"))

        for i in range(len(digits[0])):
            soma = soma + (10-i) * int(digits[0][i])

        res = (soma*10)%11

        if res %10 != int(digits[1][0]):
             raise forms.ValidationError(_("CPF invalido!"))

        soma = 0

        for i in range(len(digits[0])):
            soma = soma + (11-i) * int(digits[0][i])

        soma = soma + 2 * int(digits[1][0])

        res = (soma*10)%11

        if res  %10 != int(digits[1][1]):
             raise forms.ValidationError(_("CPF invalido!"))

        return self.cleaned_data['cpf']

    def clean_rg(self):
        rg = self.cleaned_data['rg']
        if len(rg) > 0 and len(rg) < 4:
            raise forms.ValidationError(_("Insira o RG corretamente!"))

        return self.cleaned_data['rg']

    def clean_phone(self):
        phone = self.cleaned_data['phone']
        if len(phone) > 0 and len(phone) < 14:
            raise forms.ValidationError(_("Insira o telefone corretamente!"))

        return self.cleaned_data['phone']

    def save(self, commit=True):
        disciplines = self.cleaned_data.get('disciplines')
        education_levels = self.cleaned_data.get('education_levels')
        profile = super(ProfileEditForm, self).save(commit=False)

        saved_disciplines = profile.disciplines.all()
        saving_disciplines = []
        for d in disciplines:
            if (not Discipline.objects.filter(name=d).exists()):
                new_d = Discipline.objects.create(name=d)
                new_d.save()
                saving_disciplines.append(new_d)
            else:
                saving_disciplines.append(Discipline.objects.get(name=d))
        to_save = [d for d in saving_disciplines if d not in saved_disciplines]
        for d in to_save:
            profile.disciplines.add(d)
        to_remove = [d for d in saved_disciplines if d not in saving_disciplines]
        for d in to_remove:
            profile.disciplines.remove(d)

        saved_education_levels = profile.education_levels.all()
        saving_education_levels = []
        for el in education_levels:
            saving_education_levels.append(EducationLevel.objects.get(slug=el))
        to_save = [el for el in saving_education_levels if el not in saved_education_levels]
        for el in to_save:
            profile.education_levels.add(el)
        to_remove = [el for el in saved_education_levels if el not in saving_education_levels]
        for el in to_remove:
            profile.education_levels.remove(el)

        self.save_m2m()
        profile.save()

class ProfilePasswordForm(forms.ModelForm):
    # email = forms.RegexField(max_length=75, regex=r"^[\w.@+-]+$")
    business_email = forms.RegexField(max_length=75, regex=r"^[\w.@+-]+$", required=False)
    password1 = forms.CharField(widget=forms.PasswordInput, required=False)
    password2 = forms.CharField(widget=forms.PasswordInput, required=False)

    class Meta:
        model = User
        fields = ('business_email',)

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(_("The two password fields didn't match."))
        return password2

    def save(self, commit=True):
        if self.cleaned_data['password1']:
            self.instance.set_password(self.cleaned_data['password1'])
        return super(ProfilePasswordForm, self).save(commit=commit)

class SchoolAddForm(forms.ModelForm):

    class Meta:
        model = School

class AcceptTermsForm(forms.Form):
    accept_terms = forms.BooleanField(label=_('Eu aceito os termos de uso'), initial=False, required=False)

    def __init__(self, *args, **kwargs):
        self.captcha = kwargs
        super(AcceptTermsForm, self).__init__(*args, **kwargs)

    def clean_accept_terms(self):
        captcha = self.captcha['data']
        data = self.cleaned_data['accept_terms']
        if settings.TERMS_ACCEPTANCE_REQUIRED and not data:
                raise forms.ValidationError(_('You must agree to the Terms of Use to use %(site_name)s.'),
                                            params={'site_name': settings.SITE_NAME},)

        #Check captcha
        if "g-recaptcha-response" in captcha:
            secret_key = settings.GOOGLE_RECAPTCHA_SECRET_KEY
            res = {'response': captcha["g-recaptcha-response"],'secret': secret_key}
            resp = requests.post('https://www.google.com/recaptcha/api/siteverify', data=res)
            result_json = resp.json()

            if not result_json.get('success') and not result_json.get('error-codes'):
                if result_json['score'] <= 0.6:
                    raise forms.ValidationError(_('Invalid reCAPTCHA. Please try again'))

        return self.cleaned_data['accept_terms']

class SignupForm(SignupForm, AcceptTermsForm):
    username = forms.CharField(initial=False,required=False)
    fullname = forms.CharField(label=_("Nome Completo"),initial=False,required=True)

    def extract_first_name(self,name):
        names = name.split(" ")
        return names[0]

    def extract_last_name(self, name):
        names = name.split(" ")
        if len(names) > 1:
            return " ".join(names[1:])
        else:
            return ""

    def clean_username(self):
        return self.data['email']

    def clean_fullname(self):
        data = self.cleaned_data['fullname']
        if not data.strip():
            raise forms.ValidationError(_('You Must fill your complete name'))
        return data

    def save(self, request):
        user = super(SignupForm, self).save(request)
        name = self.cleaned_data['fullname']
        user.accepted_terms = self.cleaned_data['accept_terms']
        user.first_name = name
        # user.first_name = self.extract_first_name(name)
        # user.last_name = self.extract_last_name(name)
        user.save()
        return user
        # send_mail('Novo Usuário Cadastrado', get_template('account/email/email_new_user_message.txt').render(Context(
            # {'date': now.strftime("%d/%m/%Y"), 'time': now.strftime("%H:%M"), 'username': username, 'email': email})), settings.EMAIL_SUPPORT, [settings.EMAIL_SUPPORT])

class NewUserCreationForm(UserCreationForm):
    username = forms.RegexField(label=_("Username"), max_length=75,
    regex=r'^[\w.@+-]+$',
    help_text=_("Required. 75 characters or fewer. Letters, digits and "
                    "@/./+/-/_ only."),
    error_messages={
        'invalid': _("This value may contain only letters, numbers and "
                        "@/./+/-/_ characters.")})

class NewUserChangeForm(UserChangeForm):
    username = forms.RegexField(label=_("Username"), max_length=75,
    regex=r'^[\w.@+-]+$',
    help_text=_("Required. 75 characters or fewer. Letters, digits and "
                    "@/./+/-/_ only."),
    error_messages={
        'invalid': _("This value may contain only letters, numbers and "
                        "@/./+/-/_ characters.")})<commit_msg>Update score<commit_after># -*- coding: utf-8 -*-
import datetime
import requests
from django.contrib.auth import get_user_model
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import get_template
from django.template import Context
from django.contrib.auth.forms import (UserCreationForm, UserChangeForm,)
from allauth.account.forms import SignupForm

User = get_user_model()

from .models import School, City, Occupation, Discipline, EducationLevel

class MultipleChoiceFieldNoValidation(forms.MultipleChoiceField):
    def validate(self, value):
        pass

class ProfileEditForm(forms.ModelForm):
    disciplines = MultipleChoiceFieldNoValidation()
    education_levels = MultipleChoiceFieldNoValidation()

    class Meta:
        model = User
        fields = ('picture', 'first_name', 'occupations','city', 'site', 'biography', 'cpf', 'rg', 'phone')

    def clean_cpf(self):
        cpf = self.cleaned_data['cpf']
        cpf = cpf.replace('.', '')
        digits = cpf.split('-')
        soma = 0
        all_eq = True

        if len(cpf) == 0:
            return None

        for d in cpf.replace('-', ''):
            if d != cpf[0]:
                all_eq = False
                break

        if all_eq:
            raise forms.ValidationError(_("CPF invalido!"))

        for i in range(len(digits[0])):
            soma = soma + (10-i) * int(digits[0][i])

        res = (soma*10)%11

        if res %10 != int(digits[1][0]):
             raise forms.ValidationError(_("CPF invalido!"))

        soma = 0

        for i in range(len(digits[0])):
            soma = soma + (11-i) * int(digits[0][i])

        soma = soma + 2 * int(digits[1][0])

        res = (soma*10)%11

        if res  %10 != int(digits[1][1]):
             raise forms.ValidationError(_("CPF invalido!"))

        return self.cleaned_data['cpf']

    def clean_rg(self):
        rg = self.cleaned_data['rg']
        if len(rg) > 0 and len(rg) < 4:
            raise forms.ValidationError(_("Insira o RG corretamente!"))

        return self.cleaned_data['rg']

    def clean_phone(self):
        phone = self.cleaned_data['phone']
        if len(phone) > 0 and len(phone) < 14:
            raise forms.ValidationError(_("Insira o telefone corretamente!"))

        return self.cleaned_data['phone']

    def save(self, commit=True):
        disciplines = self.cleaned_data.get('disciplines')
        education_levels = self.cleaned_data.get('education_levels')
        profile = super(ProfileEditForm, self).save(commit=False)

        saved_disciplines = profile.disciplines.all()
        saving_disciplines = []
        for d in disciplines:
            if (not Discipline.objects.filter(name=d).exists()):
                new_d = Discipline.objects.create(name=d)
                new_d.save()
                saving_disciplines.append(new_d)
            else:
                saving_disciplines.append(Discipline.objects.get(name=d))
        to_save = [d for d in saving_disciplines if d not in saved_disciplines]
        for d in to_save:
            profile.disciplines.add(d)
        to_remove = [d for d in saved_disciplines if d not in saving_disciplines]
        for d in to_remove:
            profile.disciplines.remove(d)

        saved_education_levels = profile.education_levels.all()
        saving_education_levels = []
        for el in education_levels:
            saving_education_levels.append(EducationLevel.objects.get(slug=el))
        to_save = [el for el in saving_education_levels if el not in saved_education_levels]
        for el in to_save:
            profile.education_levels.add(el)
        to_remove = [el for el in saved_education_levels if el not in saving_education_levels]
        for el in to_remove:
            profile.education_levels.remove(el)

        self.save_m2m()
        profile.save()

class ProfilePasswordForm(forms.ModelForm):
    # email = forms.RegexField(max_length=75, regex=r"^[\w.@+-]+$")
    business_email = forms.RegexField(max_length=75, regex=r"^[\w.@+-]+$", required=False)
    password1 = forms.CharField(widget=forms.PasswordInput, required=False)
    password2 = forms.CharField(widget=forms.PasswordInput, required=False)

    class Meta:
        model = User
        fields = ('business_email',)

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(_("The two password fields didn't match."))
        return password2

    def save(self, commit=True):
        if self.cleaned_data['password1']:
            self.instance.set_password(self.cleaned_data['password1'])
        return super(ProfilePasswordForm, self).save(commit=commit)

class SchoolAddForm(forms.ModelForm):

    class Meta:
        model = School

class AcceptTermsForm(forms.Form):
    accept_terms = forms.BooleanField(label=_('Eu aceito os termos de uso'), initial=False, required=False)

    def __init__(self, *args, **kwargs):
        self.captcha = kwargs
        super(AcceptTermsForm, self).__init__(*args, **kwargs)

    def clean_accept_terms(self):
        captcha = self.captcha['data']
        data = self.cleaned_data['accept_terms']
        if settings.TERMS_ACCEPTANCE_REQUIRED and not data:
                raise forms.ValidationError(_('You must agree to the Terms of Use to use %(site_name)s.'),
                                            params={'site_name': settings.SITE_NAME},)

        #Check captcha
        if "g-recaptcha-response" in captcha:
            secret_key = settings.GOOGLE_RECAPTCHA_SECRET_KEY
            res = {'response': captcha["g-recaptcha-response"],'secret': secret_key}
            resp = requests.post('https://www.google.com/recaptcha/api/siteverify', data=res)
            result_json = resp.json()

            if not result_json.get('success') and not result_json.get('error-codes'):
                if result_json['score'] <= 0.7:
                    raise forms.ValidationError(_('Invalid reCAPTCHA. Please try again'))

        return self.cleaned_data['accept_terms']

class SignupForm(SignupForm, AcceptTermsForm):
    username = forms.CharField(initial=False,required=False)
    fullname = forms.CharField(label=_("Nome Completo"),initial=False,required=True)

    def extract_first_name(self,name):
        names = name.split(" ")
        return names[0]

    def extract_last_name(self, name):
        names = name.split(" ")
        if len(names) > 1:
            return " ".join(names[1:])
        else:
            return ""

    def clean_username(self):
        return self.data['email']

    def clean_fullname(self):
        data = self.cleaned_data['fullname']
        if not data.strip():
            raise forms.ValidationError(_('You Must fill your complete name'))
        return data

    def save(self, request):
        user = super(SignupForm, self).save(request)
        name = self.cleaned_data['fullname']
        user.accepted_terms = self.cleaned_data['accept_terms']
        user.first_name = name
        # user.first_name = self.extract_first_name(name)
        # user.last_name = self.extract_last_name(name)
        user.save()
        return user
        # send_mail('Novo Usuário Cadastrado', get_template('account/email/email_new_user_message.txt').render(Context(
            # {'date': now.strftime("%d/%m/%Y"), 'time': now.strftime("%H:%M"), 'username': username, 'email': email})), settings.EMAIL_SUPPORT, [settings.EMAIL_SUPPORT])

class NewUserCreationForm(UserCreationForm):
    username = forms.RegexField(label=_("Username"), max_length=75,
    regex=r'^[\w.@+-]+$',
    help_text=_("Required. 75 characters or fewer. Letters, digits and "
                    "@/./+/-/_ only."),
    error_messages={
        'invalid': _("This value may contain only letters, numbers and "
                        "@/./+/-/_ characters.")})

class NewUserChangeForm(UserChangeForm):
    username = forms.RegexField(label=_("Username"), max_length=75,
    regex=r'^[\w.@+-]+$',
    help_text=_("Required. 75 characters or fewer. Letters, digits and "
                    "@/./+/-/_ only."),
    error_messages={
        'invalid': _("This value may contain only letters, numbers and "
                        "@/./+/-/_ characters.")})
<|endoftext|>


<commit_before>from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response

@login_required
def profile(request):
    context = {'user': request.user}
    return render_to_response('accounts/profile.xhtml', context)<commit_msg>Using RequestContext.<commit_after>from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext

@login_required
def profile(request):
    return render_to_response('accounts/profile.xhtml',
                              context_instance=RequestContext(request))<|endoftext|>


<commit_before># Copyright 2015 Cloudbase Solutions Srl
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from argus.backends.tempest import tempest_backend
from argus import exceptions
from argus import util

with util.restore_excepthook():
    from tempest.common import isolated_creds
    from tempest.common import waiters

SUBNET6_CIDR = "::ffff:a00:0/120"
DNSES6 = ["::ffff:808:808", "::ffff:808:404"]

class NetworkWindowsBackend(tempest_backend.BaseWindowsTempestBackend):
    """Backend for providing static network configuration.

    Creates an additional internal network which will be
    bound explicitly with the new created instance.
    """

    def _get_isolated_network(self):
        """Returns the network itself from the isolated network resources.

        This works only with the isolated credentials and
        this step is achieved by allowing/forcing tenant isolation.
        """
        # Extract the just created private network.
        return self._manager.primary_credentials().network

    def _get_networks(self):
        """Explicitly gather and return the private networks.

        All these networks will be attached to the newly created
        instance without letting nova to handle this part.
        """
        _networks = self._manager.networks_client.list_networks()["networks"]
        # Skip external/private networks.
        networks = [net["id"] for net in _networks
                    if not net["router:external"]]
        # Put in front the main private network.
        head = self._get_isolated_network()["id"]
        networks.remove(head)
        networks.insert(0, head)
        # Adapt the list to a format accepted by the API.
        return [{"uuid": net} for net in networks]

    def _create_private_network(self):
        """Create an extra private network to be attached.

        This network is the one with disabled DHCP and
        ready for static configuration by cb-init.
        """
        tenant_id = self._manager.primary_credentials().tenant_id
        # pylint: disable=protected-access
        net_resources = self._manager.isolated_creds._create_network_resources(
            tenant_id)

        # Store the network for later cleanup.
        key = "fake"
        fake_net_creds = util.get_namedtuple(
            "FakeCreds",
            ("network", "subnet", "router",
             "user_id", "tenant_id", "username", "tenant_name"),
            net_resources + (None,) * 4)
        self._manager.isolated_creds.isolated_creds[key] = fake_net_creds

        # Disable DHCP for this network to test static configuration and
        # also add default DNS name servers.
        subnet_id = fake_net_creds.subnet["id"]
        net_client = self._manager.network_client
        net_client.update_subnet(
            subnet_id, enable_dhcp=False,
            dns_nameservers=self._conf.argus.dns_nameservers)

        # Change the allocation pool to configure any IP,
        # other the one used already with dynamic settings.
        allocation_pools = net_client.show_subnet(subnet_id)["subnet"][
            "allocation_pools"]
        allocation_pools[0]["start"] = util.next_ip(
            allocation_pools[0]["start"], step=2)
        net_client.update_subnet(subnet_id, allocation_pools=allocation_pools)

        # Create and attach an IPv6 subnet for this network. Also, register
        # it for later cleanup.
        subnet6_name = util.rand_name(self.__class__.__name__) + "-subnet6"
        network_id = fake_net_creds.network["id"]
        net_client.create_subnet(
            network_id=network_id,
            cidr=SUBNET6_CIDR,
            name=subnet6_name,
            dns_nameservers=DNSES6,
            tenant_id=tenant_id,
            enable_dhcp=False,
            ip_version=6)

    def setup_instance(self):
        # Just like a normal preparer, but this time
        # with explicitly specified attached networks.

        if not isinstance(self._manager.isolated_creds,
                          isolated_creds.IsolatedCreds):
            raise exceptions.ArgusError(
                "Network resources are not available."
            )

        self._create_private_network()
        self._networks = self._get_networks()

        super(NetworkWindowsBackend, self).setup_instance()

    @staticmethod
    def _find_ip_address(port, subnet_id):
        for fixed_ip in port["fixed_ips"]:
            if fixed_ip["subnet_id"] == subnet_id:
                return fixed_ip["ip_address"]

    def get_network_interfaces(self):
        """Retrieve and parse network details from the compute node."""
        networks_client = self._manager.networks_client
        network_client = self._manager.network_client
        guest_nics = []
        for network in self._networks or []:
            network_id = network["uuid"]
            net_details = networks_client.show_network(network_id)["network"]
            nic = dict.fromkeys(util.NETWORK_KEYS)
            for subnet_id in net_details["subnets"]:
                details = network_client.show_subnet(subnet_id)["subnet"]

                # The network interface should follow the format found under
                # `windows.InstanceIntrospection.get_network_interfaces`
                # method or `argus.util.NETWORK_KEYS` model.
                v6switch = details["ip_version"] == 6
                v6suffix = "6" if v6switch else ""
                nic["dhcp"] = details["enable_dhcp"]
                nic["dns" + v6suffix] = details["dns_nameservers"]
                nic["gateway" + v6suffix] = details["gateway_ip"]
                nic["netmask" + v6suffix] = (
                    details["cidr"].split("/")[1] if v6switch
                    else util.cidr2netmask(details["cidr"]))

                # Find rest of the details under the ports using this subnet.
                # There should be no conflicts because on the current
                # architecture every instance is using its own router,
                # subnet and network accessible only to it.
                ports = network_client.list_ports()["ports"]
                for port in ports:
                    # Select instance related ports only, with the
                    # corresponding subnet ID.
                    if "compute" not in port["device_owner"]:
                        continue
                    ip_address = self._find_ip_address(port, subnet_id)
                    if not ip_address:
                        continue
                    nic["mac"] = port["mac_address"].upper()
                    nic["address" + v6suffix] = ip_address
                    break

            guest_nics.append(nic)
        return guest_nics

class RescueWindowsBackend(tempest_backend.BaseWindowsTempestBackend):
    """Instance rescue Windows-based backend."""

    def rescue_server(self):
        admin_pass = self._conf.openstack.image_password
        self._manager.servers_client.rescue_server(
            self.internal_instance_id(),
            adminPass=admin_pass)

        waiters.wait_for_server_status(
            self._manager.servers_client,
            self.internal_instance_id(), 'RESCUE')

    def unrescue_server(self):
        self._manager.servers_client.unrescue_server(
            self.internal_instance_id())
        waiters.wait_for_server_status(
            self._manager.servers_client,
            self.internal_instance_id(), 'ACTIVE')
<commit_msg>Use the new name for isolated_creds, including the new private _creds object, which is not public anymore, unfortunately.<commit_after># Copyright 2015 Cloudbase Solutions Srl
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from argus.backends.tempest import tempest_backend
from argus import exceptions
from argus import util

with util.restore_excepthook():
    from tempest.common import dynamic_creds
    from tempest.common import waiters

SUBNET6_CIDR = "::ffff:a00:0/120"
DNSES6 = ["::ffff:808:808", "::ffff:808:404"]

class NetworkWindowsBackend(tempest_backend.BaseWindowsTempestBackend):
    """Backend for providing static network configuration.

    Creates an additional internal network which will be
    bound explicitly with the new created instance.
    """

    def _get_isolated_network(self):
        """Returns the network itself from the isolated network resources.

        This works only with the isolated credentials and
        this step is achieved by allowing/forcing tenant isolation.
        """
        # Extract the just created private network.
        return self._manager.primary_credentials().network

    def _get_networks(self):
        """Explicitly gather and return the private networks.

        All these networks will be attached to the newly created
        instance without letting nova to handle this part.
        """
        _networks = self._manager.networks_client.list_networks()["networks"]
        # Skip external/private networks.
        networks = [net["id"] for net in _networks
                    if not net["router:external"]]
        # Put in front the main private network.
        head = self._get_isolated_network()["id"]
        networks.remove(head)
        networks.insert(0, head)
        # Adapt the list to a format accepted by the API.
        return [{"uuid": net} for net in networks]

    def _create_private_network(self):
        """Create an extra private network to be attached.

        This network is the one with disabled DHCP and
        ready for static configuration by cb-init.
        """
        tenant_id = self._manager.primary_credentials().tenant_id
        # pylint: disable=protected-access
        net_resources = self._manager.isolated_creds._create_network_resources(
            tenant_id)

        # Store the network for later cleanup.
        key = "fake"
        fake_net_creds = util.get_namedtuple(
            "FakeCreds",
            ("network", "subnet", "router",
             "user_id", "tenant_id", "username", "tenant_name"),
            net_resources + (None,) * 4)
        self._manager.isolated_creds._creds[key] = fake_net_creds

        # Disable DHCP for this network to test static configuration and
        # also add default DNS name servers.
        subnet_id = fake_net_creds.subnet["id"]
        net_client = self._manager.network_client
        net_client.update_subnet(
            subnet_id, enable_dhcp=False,
            dns_nameservers=self._conf.argus.dns_nameservers)

        # Change the allocation pool to configure any IP,
        # other the one used already with dynamic settings.
        allocation_pools = net_client.show_subnet(subnet_id)["subnet"][
            "allocation_pools"]
        allocation_pools[0]["start"] = util.next_ip(
            allocation_pools[0]["start"], step=2)
        net_client.update_subnet(subnet_id, allocation_pools=allocation_pools)

        # Create and attach an IPv6 subnet for this network. Also, register
        # it for later cleanup.
        subnet6_name = util.rand_name(self.__class__.__name__) + "-subnet6"
        network_id = fake_net_creds.network["id"]
        net_client.create_subnet(
            network_id=network_id,
            cidr=SUBNET6_CIDR,
            name=subnet6_name,
            dns_nameservers=DNSES6,
            tenant_id=tenant_id,
            enable_dhcp=False,
            ip_version=6)

    def setup_instance(self):
        # Just like a normal preparer, but this time
        # with explicitly specified attached networks.

        if not isinstance(self._manager.isolated_creds,
                          dynamic_creds.DynamicCredentialProvider):
            raise exceptions.ArgusError(
                "Network resources are not available."
            )

        self._create_private_network()
        self._networks = self._get_networks()

        super(NetworkWindowsBackend, self).setup_instance()

    @staticmethod
    def _find_ip_address(port, subnet_id):
        for fixed_ip in port["fixed_ips"]:
            if fixed_ip["subnet_id"] == subnet_id:
                return fixed_ip["ip_address"]

    def get_network_interfaces(self):
        """Retrieve and parse network details from the compute node."""
        networks_client = self._manager.networks_client
        network_client = self._manager.network_client
        guest_nics = []
        for network in self._networks or []:
            network_id = network["uuid"]
            net_details = networks_client.show_network(network_id)["network"]
            nic = dict.fromkeys(util.NETWORK_KEYS)
            for subnet_id in net_details["subnets"]:
                details = network_client.show_subnet(subnet_id)["subnet"]

                # The network interface should follow the format found under
                # `windows.InstanceIntrospection.get_network_interfaces`
                # method or `argus.util.NETWORK_KEYS` model.
                v6switch = details["ip_version"] == 6
                v6suffix = "6" if v6switch else ""
                nic["dhcp"] = details["enable_dhcp"]
                nic["dns" + v6suffix] = details["dns_nameservers"]
                nic["gateway" + v6suffix] = details["gateway_ip"]
                nic["netmask" + v6suffix] = (
                    details["cidr"].split("/")[1] if v6switch
                    else util.cidr2netmask(details["cidr"]))

                # Find rest of the details under the ports using this subnet.
                # There should be no conflicts because on the current
                # architecture every instance is using its own router,
                # subnet and network accessible only to it.
                ports = network_client.list_ports()["ports"]
                for port in ports:
                    # Select instance related ports only, with the
                    # corresponding subnet ID.
                    if "compute" not in port["device_owner"]:
                        continue
                    ip_address = self._find_ip_address(port, subnet_id)
                    if not ip_address:
                        continue
                    nic["mac"] = port["mac_address"].upper()
                    nic["address" + v6suffix] = ip_address
                    break

            guest_nics.append(nic)
        return guest_nics

class RescueWindowsBackend(tempest_backend.BaseWindowsTempestBackend):
    """Instance rescue Windows-based backend."""

    def rescue_server(self):
        admin_pass = self._conf.openstack.image_password
        self._manager.servers_client.rescue_server(
            self.internal_instance_id(),
            adminPass=admin_pass)

        waiters.wait_for_server_status(
            self._manager.servers_client,
            self.internal_instance_id(), 'RESCUE')

    def unrescue_server(self):
        self._manager.servers_client.unrescue_server(
            self.internal_instance_id())
        waiters.wait_for_server_status(
            self._manager.servers_client,
            self.internal_instance_id(), 'ACTIVE')
<|endoftext|>


<commit_before>#!/usr/bin/env python

from argparse import ArgumentParser
from contextlib import contextmanager
import logging
from textwrap import dedent
from subprocess import CalledProcessError
import sys

from jujupy import (
    EnvJujuClient,
    LXC_MACHINE,
    SimpleEnvironment,
    until_timeout,
    )
from deploy_stack import (
    BootstrapManager,
    check_token,
    get_random_string,
    )
from jujuci import add_credential_args
from utility import (
    configure_logging,
    local_charm_path,
)

def prepare_dummy_env(client):
    """Use a client to prepare a dummy environment."""
    charm_source = local_charm_path(
        charm='dummy-source', juju_ver=client.version)
    client.deploy(charm_source)
    charm_sink = local_charm_path(charm='dummy-sink', juju_ver=client.version)
    client.deploy(charm_sink)
    token = get_random_string()
    client.set_config('dummy-source', {'token': token})
    client.juju('add-relation', ('dummy-source', 'dummy-sink'))
    client.juju('expose', ('dummy-sink',))
    return token

def get_clients(initial, other, base_env, debug, agent_url):
    """Return the clients to use for testing."""
    environment = SimpleEnvironment.from_config(base_env)
    if agent_url is None:
        environment.config.pop('tools-metadata-url', None)
    initial_client = EnvJujuClient.by_version(environment, initial,
                                              debug=debug)
    other_client = EnvJujuClient.by_version(environment, other, debug=debug)
    # System juju is assumed to be released and the best choice for tearing
    # down environments reliably.  (For example, 1.18.x cannot tear down
    # environments with alpha agent-versions.)
    released_client = EnvJujuClient.by_version(environment, debug=debug)
    if released_client.env != initial_client.env:
        released_client = initial_client
    return initial_client, other_client, released_client

def assess_heterogeneous(initial, other, base_env, environment_name, log_dir,
                         upload_tools, debug, agent_url, agent_stream, series):
    """Top level function that prepares the clients and environment.

    initial and other are paths to the binary used initially, and a binary
    used later.  base_env is the name of the environment to base the
    environment on and environment_name is the new name for the environment.
    """
    initial_client, other_client, teardown_client = get_clients(
        initial, other, base_env, debug, agent_url)
    jes_enabled = initial_client.is_jes_enabled()
    bs_manager = BootstrapManager(
        environment_name, initial_client, teardown_client,
        bootstrap_host=None, machines=[], series=series, agent_url=agent_url,
        agent_stream=agent_stream, region=None, log_dir=log_dir,
        keep_env=False, permanent=jes_enabled, jes_enabled=jes_enabled)
    test_control_heterogeneous(bs_manager, other_client, upload_tools)

@contextmanager
def run_context(bs_manager, other, upload_tools):
    try:
        bs_manager.keep_env = True
        if other.env.juju_home != bs_manager.client.env.juju_home:
            raise AssertionError('Juju home out of sync')
        with bs_manager.booted_context(upload_tools):
            other.env.juju_home = bs_manager.client.env.juju_home
            yield
        # Test clean shutdown of an environment.
        callback_with_fallback(other, bs_manager.tear_down_client,
                               nice_tear_down)
    except:
        bs_manager.tear_down()
        raise

def test_control_heterogeneous(bs_manager, other, upload_tools):
    """Test if one binary can control an environment set up by the other."""
    initial = bs_manager.client
    released = bs_manager.tear_down_client
    with run_context(bs_manager, other, upload_tools):
        token = prepare_dummy_env(initial)
        initial.wait_for_started()
        if False:
            if sys.platform != "win32":
                # Currently, juju ssh is not working on Windows.
                check_token(initial, token)
                check_series(other)
                other.juju('run', ('--all', 'uname -a'))
            other.get_config('dummy-source')
            other.get_model_config()
            other.juju('remove-relation', ('dummy-source', 'dummy-sink'))
            status = other.get_status()
            other.juju('unexpose', ('dummy-sink',))
            status = other.get_status()
            if status.status['services']['dummy-sink']['exposed']:
                raise AssertionError('dummy-sink is still exposed')
            status = other.get_status()
            charm_path = local_charm_path(
                charm='dummy-sink', juju_ver=other.version)
            juju_with_fallback(other, released, 'deploy',
                               (charm_path, 'sink2'))
            other.wait_for_started()
            other.juju('add-relation', ('dummy-source', 'sink2'))
            status = other.get_status()
            other.juju('expose', ('sink2',))
            status = other.get_status()
            if 'sink2' not in status.status['services']:
                raise AssertionError('Sink2 missing')
            other.remove_service('sink2')
            for ignored in until_timeout(30):
            status = other.get_status()
            if 'sink2' not in status.status['services']:
                raise AssertionError('Sink2 missing')
            other.remove_service('sink2')
            for ignored in until_timeout(30):
                status = other.get_status()
                if 'sink2' not in status.status['services']:
                    break
            else:
                raise AssertionError('Sink2 not destroyed')
            other.juju('add-relation', ('dummy-source', 'dummy-sink'))
            status = other.get_status()
            relations = status.status['services']['dummy-sink']['relations']
            if not relations['source'] == ['dummy-source']:
                raise AssertionError('source is not dummy-source.')
            other.juju('expose', ('dummy-sink',))
            status = other.get_status()
            if not status.status['services']['dummy-sink']['exposed']:
                raise AssertionError('dummy-sink is not exposed')
            other.juju('add-unit', ('dummy-sink',))
            if not has_agent(other, 'dummy-sink/1'):
                raise AssertionError('dummy-sink/1 was not added.')
            other.juju('remove-unit', ('dummy-sink/1',))
            status = other.get_status()
            if has_agent(other, 'dummy-sink/1'):
                raise AssertionError('dummy-sink/1 was not removed.')
        container_type = LXC_MACHINE
        other.juju('add-machine', (container_type,))
        status = other.get_status()
        container_machine, = set(k for k, v in status.agent_items() if
                                 k.endswith('/{}/0'.format(container_type)))
        container_holder = container_machine.split('/')[0]
        other.juju('remove-machine', (container_machine,))
        wait_until_removed(other, container_machine)
        other.juju('remove-machine', (container_holder,))
        wait_until_removed(other, container_holder)

# suppress nosetests
test_control_heterogeneous.__test__ = False

def juju_with_fallback(other, released, command, args, include_e=True):
    """Fallback to released juju when 1.18 fails.

    Get as much test coverage of 1.18 as we can, by falling back to a released
    juju for commands that we expect to fail (due to unsupported agent version
    format).
    """
    def call_juju(client):
        client.juju(command, args, include_e=include_e)
    return callback_with_fallback(other, released, call_juju)

def callback_with_fallback(other, released, callback):
    for client in [other, released]:
        try:
            callback(client)
        except CalledProcessError:
            if not client.version.startswith('1.18.'):
                raise
        else:
            break

def nice_tear_down(client):
    if client.is_jes_enabled():
        client.kill_controller()
    else:
        if client.destroy_environment(force=False) != 0:
            raise CalledProcessError(1, 'juju destroy-environment')

def has_agent(client, agent_id):
    return bool(agent_id in dict(client.get_status().agent_items()))

def wait_until_removed(client, agent_id):
    """Wait for an agent to be removed from the environment."""
    for ignored in until_timeout(240):
        if not has_agent(client, agent_id):
            return
    else:
        raise AssertionError('Machine not destroyed: {}.'.format(agent_id))

def check_series(client,  machine='0', series=None):
    """Use 'juju ssh' to check that the deployed series meets expectations."""
    result = client.get_juju_output('ssh', machine, 'lsb_release', '-c')
    label, codename = result.rstrip().split('\t')
    if label != 'Codename:':
        raise AssertionError()
    if series:
        expected_codename = series
    else:
        expected_codename = client.env.config['default-series']
    if codename != expected_codename:
        raise AssertionError(
            'Series is {}, not {}'.format(codename, expected_codename))

def parse_args(argv=None):
    parser = ArgumentParser(description=dedent("""\
        Determine whether one juju version can control an environment created
        by another version.
    """))
    parser.add_argument('initial', help='The initial juju binary.')
    parser.add_argument('other', help='A different juju binary.')
    parser.add_argument('base_environment', help='The environment to base on.')
    parser.add_argument('environment_name', help='The new environment name.')
    parser.add_argument('log_dir', help='The directory to dump logs to.')
    parser.add_argument(
        '--upload-tools', action='store_true', default=False,
        help='Upload local version of tools before bootstrapping.')
    parser.add_argument('--debug', help='Run juju with --debug',
                        action='store_true', default=False)
    parser.add_argument('--agent-url', default=None)
    parser.add_argument('--agent-stream', action='store',
                        help='URL for retrieving agent binaries.')
    parser.add_argument('--series', action='store',
                        help='Name of the Ubuntu series to use.')
    add_credential_args(parser)
    return parser.parse_args(argv)

def main():
    args = parse_args()
    configure_logging(logging.INFO)
    assess_heterogeneous(args.initial, args.other, args.base_environment,
                         args.environment_name, args.log_dir,
                         args.upload_tools, args.debug, args.agent_url,
                         args.agent_stream, args.series)

if __name__ == '__main__':
    main()
<commit_msg>Get working.<commit_after>#!/usr/bin/env python

from argparse import ArgumentParser
from contextlib import contextmanager
import logging
from textwrap import dedent
from subprocess import CalledProcessError
import sys

from jujupy import (
    EnvJujuClient,
    EnvJujuClient1X,
    LXC_MACHINE,
    SimpleEnvironment,
    until_timeout,
    )
from deploy_stack import (
    BootstrapManager,
    check_token,
    get_random_string,
    )
from jujuci import add_credential_args
from utility import (
    configure_logging,
    local_charm_path,
)

def prepare_dummy_env(client):
    """Use a client to prepare a dummy environment."""
    charm_source = local_charm_path(
        charm='dummy-source', juju_ver=client.version)
    client.deploy(charm_source)
    charm_sink = local_charm_path(charm='dummy-sink', juju_ver=client.version)
    client.deploy(charm_sink)
    token = get_random_string()
    client.set_config('dummy-source', {'token': token})
    client.juju('add-relation', ('dummy-source', 'dummy-sink'))
    client.juju('expose', ('dummy-sink',))
    return token

def get_clients(initial, other, base_env, debug, agent_url):
    """Return the clients to use for testing."""
    environment = SimpleEnvironment.from_config(base_env)
    if agent_url is None:
        environment.config.pop('tools-metadata-url', None)
    initial_client = EnvJujuClient.by_version(environment, initial,
                                              debug=debug)
    other_client = EnvJujuClient.by_version(initial_client.env, other,
                                            debug=debug)
    # System juju is assumed to be released and the best choice for tearing
    # down environments reliably.  (For example, 1.18.x cannot tear down
    # environments with alpha agent-versions.)
    released_client = EnvJujuClient.by_version(environment, debug=debug)
    # If released_client is a different major version, it cannot tear down
    # initial client, so use initial client for teardown.
    if (isinstance(released_client, EnvJujuClient1X) !=
        isinstance(initial_client, EnvJujuClient1X)):
            released_client = initial_client
    else:
        # If system juju is used, ensure it has identical env to
        # initial_client.
        released_client.env = initial_client.env
    return initial_client, other_client, released_client

def assess_heterogeneous(initial, other, base_env, environment_name, log_dir,
                         upload_tools, debug, agent_url, agent_stream, series):
    """Top level function that prepares the clients and environment.

    initial and other are paths to the binary used initially, and a binary
    used later.  base_env is the name of the environment to base the
    environment on and environment_name is the new name for the environment.
    """
    initial_client, other_client, teardown_client = get_clients(
        initial, other, base_env, debug, agent_url)
    jes_enabled = initial_client.is_jes_enabled()
    bs_manager = BootstrapManager(
        environment_name, initial_client, teardown_client,
        bootstrap_host=None, machines=[], series=series, agent_url=agent_url,
        agent_stream=agent_stream, region=None, log_dir=log_dir,
        keep_env=False, permanent=jes_enabled, jes_enabled=jes_enabled)
    test_control_heterogeneous(bs_manager, other_client, upload_tools)

@contextmanager
def run_context(bs_manager, other, upload_tools):
    try:
        bs_manager.keep_env = True
        with bs_manager.booted_context(upload_tools):
            if other.env.juju_home != bs_manager.client.env.juju_home:
                raise AssertionError('Juju home out of sync')
            yield
        # Test clean shutdown of an environment.
        callback_with_fallback(other, bs_manager.tear_down_client,
                               nice_tear_down)
    except:
        bs_manager.tear_down()
        raise

def test_control_heterogeneous(bs_manager, other, upload_tools):
    """Test if one binary can control an environment set up by the other."""
    initial = bs_manager.client
    released = bs_manager.tear_down_client
    with run_context(bs_manager, other, upload_tools):
        token = prepare_dummy_env(initial)
        initial.wait_for_started()
        if sys.platform != "win32":
            # Currently, juju ssh is not working on Windows.
            check_token(initial, token)
            check_series(other)
            other.juju('run', ('--all', 'uname -a'))
        other.get_config('dummy-source')
        other.get_model_config()
        other.juju('remove-relation', ('dummy-source', 'dummy-sink'))
        status = other.get_status()
        other.juju('unexpose', ('dummy-sink',))
        status = other.get_status()
        if status.status['services']['dummy-sink']['exposed']:
            raise AssertionError('dummy-sink is still exposed')
        status = other.get_status()
        charm_path = local_charm_path(
            charm='dummy-sink', juju_ver=other.version)
        juju_with_fallback(other, released, 'deploy',
                           (charm_path, 'sink2'))
        other.wait_for_started()
        other.juju('add-relation', ('dummy-source', 'sink2'))
        status = other.get_status()
        other.juju('expose', ('sink2',))
        status = other.get_status()
        if 'sink2' not in status.status['services']:
            raise AssertionError('Sink2 missing')
        other.remove_service('sink2')
        for ignored in until_timeout(30):
            status = other.get_status()
            if 'sink2' not in status.status['services']:
                break
        else:
            raise AssertionError('Sink2 not destroyed')
        other.juju('add-relation', ('dummy-source', 'dummy-sink'))
        status = other.get_status()
        relations = status.status['services']['dummy-sink']['relations']
        if not relations['source'] == ['dummy-source']:
            raise AssertionError('source is not dummy-source.')
        other.juju('expose', ('dummy-sink',))
        status = other.get_status()
        if not status.status['services']['dummy-sink']['exposed']:
            raise AssertionError('dummy-sink is not exposed')
        other.juju('add-unit', ('dummy-sink',))
        if not has_agent(other, 'dummy-sink/1'):
            raise AssertionError('dummy-sink/1 was not added.')
        other.juju('remove-unit', ('dummy-sink/1',))
        status = other.get_status()
        if has_agent(other, 'dummy-sink/1'):
            raise AssertionError('dummy-sink/1 was not removed.')
        container_type = other.preferred_container()
        other.juju('add-machine', (container_type,))
        status = other.get_status()
        container_machine, = set(k for k, v in status.agent_items() if
                                 k.endswith('/{}/0'.format(container_type)))
        container_holder = container_machine.split('/')[0]
        other.juju('remove-machine', (container_machine,))
        wait_until_removed(other, container_machine)
        other.juju('remove-machine', (container_holder,))
        wait_until_removed(other, container_holder)

# suppress nosetests
test_control_heterogeneous.__test__ = False

def juju_with_fallback(other, released, command, args, include_e=True):
    """Fallback to released juju when 1.18 fails.

    Get as much test coverage of 1.18 as we can, by falling back to a released
    juju for commands that we expect to fail (due to unsupported agent version
    format).
    """
    def call_juju(client):
        client.juju(command, args, include_e=include_e)
    return callback_with_fallback(other, released, call_juju)

def callback_with_fallback(other, released, callback):
    for client in [other, released]:
        try:
            callback(client)
        except CalledProcessError:
            if not client.version.startswith('1.18.'):
                raise
        else:
            break

def nice_tear_down(client):
    if client.is_jes_enabled():
        client.kill_controller()
    else:
        if client.destroy_environment(force=False) != 0:
            raise CalledProcessError(1, 'juju destroy-environment')

def has_agent(client, agent_id):
    return bool(agent_id in dict(client.get_status().agent_items()))

def wait_until_removed(client, agent_id):
    """Wait for an agent to be removed from the environment."""
    for ignored in until_timeout(240):
        if not has_agent(client, agent_id):
            return
    else:
        raise AssertionError('Machine not destroyed: {}.'.format(agent_id))

def check_series(client,  machine='0', series=None):
    """Use 'juju ssh' to check that the deployed series meets expectations."""
    result = client.get_juju_output('ssh', machine, 'lsb_release', '-c')
    label, codename = result.rstrip().split('\t')
    if label != 'Codename:':
        raise AssertionError()
    if series:
        expected_codename = series
    else:
        expected_codename = client.env.config['default-series']
    if codename != expected_codename:
        raise AssertionError(
            'Series is {}, not {}'.format(codename, expected_codename))

def parse_args(argv=None):
    parser = ArgumentParser(description=dedent("""\
        Determine whether one juju version can control an environment created
        by another version.
    """))
    parser.add_argument('initial', help='The initial juju binary.')
    parser.add_argument('other', help='A different juju binary.')
    parser.add_argument('base_environment', help='The environment to base on.')
    parser.add_argument('environment_name', help='The new environment name.')
    parser.add_argument('log_dir', help='The directory to dump logs to.')
    parser.add_argument(
        '--upload-tools', action='store_true', default=False,
        help='Upload local version of tools before bootstrapping.')
    parser.add_argument('--debug', help='Run juju with --debug',
                        action='store_true', default=False)
    parser.add_argument('--agent-url', default=None)
    parser.add_argument('--agent-stream', action='store',
                        help='URL for retrieving agent binaries.')
    parser.add_argument('--series', action='store',
                        help='Name of the Ubuntu series to use.')
    add_credential_args(parser)
    return parser.parse_args(argv)

def main():
    args = parse_args()
    configure_logging(logging.INFO)
    assess_heterogeneous(args.initial, args.other, args.base_environment,
                         args.environment_name, args.log_dir,
                         args.upload_tools, args.debug, args.agent_url,
                         args.agent_stream, args.series)

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>"""project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from .database import views
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'clients', views.ClientViewSet)
router.register(r'services', views.ServiceViewSet)
router.register(r'testimonials', views.TestimonialViewSet)
router.register(r'profiles', views.ProfileViewSet)

certbot_hash = 'vyaZaRpD5a1mARuqFEXbgyiOyeLmGKGv-AYX_RGFgt8'

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', include(admin.site.urls)),
    # API
    url(r'^api/', include(router.urls)),
    # Certbot
    url(r'.well-known/acme-challenge/%s' % certbot_hash,
        views.certbot,
        name='certbot'),
    # Client
    url(r'^client/(?P<pk>\d+)$', views.client, name='client'),
    url(r'^client/(?P<pk>\d+)/edit$', views.client_edit, name='client_edit'),
    url(r'^client/add$', views.client_edit, name='client_edit'),
    url(r'^client$', views.client_index, name='client_index'),
    # Company
    url(r'^company/edit$', views.company_edit, name='company_edit'),
    url(r'^company$', views.company, name='company'),
    # Contact
    url(r'^contact/(?P<pk>\d+)$', views.contact, name='contact'),
    url(r'^contact/(?P<pk>\d+)/edit$', views.contact_edit,
        name='contact_edit'),
    url(r'^contact/add$', views.contact_edit, name='contact_edit'),
    url(r'^contact$', views.contact_index, name='contact_index'),
    url(r'^contact/(?P<pk>\d+)/mail$', views.contact_mail,
        name='contact_mail'),
    url(r'^contact/(?P<pk>\d+)/unsubscribe$',
        views.contact_unsubscribe,
        name='contact_unsubscribe'),
    # Estimate
    url(r'^estimate/(?P<pk>\d+)$', views.estimate, name='estimate'),
    url(r'^estimate/(?P<pk>\d+)/edit$',
        views.estimate_edit,
        name='estimate_edit'),
    url(r'^estimate/add$', views.estimate_edit, name='estimate_edit'),
    url(r'^estimate$', views.estimate_index, name='estimate_index'),
    # Invoice
    url(r'^invoice/(?P<pk>\d+)$', views.invoice, name='invoice'),
    url(r'^invoice/(?P<pk>\d+)/edit$', views.invoice_edit,
        name='invoice_edit'),
    url(r'^invoice/add$', views.invoice_edit, name='invoice_edit'),
    url(r'^invoice$', views.invoice_index, name='invoice_index'),
    # Logs
    url(r'^logs$', views.settings, name='logs'),
    # Note
    url(r'^note/(?P<pk>\d+)$', views.note, name='note'),
    url(r'^note/(?P<pk>\d+)/edit$', views.note_edit, name='note_edit'),
    url(r'^note/add$', views.note_edit, name='note_edit'),
    url(r'^note$', views.note_index, name='note_index'),
    # Project
    url(r'^project/(?P<pk>\d+)$', views.project, name='project'),
    url(r'^project/(?P<pk>\d+)/edit$', views.project_edit,
        name='project_edit'),
    url(r'^project/add$', views.project_edit, name='project_edit'),
    url(r'^project$', views.project_index, name='project_index'),
    # Report
    url(r'^report/(?P<pk>\d+)$', views.report, name='report'),
    url(r'^report$', views.report_index, name='report_index'),
    url(r'^report/add$', views.report_edit, name='report_edit'),
    url(r'^report/(?P<pk>\d+)/edit$', views.report_edit, name='report_edit'),
    url(r'^report_plot$', views.report_plot, name='report_plot'),
    # Settings
    url(r'^settings/edit$', views.settings_edit, name='settings_edit'),
    url(r'^settings$', views.settings, name='settings'),
    # Social
    url('', include(
        'django.contrib.auth.urls', namespace='auth')),
    url('', include(
        'social_django.urls', namespace='social')),
    # Task
    url(r'^task/(?P<pk>\d+)$', views.task, name='task'),
    url(r'^task/(?P<pk>\d+)/edit$', views.task_edit, name='task_edit'),
    url(r'^task/add$', views.task_edit, name='task_edit'),
    url(r'^task$', views.task_index, name='task_index'),
    # Time
    url(r'^time/(?P<pk>\d+)$', views.time, name='entry'),
    url(r'^time/(?P<pk>\d+)/edit$', views.time_edit, name='entry_edit'),
    url(r'^time/add$', views.time_edit, name='entry_edit'),
    url(r'^time$', views.time_index, name='entry_index'),
    # TinyMCE
    url(r'^tinymce/', include('tinymce.urls')),
    # User
    url(r'^user/(?P<pk>\d+)$', views.user, name='user'),
    url(r'^user/(?P<pk>\d+)/edit$', views.user_edit, name='user_edit'),
    url(r'^user/(?P<pk>\d+)/contact$', views.user_contact,
        name='user_contact'),
    url(r'^user$', views.user_index, name='user_index'),
]
<commit_msg>Update<commit_after>"""project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from .database import views
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'clients', views.ClientViewSet)
router.register(r'services', views.ServiceViewSet)
router.register(r'testimonials', views.TestimonialViewSet)
router.register(r'profiles', views.ProfileViewSet)

certbot_hash = 'vyaZaRpD5a1mARuqFEXbgyiOyeLmGKGv-AYX_RGFgt8'

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', include(admin.site.urls)),
    # API
    url(r'^api/', include(router.urls)),
    # Certbot
    url(r'.well-known/acme-challenge/%s' % certbot_hash,
        views.certbot,
        name='certbot'),
    # Client
    url(r'^client/(?P<pk>\d+)$', views.client, name='client'),
    url(r'^client/(?P<pk>\d+)/edit$', views.client_edit, name='client_edit'),
    url(r'^client/add$', views.client_edit, name='client_edit'),
    url(r'^client$', views.client_index, name='client_index'),
    # Company
    url(r'^company/edit$', views.company_edit, name='company_edit'),
    url(r'^company$', views.company, name='company'),
    # Contact
    url(r'^contact/(?P<pk>\d+)$', views.contact, name='contact'),
    url(r'^contact/(?P<pk>\d+)/edit$', views.contact_edit,
        name='contact_edit'),
    url(r'^contact/add$', views.contact_edit, name='contact_edit'),
    url(r'^contact$', views.contact_index, name='contact_index'),
    url(r'^contact/(?P<pk>\d+)/mail$', views.contact_mail,
        name='contact_mail'),
    url(r'^contact/(?P<pk>\d+)/unsubscribe$',
        views.contact_unsubscribe,
        name='contact_unsubscribe'),
    # Estimate
    url(r'^estimate/(?P<pk>\d+)$', views.estimate, name='estimate'),
    url(r'^estimate/(?P<pk>\d+)/edit$',
        views.estimate_edit,
        name='estimate_edit'),
    url(r'^estimate/add$', views.estimate_edit, name='estimate_edit'),
    url(r'^estimate$', views.estimate_index, name='estimate_index'),
    # Invoice
    url(r'^invoice/(?P<pk>\d+)$', views.invoice, name='invoice'),
    url(r'^invoice/(?P<pk>\d+)/edit$', views.invoice_edit,
        name='invoice_edit'),
    url(r'^invoice/add$', views.invoice_edit, name='invoice_edit'),
    url(r'^invoice$', views.invoice_index, name='invoice_index'),
    # Logs
    url(r'^logs$', views.logs, name='logs'),
    # Note
    url(r'^note/(?P<pk>\d+)$', views.note, name='note'),
    url(r'^note/(?P<pk>\d+)/edit$', views.note_edit, name='note_edit'),
    url(r'^note/add$', views.note_edit, name='note_edit'),
    url(r'^note$', views.note_index, name='note_index'),
    # Project
    url(r'^project/(?P<pk>\d+)$', views.project, name='project'),
    url(r'^project/(?P<pk>\d+)/edit$', views.project_edit,
        name='project_edit'),
    url(r'^project/add$', views.project_edit, name='project_edit'),
    url(r'^project$', views.project_index, name='project_index'),
    # Report
    url(r'^report/(?P<pk>\d+)$', views.report, name='report'),
    url(r'^report$', views.report_index, name='report_index'),
    url(r'^report/add$', views.report_edit, name='report_edit'),
    url(r'^report/(?P<pk>\d+)/edit$', views.report_edit, name='report_edit'),
    url(r'^report_plot$', views.report_plot, name='report_plot'),
    # Settings
    url(r'^settings/edit$', views.settings_edit, name='settings_edit'),
    url(r'^settings$', views.settings, name='settings'),
    # Social
    url('', include(
        'django.contrib.auth.urls', namespace='auth')),
    url('', include(
        'social_django.urls', namespace='social')),
    # Task
    url(r'^task/(?P<pk>\d+)$', views.task, name='task'),
    url(r'^task/(?P<pk>\d+)/edit$', views.task_edit, name='task_edit'),
    url(r'^task/add$', views.task_edit, name='task_edit'),
    url(r'^task$', views.task_index, name='task_index'),
    # Time
    url(r'^time/(?P<pk>\d+)$', views.time, name='entry'),
    url(r'^time/(?P<pk>\d+)/edit$', views.time_edit, name='entry_edit'),
    url(r'^time/add$', views.time_edit, name='entry_edit'),
    url(r'^time$', views.time_index, name='entry_index'),
    # TinyMCE
    url(r'^tinymce/', include('tinymce.urls')),
    # User
    url(r'^user/(?P<pk>\d+)$', views.user, name='user'),
    url(r'^user/(?P<pk>\d+)/edit$', views.user_edit, name='user_edit'),
    url(r'^user/(?P<pk>\d+)/contact$', views.user_contact,
        name='user_contact'),
    url(r'^user$', views.user_index, name='user_index'),
]
<|endoftext|>


<commit_before>import constant
from database import Database
from arduino import Arduino
from flask import Flask, request, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)
arduino = Arduino()
database = Database()

@app.route("/")
def index():
    return render_template("dashboardv2.html")

@app.route("/getTime")
def getTime():
	return arduino.getTime()

@app.route("/resetTime")
def resetTime():
	return arduino.resetTime()

@app.route("/registerCard", methods=['POST'])
def registerCard():
	data = request.get_json()
	arduinoStatus = arduino.registerCard(data)
	if arduinoStatus == data["uid"]:
		print("RFID tag registered")
		if data["isNew"]:
			return database.insertUser(data)
		else:
			return arduinoStatus
	else:
		return "0"

@app.route("/laserLog/<laser>/<int:id>/<int:elapsedTime>/<int:existingTime>")
def laserLog(laser, id, elapsedTime, existingTime):
	data = {"laserType": laser, "uid": id, "elapsedTime": elapsedTime, "existingTime": existingTime}
	database.laserLog(data)
	return database.insertLaserTime(data)

@app.route("/scanTest/<int:id>")
def serialTest(id):
	if id != 0:
		# ignore guest cards for now
		if id != 6 and id != 12 and id < 100:
			data = database.retrieveUser(id)
			socketio.emit('scan', data)
			if refresh(id, data) == id:
				print("RFID tag refreshed")
			database.scanLog(id)
	return str(id)
# ----------------------------------------
@app.route("/refresh")
def refresh(id, data):
	userData = [ str(id) ]
	userData.extend(data[constant.COL_USES_LASER_A:constant.COL_USES_3D+1])
	print(userData)
	return arduino.refreshUser(userData)

if (__name__ == "__main__"):
    # app.run(host='0.0.0.0')
	socketio.run(app, host='0.0.0.0')<commit_msg>Fixing bug with staff offset<commit_after>import constant
from database import Database
from arduino import Arduino
from flask import Flask, request, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)
arduino = Arduino()
database = Database()

@app.route("/")
def index():
    return render_template("dashboardv2.html")

@app.route("/getTime")
def getTime():
	return arduino.getTime()

@app.route("/resetTime")
def resetTime():
	return arduino.resetTime()

@app.route("/registerCard", methods=['POST'])
def registerCard():
	data = request.get_json()
	arduinoStatus = arduino.registerCard(data)
	if arduinoStatus == data["uid"]:
		print("RFID tag registered")
		if data["isNew"]:
			return database.insertUser(data)
		else:
			return arduinoStatus
	else:
		return "0"

@app.route("/laserLog/<laser>/<int:id>/<int:elapsedTime>/<int:existingTime>")
def laserLog(laser, id, elapsedTime, existingTime):
	data = {"laserType": laser, "uid": id, "elapsedTime": elapsedTime, "existingTime": existingTime}
	database.laserLog(data)
	return database.insertLaserTime(data)

@app.route("/scanTest/<int:id>")
def serialTest(id):
	if id != 0:
		# ignore guest cards for now
		if id != 6 and id != 12 and id < 100:
			data = database.retrieveUser(id)
			socketio.emit('scan', data)
			if refresh(id, data) == id:
				print("RFID tag refreshed")
			database.scanLog(id)
	return str(id)
# ----------------------------------------
@app.route("/refresh")
def refresh(id, data):
	userData = [ str(id), data[2] ]
	userData.extend(data[constant.COL_USES_LASER_A:constant.COL_USES_3D+1])
	print(userData)
	return arduino.refreshUser(userData)

if (__name__ == "__main__"):
    # app.run(host='0.0.0.0')
	socketio.run(app, host='0.0.0.0')<|endoftext|>


<commit_before>#!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Requires Python 2.7+
#

import os
import sys

from OSEncryptionState import *
from time import sleep

class StripdownState(OSEncryptionState):
    def __init__(self, context):
        super(StripdownState, self).__init__('StripdownState', context)

    def should_enter(self):
        self.context.logger.log("Verifying if machine should enter stripdown state")

        if not super(StripdownState, self).should_enter():
            return False

        self.context.logger.log("Performing enter checks for stripdown state")

        self.command_executor.Execute('rm -rf /usr/tmproot', True)
        self.command_executor.ExecuteInBash('! [ -e "/oldroot" ]', True)

        return True

    def enter(self):
        if not self.should_enter():
            return

        self.context.logger.log("Entering stripdown state")

        self.command_executor.Execute('swapoff -a')
        self.command_executor.Execute('umount -a')
        self.command_executor.Execute('mkdir /usr/tmproot', True)
        self.command_executor.Execute('mount -t tmpfs none /usr/tmproot', True)
        self.command_executor.ExecuteInBash('for i in proc sys dev run usr var tmp root oldroot boot; do mkdir /usr/tmproot/$i; done', True)
        self.command_executor.ExecuteInBash('for i in bin etc mnt sbin lib lib64 root; do cp -ax /$i /usr/tmproot/; done', True)
        self.command_executor.ExecuteInBash('for i in bin sbin libexec lib lib64 share; do cp -ax /usr/$i /usr/tmproot/usr/; done', True)
        self.command_executor.ExecuteInBash('for i in lib local lock opt run spool tmp; do cp -ax /var/$i /usr/tmproot/var/; done', True)
        self.command_executor.ExecuteInBash('mkdir /usr/tmproot/var/log', True)
        self.command_executor.ExecuteInBash('cp -ax /var/log/azure /usr/tmproot/var/log/', True)
        self.command_executor.Execute('mount --make-rprivate /', True)
        self.command_executor.ExecuteInBash('[ -e "/usr/tmproot/var/lib/azure_disk_encryption_config/azure_crypt_request_queue.ini" ]', True)
        self.command_executor.Execute('systemctl stop waagent', True)
        self.command_executor.Execute('pivot_root /usr/tmproot /usr/tmproot/oldroot', True)
        self.command_executor.ExecuteInBash('for i in dev proc sys run; do mount --move /oldroot/$i /$i; done', True)

    def should_exit(self):
        self.context.logger.log("Verifying if machine should exit stripdown state")

        if not os.path.exists(self.state_marker):
            self.context.logger.log("First call to stripdown state (pid={0}), restarting process".format(os.getpid()))

            # create the marker, but do not advance the state machine
            super(StripdownState, self).should_exit()

            self.command_executor.ExecuteInBash('rm -f /run/systemd/generator/*.mount', True)
            self.command_executor.ExecuteInBash('rm -f /run/systemd/generator/local-fs.target.requires/*.mount', True)

            self.command_executor.Execute("sed -i.bak '/rootlv/d' /etc/fstab", True)

            self.command_executor.Execute('telinit u', True)

            sleep(10)

            if self.command_executor.Execute('mountpoint /var') == 0:
                self.command_executor.Execute('umount /var', True)

            # the restarted process shall see the marker and advance the state machine
            self.command_executor.Execute('systemctl restart atd', True)

            os.chdir('/')
            with open("/restart-wala.sh", "w") as f:
                f.write("systemctl restart waagent\n")
            self.command_executor.Execute('at -f /restart-wala.sh now + 1 minutes', True)

            self.context.hutil.do_exit(exit_code=0,
                                       operation='EnableEncryptionOSVolume',
                                       status=CommonVariables.extension_success_status,
                                       code=str(CommonVariables.success),
                                       message="Restarted extension from stripped down OS")
        else:
            self.context.logger.log("Second call to stripdown state (pid={0}), continuing process".format(os.getpid()))
            return True
<commit_msg>Remove all fstab lines containing rootvg<commit_after>#!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Requires Python 2.7+
#

import os
import sys

from OSEncryptionState import *
from time import sleep

class StripdownState(OSEncryptionState):
    def __init__(self, context):
        super(StripdownState, self).__init__('StripdownState', context)

    def should_enter(self):
        self.context.logger.log("Verifying if machine should enter stripdown state")

        if not super(StripdownState, self).should_enter():
            return False

        self.context.logger.log("Performing enter checks for stripdown state")

        self.command_executor.Execute('rm -rf /usr/tmproot', True)
        self.command_executor.ExecuteInBash('! [ -e "/oldroot" ]', True)

        return True

    def enter(self):
        if not self.should_enter():
            return

        self.context.logger.log("Entering stripdown state")

        self.command_executor.Execute('swapoff -a')
        self.command_executor.Execute('umount -a')
        self.command_executor.Execute('mkdir /usr/tmproot', True)
        self.command_executor.Execute('mount -t tmpfs none /usr/tmproot', True)
        self.command_executor.ExecuteInBash('for i in proc sys dev run usr var tmp root oldroot boot; do mkdir /usr/tmproot/$i; done', True)
        self.command_executor.ExecuteInBash('for i in bin etc mnt sbin lib lib64 root; do cp -ax /$i /usr/tmproot/; done', True)
        self.command_executor.ExecuteInBash('for i in bin sbin libexec lib lib64 share; do cp -ax /usr/$i /usr/tmproot/usr/; done', True)
        self.command_executor.ExecuteInBash('for i in lib local lock opt run spool tmp; do cp -ax /var/$i /usr/tmproot/var/; done', True)
        self.command_executor.ExecuteInBash('mkdir /usr/tmproot/var/log', True)
        self.command_executor.ExecuteInBash('cp -ax /var/log/azure /usr/tmproot/var/log/', True)
        self.command_executor.Execute('mount --make-rprivate /', True)
        self.command_executor.ExecuteInBash('[ -e "/usr/tmproot/var/lib/azure_disk_encryption_config/azure_crypt_request_queue.ini" ]', True)
        self.command_executor.Execute('systemctl stop waagent', True)
        self.command_executor.Execute('pivot_root /usr/tmproot /usr/tmproot/oldroot', True)
        self.command_executor.ExecuteInBash('for i in dev proc sys run; do mount --move /oldroot/$i /$i; done', True)

    def should_exit(self):
        self.context.logger.log("Verifying if machine should exit stripdown state")

        if not os.path.exists(self.state_marker):
            self.context.logger.log("First call to stripdown state (pid={0}), restarting process".format(os.getpid()))

            # create the marker, but do not advance the state machine
            super(StripdownState, self).should_exit()

            self.command_executor.ExecuteInBash('rm -f /run/systemd/generator/*.mount', True)
            self.command_executor.ExecuteInBash('rm -f /run/systemd/generator/local-fs.target.requires/*.mount', True)
            self.command_executor.Execute("sed -i.bak '/rootvg/d' /etc/fstab", True)

            self.command_executor.Execute('telinit u', True)

            sleep(10)

            if self.command_executor.Execute('mountpoint /var') == 0:
                self.command_executor.Execute('umount /var', True)

            # the restarted process shall see the marker and advance the state machine
            self.command_executor.Execute('systemctl restart atd', True)

            os.chdir('/')
            with open("/restart-wala.sh", "w") as f:
                f.write("systemctl restart waagent\n")
            self.command_executor.Execute('at -f /restart-wala.sh now + 1 minutes', True)

            self.context.hutil.do_exit(exit_code=0,
                                       operation='EnableEncryptionOSVolume',
                                       status=CommonVariables.extension_success_status,
                                       code=str(CommonVariables.success),
                                       message="Restarted extension from stripped down OS")
        else:
            self.context.logger.log("Second call to stripdown state (pid={0}), continuing process".format(os.getpid()))
            return True
<|endoftext|>