Beispiel #1
0
def signup(request):
    if request.method == 'POST':
        print(request.POST)
        # username = request.POST.get('username')
        first_name = request.POST.get('firstname')
        last_name = request.POST.get('lastname')
        email = request.POST.get('email')
        phonenumber = request.POST.get('phonenumber')
        confirm_pass = request.POST.get('confirmpwd')
        password = request.POST.get('pwd')
        if password == confirm_pass:
            if User().objects.filter(email=email).exists():
                messages.info(request, 'Email Taken, Please try again')
                return redirect('app:signup')
            else:
                user = User()(email=email)
                user.first_name = first_name
                user.last_name = last_name
                user.phonenumber = phonenumber
                user.set_password(password)
                # user.password = password
                user.save()
                print(f"user saved. Instance is :{user}")
                return redirect('app:login')
        else:
            messages.error(request, 'Password mismatch')
            return redirect("app:signup")
    return render(request, "app/signup.html")
Beispiel #2
0
def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User().objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.profile.email_confirmed = True
        user.save()
        login(request, user)
        return redirect('qanda:home')
    else:
        return render(request, 'qanda/account_activation_invalid.html')
 def setUp(self):
     super(EventTests, self).setUp()
     app = "mezzanine_agenda"
     model = "event"
     self.url = urlresolvers.reverse("admin:%s_%s_add" % (app, model))
     self.user = User().objects.create_user(username="******",
                                            password='******')
     self.parent_event = Event.objects.create(
         start=datetime.datetime.today(),
         title="parent_event",
         user=self._user)
     self.category = EventCategory.objects.create(name="category")
     self.shop = ExternalShop.objects.create()
     file = tempfile.NamedTemporaryFile(suffix='.png')
     img = ImageFile(file, name=file.name)
     self.event = Event.objects.create(
         title="mon-evenement",
         start=datetime.datetime.strptime("2018-01-13", "%Y-%m-%d").date(),
         end=datetime.datetime.strptime("2018-01-18", "%Y-%m-%d").date(),
         user=self.user,
         status=CONTENT_STATUS_PUBLISHED,
         category=self.category,
         facebook_event=10,
         shop=self.shop,
         external_id=12,
         is_full=True,
         brochure=img,
         no_price_comments="no_price_comments",
         mentions="mentions",
         allow_comments=True,
         rank=2)
Beispiel #4
0
    def authenticate(self, request, **kwargs):
        try:
            if request.GET.get('next') == '/admin/' and request.POST.get(
                    "username"):
                print("we are here now")
                email = request.POST.get("username")
                password = request.POST.get("password")
                try:
                    print("getting here now")
                    user = User().objects.get(email=email)
                    print(user)
                    if user.is_superuser:
                        print("A Super User is logging in")
                        return user
                except User().DoesNotExist:
                    print("User does not exist or user is not a super user")
                    return None
        except:
            pass

        email = kwargs['email']
        password = kwargs['password']
        if email and password:
            # try:
            #     user = User().objects.get(email=email)
            #     print(f"the user password {user.password}")
            #     print(f"the user login password {password}")
            #     if user.check_password(password, user.password):
            #         return user
            #     # check = user.check_password(password)
            #     # print(check)
            #     # if check:
            #     # if password == user.password:
            #     #     return user
            # except User().DoesNotExist:
            #     return None
            try:
                user = User().objects.get(email=email)
            except User().DoesNotExist:
                return None
            else:
                if user.check_password(password):
                    return user
            return None
Beispiel #5
0
 def setUp(self):
     super(ArticleTests, self).setUp()
     app = "organization_magazine"
     model = "article"
     self.url = urlresolvers.reverse("admin:%s_%s_add" % (app, model))
     organization = Organization.objects.create()
     User().objects.create_user(username="******", password='******')
     self.department = Department.objects.create(organization=organization)
     self.user = User().objects.create_user(username="******", password="******")
     self.article = Article.objects.create(
         department=self.department,
         user=self.user
     )
Beispiel #6
0
 def setUp(self):
     user = User().objects.create_user(email="*****@*****.**",
                                       password="******",
                                       first_name='userfromT')
     user.save()
     user1 = User().objects.create_user(email="*****@*****.**",
                                        password="******",
                                        first_name='seconduserfromT')
     user1.save()
