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")
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 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 setUp(self): self.client = Client() self.admin_user = User().objects.create_superuser( email='*****@*****.**', password='******' ) self.client.force_login(self.admin_user) self.user = User().objects.create_user( email='*****@*****.**', password='******', name='Test 010010 2020' )
class Profile(models.Model): user = models.OneToOneField(User(), on_delete=models.CASCADE, primary_key=True) email_confirmed = models.BooleanField(default=False) objects = ProfileManager() def __str__(self): return f'{self.user}' @receiver(post_save, sender=User()) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save()
def setUp(self): super(URLTests, self).setUp() self.basic_user = User().objects.create_user(username="******", password='******') """ This simulate an event creation on front, a keyword is created when keywords field is filled """ keyword = Keyword.objects.create(title="scientific event") self.event_tagged = Event.objects.create( title="mon-evenement", start=datetime.date.today() + datetime.timedelta(days=1), user=self.basic_user, keywords_string="scientific event") AssignedKeyword.objects.create(keyword_id=keyword.id, content_object=self.event_tagged) Season.objects.create( title="s1", start=datetime.datetime.strptime("2016-06-01", "%Y-%m-%d"), end=datetime.datetime.strptime("2016-05-31", "%Y-%m-%d")) Season.objects.create( title="s2", start=datetime.datetime.strptime("2017-06-01", "%Y-%m-%d"), end=datetime.datetime.strptime("2017-05-31", "%Y-%m-%d")) Season.objects.create( title="s3", start=datetime.datetime.strptime("2018-06-01", "%Y-%m-%d"), end=datetime.datetime.strptime("2018-05-31", "%Y-%m-%d")) self.event_archive = Event.objects.create( title="past_event", start=datetime.datetime.strptime("2017-04-02", "%Y-%m-%d"), user=self.basic_user)
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 setUp(self): super(PlaylistTests, self).setUp() self.user = User().objects.create_user(username="******", password='******') self.playlist = Playlist.objects.create(type="audio") app = "organization_media" model = "playlist" self.url = urlresolvers.reverse("admin:%s_%s_add" % (app, model))
def test_create_user_with_email_successful(self): """Test creating a new user with an email is successful""" email = "*****@*****.**" password = '******' user = User().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password)
class Meta: model = User() fields = ('email', 'password', 'name') extra_kwargs = { 'password': { 'write_only': True, 'min_length': 5 }, }
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
def test_sign_up(self): url = reverse("signup") data = { 'email': '*****@*****.**', 'password': '******', 'first_name': 'userfromT' } # resp = self.client.post(path=url, data=data, format='json') # self.assertEqual(resp.status_code,status.HTTP_201_CREATED) self.assertEqual(User().objects.count(), 1)
class Votable(models.Model): UP = 1 DOWN = -1 VALUE_CHOICES = ((UP, '👍'), (DOWN, '👎')) value = models.SmallIntegerField(choices=VALUE_CHOICES) user = models.ForeignKey(User(), on_delete=models.CASCADE) voten_on = models.DateTimeField(auto_now=True) class Meta: abstract = True
def profile(request, user_pk): """ 1. 내가 쓴 모든 글 출력 2. 내가 쓴 댓글들 출력 3. 작성자를 눌렀을때 프로필로 이동 """ user = get_object_or_404(User(), pk=user_pk) ctx = { 'profile_user': user, } return render(request, 'accounts/profile.html', ctx)
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 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', '/'))
class Publishable(models.Model): user = models.ForeignKey(User(), on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(editable=False) modified = models.DateTimeField() def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Publishable, self).save(*args, **kwargs) class Meta: abstract = True
def test_login_refresh_access(self): url = reverse("token_obtain_pair") data = {'email': '*****@*****.**', 'password': '******'} resp = self.client.post(path=url, data=data, format='json') refresh = resp.data["refresh"] # print(resp.data) self.assertIn('refresh', resp.data) self.assertIn('access', resp.data) self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(User().objects.count(), 1) url = reverse("token_refresh") data = {"refresh": refresh} resp = self.client.post(path=url, data=data) # print(resp.data) self.assertIn('access', resp.data)
def get_context_data(self, **kwargs): user = User().objects.get(username=self.kwargs['username']) ctx = super(UserDetail, self).get_context_data(**kwargs) tab = self.request.GET.get('tab', None) ctx['answers'] = Answer.objects.all_with_score() \ .filter(user=user).order_by('-score') ctx['questions'] = \ Question.objects.all_with_relations_and_score() \ .filter(user=user).order_by('-score') # User entered no tab query or invalid quer if (tab == 'None' or (tab != 'questions' and tab != 'answers')): ctx['answers'] = ctx['answers'][:5] ctx['questions'] = ctx['questions'][:5] return ctx
def setUp(self): super(JobResponseTests, self).setUp() app = "organization_job" model = "joboffer" self.user = User().objects.create_user(username="******", password='******') self.file = SimpleUploadedFile('letter.txt'.encode(), 'content'.encode()) self.job_offer = JobOffer.objects.create(email="*****@*****.**", type="internship") self.job_response = JobResponse.objects.create( first_name="jean", last_name="dupont", email="*****@*****.**", message="I want this job", curriculum_vitae=self.file, cover_letter=self.file, job_offer=self.job_offer) self.url = urlresolvers.reverse("admin:%s_%s_change" % (app, model), args=(self.job_offer.id, ))
class SignUp(viewsets.ModelViewSet): ''' create: Register\n Uses the email and password provided to Register a User ''' serializer_class = UsersSerializer queryset = User().objects.all() def perform_create(self, serializer): serializer = UsersSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) data = { 'refresh': str(refresh), 'access': str(refresh.access_token), } data[id] = user.id return Response(data, status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class FreeAgentBid(models.Model): free_agent = models.ForeignKey(AvailableFreeAgent, on_delete=models.CASCADE) bid_time_stamp = models.DateTimeField() bid_team = models.ForeignKey(Franchise, on_delete=models.PROTECT) bid_length = models.IntegerField() bid_salary = models.IntegerField() user = models.ForeignKey(User(), on_delete=models.PROTECT) class Meta: ordering = ['free_agent', '-bid_time_stamp'] def __str__(self): return '{}, {}-{}-Free Agent Bid'.format(self.free_agent.last_name, self.free_agent.first_name, self.bid_time_stamp) def is_high_bid(self): if self.bid_time_stamp == self.free_agent.bid_time_stamp: return True else: return False
class UserDetail(CacheVaryOnCookieMixin, DetailView): model = User() slug_field = "username" slug_url_kwarg = "username" template_name = 'qanda/user_detail.html' def get_context_data(self, **kwargs): user = User().objects.get(username=self.kwargs['username']) ctx = super(UserDetail, self).get_context_data(**kwargs) tab = self.request.GET.get('tab', None) ctx['answers'] = Answer.objects.all_with_score() \ .filter(user=user).order_by('-score') ctx['questions'] = \ Question.objects.all_with_relations_and_score() \ .filter(user=user).order_by('-score') # User entered no tab query or invalid quer if (tab == 'None' or (tab != 'questions' and tab != 'answers')): ctx['answers'] = ctx['answers'][:5] ctx['questions'] = ctx['questions'][:5] return ctx
class QuestionSubscription(models.Model): user = models.ForeignKey(User(), on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) objects = QuestionSubscriptionManager() ANSWER_EMAIL_TEMPLATE = 'email/new_answer.html' def email_new_answer(self): subject = f"New answer on '{self.question.title}'" message = render_to_string( self.ANSWER_EMAIL_TEMPLATE, { 'domain': settings.EMAIL_HOST, 'user': self.user, 'question': self.question }) tasks.send_email.delay(self.user.id, subject, message) def __str__(self): return f'{self.user} | {self.question.title}' class Meta: unique_together = ('user', 'question')
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
def test_create_new_super_user(self): """Test create new super user""" user = User().objects.create_superuser('*****@*****.**', 'test123') self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)
def test_new_user_invalid_email(self): """New User Email Validation Test""" with self.assertRaises(ValueError): User().objects.create_user(None, 'test@123')
def test_new_user_email_nomalized(self): """New user email is normalized""" email = '*****@*****.**' user = User().objects.create_user(email, 'test123') self.assertEqual(user.email, email.lower())
def test_exam_livetime_process(self): #Logging in the user created in the setup method new_user = User().objects.get(email="*****@*****.**") url = reverse("token_obtain_pair") data = {"email": "*****@*****.**", "password": "******"} resp = self.client.post(path=url, data=data, format='json') self.assertIn('refresh', resp.data) self.assertNotIn('token', resp.data) self.assertEqual(resp.status_code, status.HTTP_200_OK) # THE following requests are made without Authentication #POST: create an exam for the cuurent user without Authentication ie Authorization Header access = resp.data["access"] url = reverse("all_exams") user = UserSerializer(new_user) data = { "user": user.data, "instructions": "Test instructions for test exam", "title": "Test title for test exam", "exam_time": "18:00:00" } resp = self.client.post(path=url, data=data, format='json') self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) resp = self.client.get(path=url) self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) # POST: create an exam for the cuurent user with wrong authentication( wrong access token ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='Bearer ' + 'incorrect credentials') resp = client.get(url, data=data) self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) #POST: create an exam for the cuurent user with the earlier generated access token client.credentials(HTTP_AUTHORIZATION=f'Bearer {access}') resp = client.post(path=url, data=data, format='json') self.assertEqual(resp.status_code, status.HTTP_201_CREATED) resp = client.get(path=url) self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(Exam.objects.count(), 1) self.assertEqual(Exam.objects.filter(user=new_user).count(), 1) # PERMISSIONS # we need to create a second user and try to update/retrive/delete the old users exam # This user will be used to check for object level permissions second_user = User().objects.get(email="*****@*****.**") url = reverse("token_obtain_pair") data = {"email": "*****@*****.**", "password": "******"} resp = self.client.post(path=url, data=data, format='json') second_user_access = resp.data["access"] self.assertIn('refresh', resp.data) self.assertNotIn('token', resp.data) self.assertEqual(resp.status_code, status.HTTP_200_OK) url = reverse("all_exams") client.credentials(HTTP_AUTHORIZATION=f'Bearer {second_user_access}') resp = client.get(path=url) # *********************** #Issue: this get request above is returning all exams in the db instead of only the users exams # *********************** self.assertEqual(resp.status_code, status.HTTP_200_OK) print(resp.data)
class Meta: model = User() extra_kwargs = {'password': {'write_only': True}} fields = ["id", "email", "password"]