Beispiel #1
0
def api_registration_view(request):
    logger = logging.getLogger(__name__)
    data = {}
    email = request.data.get('email').lower()
    role = request.data.get('role')
    if validate_email(email) is not None:
        data['error_message'] = 'That email is already in use.'
        data['response'] = 'Error'
        return Response(data)

    instaAccount = request.data.get('instaAccount')
    if validate_instaacount(
            instaAccount
    ) is not None:  # TODO: Hay que corregir la funcion validate_instaacount()
        data['error_message'] = 'That instagram account is already in use.'
        data['response'] = 'Error'
        return Response(data)

    serializer = RegistrationSerializer(data=request.data)

    if request.data.get('password') != request.data.get('password2'):
        data['error_message'] = 'Passwords must match'
        data['response'] = 'Error'
        return Response(data)

    if serializer.is_valid():

        user = serializer.save()
        if (role == '2'):
            company = Company(user=user,
                              instaAccount=request.data.get('instaAccount'),
                              phone=request.data.get('phone'))
            company.save()
        elif (role == '1'):
            if (request.data.get('phone') is None):
                profile = Profile(
                    user=user, instaAccount=request.data.get('instaAccount'))
                profile.save()
            else:
                profile = Profile(
                    user=user,
                    instaAccount=request.data.get('instaAccount'),
                    phone=request.data.get('phone')).save()
        data['response'] = 'user registered successfuly'
        data['email'] = user.email
        data['full_name'] = user.full_name
        data['active'] = user.active
        data['staff'] = user.staff
        data['admin'] = user.admin
        data['instaAccount'] = instaAccount
        data['phone'] = request.data.get('phone')
        data['role'] = role
        data['timestamp'] = user.timestamp
        token = Token.objects.get(user=user).key
        data['token'] = token
        logger.error(data)
    else:
        data = serializer.errors
        return Response(data)
    return Response(data, status=status.HTTP_201_CREATED)
Beispiel #2
0
 def test_company_save_userprofile(self):
     """
     Tests whether the save method for the Company class properly
     saves the user profile along with the Company object.
     """
     c = Company(**self.company_data)
     c.save()
     self.assertEquals(
             c.userprofile.user.username,
             self.company_data['username'])
Beispiel #3
0
    def test_company_from_member_cast(self):
        """
        Tests whether the cast method of the Member class returns the
        Company object properly.
        """
        c = Company(**self.company_data)
        c.save()
        pk = c.pk
        del c

        m = Member.objects.get(pk=pk)
        self.assertIsInstance(m.cast(), Company)
Beispiel #4
0
def company_signUp(request):
    if request.user.is_authenticated:
        return redirect('home')

    username = request.POST['walletAddress']
    compName = request.POST['compName']
    user = User.objects.create_user(username=username)
    company = Company(user=user, name=compName)
    company.save()
    messages = company
    context = {'message': messages}
    return HttpResponse(status=201)
Beispiel #5
0
 def test_company_save_group(self):
     """
     Tests whether the save method for the Company class properly
     initializes the user's group to Companies.
     """
     c = Company(**self.company_data)
     c.save()
     # Just one default group
     self.assertEqual(
             c.userprofile.user.groups.all().count(),
             1,
             "Company not associated with one and only one group.")
     self.assertEqual(
             c.userprofile.user.groups.all()[0].name,
             u'Companies',
             "Company not associated with 'Companies' group.")
Beispiel #6
0
    def save(self):

        user = super(CompanySignupFormExtra, self).save()

        company_name = self.cleaned_data['company_name']
        creator_id = user.id
        company = Company(name=company_name, creator_id=creator_id)
        company.save()
        company.id

        user_profile = user.get_profile()
        user_profile.account_type = '2'
        user_profile.role = '2'
        user_profile.company_id = company.id
        user_profile.save()

        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

        return user
Beispiel #7
0
    def test_company_username_property(self):
        """
        Tests whether the parent class' username property works from
        the Company class.
        """
        c = Company(**self.company_data)
        c.save()
        self.assertEquals(
                c.username,
                self.company_data['username'])

        new_username = '******'
        c.username = new_username
        c.save()
        self.assertEquals(
                c.username,
                new_username)

        pk = c.pk
        del c
        c = Company.objects.get(pk=pk)
        self.assertEquals(c.username, new_username)