def RegisterUser(request):
    if request.method == 'POST':
        body = json.loads(request.body.decode('utf-8'))
        print(body)

        if (len(User().objects.filter(email=body["email"])) != 0):
            return HttpResponse(json.dumps({"field": "email"}), status=300)

        if (len(User().objects.filter(username=body["username"])) != 0):
            return HttpResponse(json.dumps({"field": "username"}), status=300)

        if (body["type"] == "Patient"):
            if (len(Patient.objects.filter(cpf=body["cpf"])) != 0):
                return HttpResponse(json.dumps({"field": "cpf"}), status=300)

        elif (body["type"] == "Medic"):
            if (len(Medic.objects.filter(cpf=body["cpf"])) != 0):
                return HttpResponse(json.dumps({"field": "cpf"}), status=300)
            if (len(Medic.objects.filter(crm=body["crm"])) != 0):
                return HttpResponse(json.dumps({"field": "crm"}), status=300)
            if (len(
                    Medic.objects.filter(
                        metamaskAccount=body["metamaskAccount"])) != 0):
                return HttpResponse(json.dumps({"field": "Metamask Account"}),
                                    status=300)
        else:
            if (len(Pharmacy.objects.filter(cnpj=body["cnpj"])) != 0):
                return HttpResponse(json.dumps({"field": "cnpj"}), status=300)

        try:
            user = User().objects.create_user(email=body["email"],
                                              username=body["username"],
                                              password=body["password"],
                                              type=body["type"])
        except Exception as err:
            print("Error registering user on database:" + str(err))
            return HttpResponse(status=500)

        if (body["type"] == "Patient"):
            try:
                patient = Patient(user=user, cpf=body["cpf"])
                patient.save()
            except Exception as err:
                print("Error registering new patient in patient table:" +
                      str(err))
                user.delete()
                return HttpResponse(status=500)

        elif (body["type"] == "Medic"):
            try:
                medic = Medic(user=user,
                              cpf=body["cpf"],
                              crm=body["crm"],
                              metamaskAccount=body["metamaskAccount"])
                medic.save()
            except Exception as err:
                print("Error registering new medic in medic table:" + str(err))
                user.delete()
                return HttpResponse(status=500)

        else:
            try:
                pharmacy = Pharmacy(user=user, cnpj=body["cnpj"])
                pharmacy.save()
            except Exception as err:
                print("Error registering new pharmacy in pharmacy table:" +
                      str(err))
                user.delete()
                return HttpResponse(status=500)

        login(request, user)

        success_url = reverse_lazy('home')
        return redirect(success_url)  #return user
class EventTests(TestCase):
    def setUp(self):
        super(EventTests, self).setUp()
        app = "mezzanine_agenda"
        model = "event"
        self.url = urlresolvers.reverse("admin:%s_%s_add" % (app, model))
        self.user = User().objects.create_user(username="******",
                                               password='******')
        self.parent_event = Event.objects.create(
            start=datetime.datetime.today(),
            title="parent_event",
            user=self._user)
        self.category = EventCategory.objects.create(name="category")
        self.shop = ExternalShop.objects.create()
        file = tempfile.NamedTemporaryFile(suffix='.png')
        img = ImageFile(file, name=file.name)
        self.event = Event.objects.create(
            title="mon-evenement",
            start=datetime.datetime.strptime("2018-01-13", "%Y-%m-%d").date(),
            end=datetime.datetime.strptime("2018-01-18", "%Y-%m-%d").date(),
            user=self.user,
            status=CONTENT_STATUS_PUBLISHED,
            category=self.category,
            facebook_event=10,
            shop=self.shop,
            external_id=12,
            is_full=True,
            brochure=img,
            no_price_comments="no_price_comments",
            mentions="mentions",
            allow_comments=True,
            rank=2)

    def test_event_display_for_everyone(self):
        self.client.logout()
        response = self.client.get(self.event.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "agenda/event_detail.html")
        self.client.login(username='******', password='******')
        response = self.client.get(self.event.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "agenda/event_detail.html")
        self.client.login(username='******', password='******')
        response = self.client.get(self.event.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "agenda/event_detail.html")

    @skip("No translation")
    def test_event_admin(self):
        self.client.logout()
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 302)
        self.client.login(username='******', password='******')
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 302)
        self.client.login(username='******', password='******')
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)

    @skip('No translation')
    def test_event_admin_creation(self):
        self.client.login(username='******', password='******')
        response = self.client.post(self.url, {
            "title": 'titre',
            "status": 2,
            "user": 1,
            "start_0": '30/04/2018'
        })
        self.assertEqual(response.status_code, 200)
        self.assertEqual(1, Event.objects.count())

    def test_event_admin_edition(self):
        self.client.logout()
        response = self.client.get(self.event.get_absolute_url())
        self.assertNotContains(response, "editable")
        self.client.login(username='******', password='******')
        response = self.client.get(self.event.get_absolute_url())
        self.assertContains(response, "editable")
        self.client.login(username='******', password='******')
        response = self.client.get(self.event.get_absolute_url())
        self.assertContains(response, "editable")

    def test_event_many_to_many_fields(self):
        event_price = EventPrice.objects.create(value=1, unit=1)
        self.event.prices.add(event_price)
        self.assertEqual(1, self.event.prices.all().count())
        event_price = EventPrice.objects.create(value=1, unit=1)
        self.event.prices.add(event_price)
        self.assertEqual(2, self.event.prices.all().count())
        event_price = EventPrice.objects.create(value=1, unit=1)
        self.event.prices.add(event_price)
        self.assertEqual(3, self.event.prices.all().count())

    def test_event_previous_next_date(self):
        next_event = Event.objects.create(title="mon-futur-evenement",
                                          start=datetime.datetime.strptime(
                                              "2018-01-14", "%Y-%m-%d").date(),
                                          user=self._user,
                                          status=CONTENT_STATUS_PUBLISHED)
        previous_event = Event.objects.create(title="mon-evenement-passe",
                                              start=datetime.datetime.strptime(
                                                  "2018-01-12",
                                                  "%Y-%m-%d").date(),
                                              user=self._user,
                                              status=CONTENT_STATUS_PUBLISHED)
        self.assertEqual(self.event.get_previous_by_start_date(),
                         previous_event)
        self.assertEqual(self.event.get_next_by_start_date(), next_event)

    def test_event_start_end_date(self):
        event = Event(start=datetime.datetime.today(),
                      title="parent_event",
                      user=self._user,
                      end=datetime.datetime.strptime("2018-01-14",
                                                     "%Y-%m-%d").date())
        self.assertRaises(ValidationError, event.save())

    def test_event_creation(self):
        self.assertTrue(isinstance(self.event, Event))
        self.assertEqual(self.event.title, "mon-evenement")
        self.assertEqual(
            self.event.start,
            datetime.datetime.strptime("2018-01-13", "%Y-%m-%d").date())
        self.assertEqual(
            self.event.end,
            datetime.datetime.strptime("2018-01-18", "%Y-%m-%d").date())
        self.assertEqual(self.event.user, self.user)
        self.assertEqual(self.event.status, CONTENT_STATUS_PUBLISHED)
        self.assertEqual(self.event.category, self.category)
        self.assertEqual(self.event.facebook_event, 10)
        self.assertEqual(self.event.shop, self.shop)
        self.assertEqual(self.event.external_id, 12)
        self.assertTrue(self.event.is_full)
        self.assertEqual(self.event.no_price_comments, "no_price_comments")
        self.assertEqual(self.event.mentions, "mentions")
        self.assertTrue(self.event.allow_comments)
        self.assertEqual(self.event.rank, 2)

    def test_event_retrieval(self):
        self.assertTrue(self.event in Event.objects.all())
        self.assertTrue(self.event in Event.objects.filter(
            status=CONTENT_STATUS_PUBLISHED))
        self.assertTrue(self.event in Event.objects.filter(user=self.user))
        self.assertTrue(self.event in Event.objects.filter(
            start=datetime.datetime.strptime("2018-01-13", "%Y-%m-%d").date()))
        self.assertTrue(self.event in Event.objects.filter(
            end=datetime.datetime.strptime("2018-01-18", "%Y-%m-%d").date()))
        self.assertTrue(self.event in Event.objects.filter(
            category=self.category))
        self.assertTrue(self.event in Event.objects.filter(facebook_event=10))
        self.assertTrue(self.event in Event.objects.filter(shop=self.shop))
        self.assertTrue(self.event in Event.objects.filter(external_id=12))
        self.assertTrue(self.event in Event.objects.filter(is_full=True))
        self.assertTrue(self.event in Event.objects.filter(
            no_price_comments="no_price_comments"))
        self.assertTrue(self.event in Event.objects.filter(
            mentions="mentions"))
        self.assertTrue(self.event in Event.objects.filter(
            allow_comments=True))
        self.assertTrue(self.event in Event.objects.filter(rank=2))

    def test_event_update(self):
        self.event.title = "my-event"
        self.assertEqual(1,
                         Event.objects.filter(title="mon-evenement").count())
        self.assertEqual(0, Event.objects.filter(title="my-event").count())
        self.event.save()
        self.assertEqual(0,
                         Event.objects.filter(title="mon-evenement").count())
        self.assertEqual(1, Event.objects.filter(title="my-event").count())

    def test_event_deletion(self):
        event_block = EventBlock.objects.create(event=self.event)
        event_image = EventImage.objects.create(event=self.event)
        event_departement = EventDepartment.objects.create(event=self.event)
        event_person = EventPerson.objects.create(event=self.event)
        link_type = LinkType.objects.create(name="test link")
        event_link = EventLink.objects.create(event=self.event,
                                              link_type=link_type)
        event_playlist = EventPlaylist.objects.create(event=self.event)
        event_period = EventPeriod.objects.create(event=self.event)
        event_training = EventTraining.objects.create(event=self.event)
        event_related_title = EventRelatedTitle.objects.create(
            event=self.event)
        event_dynamic_content = DynamicContentEvent.objects.create(
            event=self.event)
        self.event.delete()
        self.assertTrue(event_block in EventBlock.objects.filter(
            event__isnull=True))
        self.assertTrue(event_image in EventImage.objects.filter(
            event__isnull=True))
        self.assertTrue(event_departement in EventDepartment.objects.filter(
            event__isnull=True))
        self.assertTrue(event_person in EventPerson.objects.filter(
            event__isnull=True))
        self.assertTrue(event_link in EventLink.objects.filter(
            event__isnull=True))
        self.assertTrue(event_playlist in EventPlaylist.objects.filter(
            event__isnull=True))
        self.assertTrue(event_period in EventPeriod.objects.filter(
            event__isnull=True))
        self.assertTrue(event_training in EventTraining.objects.filter(
            event__isnull=True))
        self.assertTrue(
            event_related_title in EventRelatedTitle.objects.filter(
                event__isnull=True))
        self.assertFalse(
            event_dynamic_content in DynamicContentEvent.objects.all())
        self.assertFalse(self.event in Event.objects.all())

    def test_event_fk_deletion(self):
        self.parent_event.delete()
        self.category.delete()
        self.shop.delete()
        self.assertTrue(self.event in Event.objects.filter(
            parent__isnull=True))
        self.assertTrue(self.event in Event.objects.filter(
            category__isnull=True))
        self.assertTrue(self.event in Event.objects.filter(shop__isnull=True))
        self.user.delete()
        self.assertFalse(self.event in Event.objects.all())