def save(self, Company):
    new_company = Company(Company)
    new_company.save()

    new_user = User(
        email=self.validated_data['email'],
        first_name=self.validated_data['first_name'],
        last_name=self.validated_data['last_name'],
        role=self.validated_data['role'],
        staff=False,
        admin=False,
        active=True,
    )
    password = self.validated_data['password']
    password2 = self.validated_data['password2']
    if(password != password2):
        raise serializers.ValidationError({'password:'******'Passwords must match'})
    name = self.validated_data['first_name'] + ' ' + self.validated_data['last_name']
    new_user.full_name = name
    new_user.set_password(password)
    # Generate EmailConfirmation
    new_user.save()
    self.generateConfimationKey(new_user)
    return new_user
def register(request):

    if request.method == 'POST':
        # Get form values
        company_name = request.POST['company_name']
        email = request.POST['email']
        phone = request.POST['phone']
        password = request.POST['password']

        if (not company_name) or (not email) or (not phone) or (not password):
            return JsonResponse({
                'message': "please fill in the form",
                'type': "error",
            })

        # Check username
        if User.objects.filter(username=company_name).exists():
            return JsonResponse({
                'message': "name already used",
                'type': "error",
            })
        else:
            if User.objects.filter(email=email).exists():
                return JsonResponse({
                    'message': "email already used",
                    'type': "error",
                })

            else:
                # create companiesRelatedFiles which will containg embeddings folder and photos
                companiesRelatedFilesPath = os.getcwd(
                ) + r'/companiesRelatedFiles'
                # create the embeddings folder that will contain embeddings for each company
                # it is created with the first company then it checks if exists to make it or not and it should be exits
                embeddingsPath = companiesRelatedFilesPath + r'/embeddings'
                # create the students photos folder that will contain photos for each company
                # it is created with the first company then it checks if exists to make it or not and it should be exits
                studentsPhotosPath = companiesRelatedFilesPath + r'/studentsPhotos'
                # create the lectures photos folder that will contain photos for each company
                # it is created with the first company then it checks if exists to make it or not and it should be exits
                lecturesPhotosPath = companiesRelatedFilesPath + r'/lecturesPhotos'
                # create the company folder inside the embeddings , photos folder , it will have company name
                # we check if the folders exist for safety
                companyEmbeddingsPath = embeddingsPath + r'/' + company_name
                companyStudentsPhotosPath = studentsPhotosPath + r'/' + company_name
                companyLecturesPhotosPath = lecturesPhotosPath + r'/' + company_name
                try:
                    if not (os.path.isdir(companiesRelatedFilesPath)):
                        os.mkdir(companiesRelatedFilesPath)
                        if not (os.path.isdir(embeddingsPath)):
                            os.mkdir(embeddingsPath)
                            if not (os.path.isdir(studentsPhotosPath)):
                                os.mkdir(studentsPhotosPath)
                                if not (os.path.isdir(lecturesPhotosPath)):
                                    os.mkdir(lecturesPhotosPath)

                    if not (os.path.isdir(companyEmbeddingsPath)):
                        os.mkdir(companyEmbeddingsPath)
                        if not (os.path.isdir(companyStudentsPhotosPath)):
                            os.mkdir(companyStudentsPhotosPath)
                            if not (os.path.isdir(companyLecturesPhotosPath)):
                                os.mkdir(companyLecturesPhotosPath)

                                # Looks good
                                user = User.objects.create_user(
                                    username=company_name,
                                    password=password,
                                    email=email)
                                user.save()

                                company = Company(
                                    user=user,
                                    name=company_name,
                                    email=email,
                                    phone=phone,
                                    embeddingsPath=companyEmbeddingsPath,
                                    studentsPhotosPath=
                                    companyStudentsPhotosPath,
                                    lecturesPhotosPath=companyLecturesPhotosPath
                                )

                                company.save()

                                return JsonResponse({
                                    'type': "success",
                                    'url': "login",
                                })
                except:
                    # get user and company objects if exist to delete them in case of an error
                    user = User.objects.get(username=company_name,
                                            password=password,
                                            email=email)
                    company = Company.objects.get(user=user,
                                                  name=company_name,
                                                  email=email,
                                                  phone=phone)

                    if user is not None:
                        user.delete()
                    if company is not None:
                        company.delete()
                        # delete company associated filess
                        shutil.rmtree(companyEmbeddingsPath,
                                      ignore_errors=False,
                                      onerror=None)
                        shutil.rmtree(companyStudentsPhotosPath,
                                      ignore_errors=False,
                                      onerror=None)
                        shutil.rmtree(companyLecturesPhotosPath,
                                      ignore_errors=False,
                                      onerror=None)

                    return render(request, 'error/error.html')
    else:
        return render(request, 'accounts/register.html')