Beispiel #9
0
def send_email(user_id, subject, message):
    from django.contrib.auth import get_user_model as User
    user = User().objects.get(id=user_id)
    user.email_user(subject, message)
Beispiel #10
0
def add_admin(request):
    users = request.user
    if request.method == 'POST':
        first_name = request.POST.get('firstname')
        last_name = request.POST.get('lastname')
        email = request.POST.get('email')
        phonenumber = request.POST.get('phonenumber')
        pass1 = request.POST.get('pass1')
        pass2 = request.POST.get('pass2')
        if pass1 == pass2:
            password = pass1
            if User().objects.filter(email=email).exists():
                messages.info(request, 'Email already exists.')
            else:
                user = User()(email=email)
                user.first_name = first_name
                user.last_name = last_name
                user.phonenumber = phonenumber
                user.set_password(password)
                user.is_admin = True
                user.save(commit=False)
                admin = Admin.objects.create(user=user)
                user.save()
                admin.save()
                messages.success(request, "Admin successfully added")
            #check logged in user and render the current add-staff page for the proper user. I wouldn't want to redirect admin to staff signup page
            return render(request, "len_admin/add_admin.html")
        else:
            messages.error(request, 'Passwords do not match')
    elif request.method == 'GET':
        try:
            Admin.objects.get(
                user=users.id)  #checks if the logged in user is an Admin
            return render(request, "len_admin/add_admin.html")
        except ObjectDoesNotExist:
            return redirect(request.META.get('HTTP_REFERER', '/'))
Beispiel #11
0
class ArticleTests(TestCase):

    def setUp(self):
        super(ArticleTests, self).setUp()
        app = "organization_magazine"
        model = "article"
        self.url = urlresolvers.reverse("admin:%s_%s_add" % (app, model))
        organization = Organization.objects.create()
        User().objects.create_user(username="******", password='******')
        self.department = Department.objects.create(organization=organization)
        self.user = User().objects.create_user(username="******", password="******")
        self.article = Article.objects.create(
            department=self.department,
            user=self.user
        )

    def test_article_many_to_many_fields(self):
        topic = Topic.objects.create()
        self.article.topics.add(topic)
        self.assertEqual(1, self.article.topics.all().count())
        topic = Topic.objects.create()
        self.article.topics.add(topic)
        self.assertEqual(2, self.article.topics.all().count())
        topic = Topic.objects.create()
        self.article.topics.add(topic)
        self.assertEqual(3, self.article.topics.all().count())

    def test_article_fk_deletion(self):
        self.department.delete()
        self.user.delete()
        self.assertFalse(self.article in Article.objects.all())

    def test_article_creation(self):
        self.assertTrue(isinstance(self.article, Article))
        self.assertEquals(self.article.department, self.department)
        self.assertEquals(self.article.user, self.user)

    def test_article_retrieval(self):
        self.assertTrue(
            self.article in Article.objects.filter(department=self.department)
        )
        self.assertTrue(self.article in Article.objects.filter(user=self.user))
        self.assertTrue(self.article in Article.objects.all())

    def test_article_update(self):
        self.article.department = None
        self.assertEqual(
            1,
            Article.objects.filter(department=self.department).count()
        )
        self.assertEqual(
            0,
            Article.objects.filter(department__isnull=True).count()
        )
        self.article.save()
        self.assertEqual(
            0,
            Article.objects.filter(department=self.department).count()
        )
        self.assertEqual(1, Article.objects.filter(department__isnull=True).count())

    def test_article_deletion(self):
        article_image = ArticleImage.objects.create(article=self.article)
        article_related_title = ArticleRelatedTitle.objects.create(article=self.article)
        article_playslist = ArticlePlaylist.objects.create(article=self.article)
        article_person_list_block_inline = ArticlePersonListBlockInline.objects.create(
            article=self.article
        )
        dynamic_content_article = DynamicContentArticle.objects.create(
            article=self.article
        )
        self.article.delete()
        self.assertTrue(
            article_image in ArticleImage.objects.filter(
                article__isnull=True
            )
        )
        self.assertTrue(
            article_related_title in ArticleRelatedTitle.objects.filter(
                article__isnull=True
            )
        )
        self.assertTrue(
            article_playslist in ArticlePlaylist.objects.filter(
                article__isnull=True
            )
        )
        self.assertTrue(
            article_person_list_block_inline in ArticlePersonListBlockInline.objects
            .filter(article__isnull=True)
        )
        self.assertFalse(
            dynamic_content_article in DynamicContentArticle.objects
            .filter(article__isnull=True)
        )
        self.assertFalse(self.article in Article.objects.all())

    def test_article_display_for_everyone(self):
        self.client.logout()
        response = self.client.get(self.article.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "magazine/article/article_detail.html")
        self.client.login(username='******', password='******')
        response = self.client.get(self.article.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "magazine/article/article_detail.html")
        self.client.login(username='******', password='******')
        response = self.client.get(self.article.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "magazine/article/article_detail.html")

    def test_article_admin_edition(self):
        self.client.logout()
        response = self.client.get(self.article.get_absolute_url())
        self.assertNotContains(response, "editable")
        self.client.login(username='******', password='******')
        response = self.client.get(self.article.get_absolute_url())
        self.assertNotContains(response, "editable")
        self.client.login(username='******', password='******')
        response = self.client.get(self.article.get_absolute_url())
        self.assertContains(response, "editable")
        self.client.login(username='******', password='******')
        response = self.client.get(self.article.get_absolute_url())
        self.assertContains(response, "editable")

    def test_article_admin_creation(self):
        nmb = Article.objects.count()
        self.client.login(username='******', password='******')
        response = self.client.post(
            self.url,
            {
                "title": 'titre',
                "status": 2,
                "user": self.user.id,
                'article_person_list_block_inlines-INITIAL_FORMS': '0',
                'article_person_list_block_inlines-TOTAL_FORMS': '1',
                'dynamic_content_articles-INITIAL_FORMS': '0',
                'dynamic_content_articles-TOTAL_FORMS': '1',
                'images-INITIAL_FORMS': '0',
                'images-TOTAL_FORMS': '1',
                'playlists-INITIAL_FORMS': '0',
                'playlists-TOTAL_FORMS': '1',
                'related_title-INITIAL_FORMS': '0',
                'related_title-TOTAL_FORMS': '1',
                'allow_comments': 'on',
                'gen_description': 'on',
                'in_sitemap': 'on',
                'content': 'yes',
                'csrfmiddlewaretoken': 'ahGmaJGV8YSLUM8Vuvlzt9DOE8Bz9IxD'
            }
        )
        self.assertEqual(response.status_code, 302)
        self.assertEqual(nmb + 1, Article.objects.count())
Beispiel #12
0
from django.contrib.auth import get_user_model as USER, get_backends
from . import methods

User = USER()

User.all_permissions = methods.User.all_permissions