def test_tokens_can_be_manually_blacklisted(self): token = RefreshToken.for_user(self.user) # Should raise no exception RefreshToken(str(token)) self.assertEqual(OutstandingToken.objects.count(), 1) # Add token to blacklist blacklisted_token, created = token.blacklist() # Should not add token to outstanding list if already present self.assertEqual(OutstandingToken.objects.count(), 1) # Should return blacklist record and boolean to indicate creation self.assertEqual(blacklisted_token.token.jti, token["jti"]) self.assertTrue(created) with self.assertRaises(TokenError) as e: # Should raise exception RefreshToken(str(token)) self.assertIn("blacklisted", e.exception.args[0]) # If blacklisted token already exists, indicate no creation through # boolean blacklisted_token, created = token.blacklist() self.assertEqual(blacklisted_token.token.jti, token["jti"]) self.assertFalse(created) # Should add token to outstanding list if not already present new_token = RefreshToken() blacklisted_token, created = new_token.blacklist() self.assertEqual(blacklisted_token.token.jti, new_token["jti"]) self.assertTrue(created) self.assertEqual(OutstandingToken.objects.count(), 2)
def test_list_success_my_following_users(self): """ Followingモデルの一覧取得APIへのGETリクエスト (正常系:自分のフォローしているユーザー情報の一覧取得) """ # JWT認証のトークン取得 token = str(RefreshToken.for_user(self.user).access_token) # ログイン self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token) # リクエストを実行 response = self.client.get( self.TARGET_URL, format='json', ) # JSONデータの読み込み content = json.loads(response.content) # ステータスコードをテスト self.assertEqual(response.status_code, 200) # 予想されるデータを取得 my_following_objects = Following.objects.filter( followed_by=self.user, ) # シリアライザのインスタンスを作成 serializer = FollowingSerializer( my_following_objects, many=True, ) # データ内容をテスト self.assertEqual(content, serializer.data)
def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) user.is_active = False user.save() token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://' + current_site + relativeLink + "?token=" + str( user.id) email_body = 'Hi '+user.email + \ ' Use the link below to verify your email \n' + absurl data = { 'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email' } Util.send_email(data) return Response(serializer.data, status=status.HTTP_201_CREATED)
def post(self, request: Request) -> Response: """Authenticate or Re-authtenticate a User.""" data = json_or_raise(request) user_serd = LoginSerializer(data=data) if not user_serd.is_valid(): return Response(user_serd.errors, status=status.HTTP_400_BAD_REQUEST) user_data = user_serd.data user_query = User.objects.filter(username=user_data["username"]) if not user_query: return Response( "Either the user or the password doesn't match", status=status.HTTP_400_BAD_REQUEST, ) user: User = user_query[0] if not user.check_password(user_data["password"]): return Response( "Either the user or the password doesn't match", status=status.HTTP_400_BAD_REQUEST, ) return Response( {"token": str(RefreshToken.for_user(user).access_token)}, status=status.HTTP_201_CREATED, )
def validate(self, data): email = data.get('email', None) password = data.get('password', None) if email is None: raise serializers.ValidationError("Email address was not provided for login") if password is None: raise serializers.ValidationError("Password was not provided") user = authenticate(username=email, password=password) if user is None: raise serializers.ValidationError("A user with this email and password was not found") if not user.is_active: raise serializers.ValidationError("The user has been deactivated") tokens = RefreshToken.for_user(user) return { 'email': user.email, 'refresh': str(tokens), 'access': str(tokens.access_token), }
def post(self, request, *args, **kwargs): try: email = request.data['email'].lower() password_date = datetime.datetime.now() user_instance = authenticate(username=email, password=request.data['code']) if user_instance is not None: delta = password_date.replace( tzinfo=None) - user_instance.password_change_date.replace( tzinfo=None) if delta.seconds > 300: return Response({ 'status': status.HTTP_408_REQUEST_TIMEOUT, }) else: refresh = RefreshToken.for_user(user_instance) user_instance.password_change_date = datetime.datetime( 1970, 1, 1) user_instance.set_password(pg.generate()) user_instance.save() return Response({ 'status': status.HTTP_200_OK, 'tokens': { 'refresh': str(refresh), 'access': str(refresh.access_token), } }) else: return Response({ 'status': status.HTTP_403_FORBIDDEN, }) except Exception: return Response({ 'status': status.HTTP_400_BAD_REQUEST, })
def post(self, request, format="json"): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data new_user = User.objects.get(email=json['email']) token = RefreshToken.for_user(user).access_token current_site = "sparklehood.web.app" relativeLink = "/verifyemail/" absurl = 'https://' + current_site + relativeLink + str(token) email_body = "Hi " + new_user.user_name + \ " Use the Link below to verify your email \n" + absurl data = { 'email_body': email_body, 'to_email': new_user.email, 'email_subject': 'Verify Your Email' } Util.send_email(data) return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def validate(self, attrs): email = attrs.get('email', '') password = attrs.get('password', '') user_obj_email = User.objects.filter(email=email).first() if user_obj_email: user = auth.authenticate(email=user_obj_email.email, password=password) if user_obj_email.auth_provider != 'email': raise AuthenticationException( detail='Please continue your login using ' + filtered_user_by_email[0].auth_provider) if not user: raise AuthenticationException('Invalid credentials. Try again') if not user.is_active: raise AuthenticationException( 'Account disabled. contact admin') if not user.is_verified: email = user.email token = RefreshToken.for_user(user).access_token current_site = self.context.get('current_site') relative_link = reverse('email-verify') absurl = 'https://' + current_site + relative_link + "?token=" + str( token) email_body = 'Hi ' + user.email + '. Use link below to verify your email \n' + absurl data = { 'email_body': email_body, 'email_subject': 'Verify your email', 'to_email': user.email } Util.send_email(data) raise AuthenticationException( 'Email is not verified, A Verification Email has been sent to your email address' ) return {'email': user.email, 'tokens': user.tokens} return super().validate(attrs) raise AuthenticationException('Invalid credentials. Try again')
def post(self, request): user = self.serializer_class(data=request.data) user.is_valid(raise_exception=True) user.save() user_data = user.data user = User.object.get(email=user_data["email"]) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relative_link = reverse("email-verify") abs_url = "http://" + current_site + relative_link + "?token=" + str( token) email_body = "Hi " + user.username + ", Use link bellow to verify your emai \n" + abs_url data = { "email_body": email_body, "to": user.email, "email_subject": "Verify your account", "domain": current_site } Util.send_email(data) return Response(user_data, status=status.HTTP_201_CREATED)
def register_staff(self, request): user_data = request.data serializer = StaffSerializer(data=user_data) serializer.is_valid(raise_exception=True) # run validate method serializer.save() # run create method user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relative_link = reverse('account-verify_email') absolute_url = 'http://' + current_site + relative_link + '?token=' + str( token) email_body = 'Hi ' + user.username + "\nClick on the link below to verify your email\n\n" + absolute_url data = { 'email_body': email_body, 'to_email': user.email, 'email_subject': "verify your email" } Helper.send_email(data) return Response(serializer.data, status=status.HTTP_201_CREATED)
def admin_login(request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: context = { 'response': 'Invalid Credentials', } return Response(context, status=HTTP_404_NOT_FOUND) refresh_token = RefreshToken.for_user(user=user) context = { 'token': str(refresh_token.access_token), 'id': user.id, 'username': username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name, 'password': user.password } return Response(context, status=HTTP_200_OK)
def post(self, request, format=None): email = request.data['email'] password = request.data['password'] if email is None or password is None: return Response(status=status.HTTP_400_BAD_REQUEST) try: Use = User.objects.get(email=email) except: return Response({"msg":"incorrect email or password"},\ status = status.HTTP_401_UNAUTHORIZED) if Use: serializer = UserSerializer(Use) register_user = dict(serializer.data) registered_pass = register_user['password'] if password == registered_pass: tokens = str(RefreshToken.for_user(Use)) id_new = register_user['id'] return Response({"user_id": id_new,"JWT_Token": tokens},\ status = status.HTTP_200_OK) return Response(status=status.HTTP_401_AUTHENTICATION_ERROR) else: return Response(satuts=status.HTTP_401_AUTHENTICATION_ERROR)
def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data #Preparing email and its content user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = '127.0.0.1:8000' relativeLink = reverse('email-verify') absurl = 'http://' + current_site + relativeLink + "?token=" + str( token) email_body = 'Hi '+user.username + \ ' Use the link below to verify your email \n' + absurl data = { 'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email' } Util.send_email(data) return Response(user_data, status=status.HTTP_201_CREATED)
def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save(password=make_password(self.request.data['password'])) user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token relativeLink = reverse('email-verify') current_site = get_current_site(request).domain absurl = 'http://' + current_site + relativeLink + "?token=" + str( token) email_body = 'hi ' + user.username + ' Use link below\n' + absurl data = { 'email_body': email_body, 'email_subject': 'Verify Your Email', 'to_email': user.email } Util.send_email(data) return Response(user_data, status=status.HTTP_201_CREATED)
def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = User.objects.get(email=serializer.data['email']) token = RefreshToken.for_user(user) user.refresh_token_expires_at = str( (datetime.now() + timedelta(weeks=1)).astimezone().replace( microsecond=0).isoformat()) user.save(update_fields=('refresh_token_expires_at', )) data = {} data['token_type'] = settings.SIMPLE_JWT['AUTH_HEADER_TYPES'][0] data['access_token'] = str(token.access_token) data['expires_at'] = str( (datetime.now() + timedelta(minutes=30)).astimezone().replace( microsecond=0).isoformat()) data['refresh_token'] = str(token) data['refresh_token_expires_at'] = user.refresh_token_expires_at return Response(data)
def login(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validate_data('email') user_obj = None try: user_obj = User.objects.get(email=email) except Exception as e: response = { 'status': 403, 'message': 'invalid email not user found' } return Response(response) refresh = RefreshToken.for_user(user_obj) response = { 'status': 200, 'message': 'User login', 'refresh': str(refresh), 'access': str(refresh.access_token), } return Response(response)
def get(self, request, *args, **kwargs): temp_token = kwargs.get('token') try: if self.check_availability(temp_token): user = User.objects.get(auth_temp_token__token=temp_token) refresh_token = RefreshToken.for_user(user) access_token = AccessToken.for_user(user) user_serializer = UserSerializer(user) return Response(user_serializer.data, headers={ 'refresh': refresh_token, 'access': access_token }, status=status.HTTP_200_OK) else: return Response( {'detail': 'Token is not active or time expired'}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: return Response(data={'detail': 'User does not exist'}, status=status.HTTP_400_BAD_REQUEST) except TempToken.DoesNotExist: return Response(data={'detail': 'Token is invalid'}, status=status.HTTP_400_BAD_REQUEST)
def setUp(self): self.user = User.objects.create(email='*****@*****.**', display_name='tester') self.user.set_password('verylongpassword') self.user.save() refresh = RefreshToken.for_user(self.user) self.access_token = str(refresh.access_token) self.refresh_token = str(refresh) self.listing1 = Listing.objects.create( price=15.5, title='testing1', description='very good listing for testing', postal_code=42000, owner=self.user, category='HOME') self.listing2 = Listing.objects.create(price=66.9, title='testing2', description='testing', postal_code=54000, owner=self.user, category='KITCHEN')
def post(self, request, *args, **kwargs): try: serializer = self.get_serializer(data=self.request.data) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data email = validated_data.get('email') password = validated_data.get('password') user = UserModel.objects.annotate(cars_count=Count("cars")).get( email=email) if check_password(password, user.password): user_data = UserSerializer(user).data refresh = RefreshToken.for_user(user) return Response(data={ "user": user_data, "access_token": str(refresh.access_token), "refresh_token": str(refresh) }, status=status.HTTP_200_OK) else: raise Exception("Given password is invalid") except Exception as e: print(e) raise exceptions.AuthenticationFailed( {'detail': 'Invalid email or password'})
def register(request): try: data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) return Response( { 'status': 'success', 'data': { 'refresh': str(refresh), 'access': str(refresh.access_token) } }, status=200) else: return Response({ 'status': 'error', 'message': serializer.errors }, status=400) except Exception as e: return Response({'status': 'error', 'message': str(e)}, status=400)
def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user_for_token = User.objects.get(email=serializer.data['email']) token = RefreshToken.for_user(user_for_token).access_token user_data['token'] = str(token) # To catch any error that occurs while sending verification email try: data = {'email_subject': 'Bankless E-Mail Verification', 'email_body': 'Please verify your email with the following link: http://Bankless.com/verify-email', 'recipient': [user_for_token.email]} Util.send_email(data) except SMTPException as e: print("An error occurred while sending email: ", e) # For test, regardless of error in sending email, token is still returned, # Please don't leave this in Production!!!! return Response({"message": "There was an error sending email", "token": str(token)}) return Response(user_data, status=status.HTTP_201_CREATED)
def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data # Enviar Correo user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token relative_link = reverse_lazy('mail_verify') url = f'https://backendproyectofinal.herokuapp.com{relative_link}?token={token}' data = { 'subject': 'Confirmar cuenta', 'body': f'Hola {user.nombreCompleto}, usa este link para confirmar tu cuenta {url}', 'to': f'{user.email}' } send_email(data) return Response(user_data, status=status.HTTP_201_CREATED)
def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') user = User.objects.get(username=username) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('login') absurl = 'http://' + current_site + relativeLink + "?token=" + str( token) email_body = 'Hi ' + user.username + ' use link below to verify your email \n' + absurl data = { 'to': email, 'email_body': email_body, 'email_subject': 'Verify your email' } Util.send_email(data) return redirect('verify-email') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form})
def post(self, request): data = google_request_oauth2(request.data.get("token")) if 'error' in data: content = { 'message': 'wrong google token / this google token is already expired.' } return Response(data=content, status=status.HTTP_401_UNAUTHORIZED) # create user if not exist try: user = User.objects.get(email=data.get('email')) except User.DoesNotExist: user = User() user.username = data.get('email') # provider random default password user.password = make_password( CustomUserManager().make_random_password()) user.email = data.get('email') user.first_name = data.get('given_name') user.last_name = data.get('family_name') user.is_google = True user.save() token = RefreshToken.for_user( user) # generate token without username & password response = {} user_serializer = UserSerializer(user) response['user'] = user_serializer.data response['access'] = str(token.access_token) response['refresh'] = str(token) response['token_expire_at'] = token.access_token.get('exp') response['refresh_token_expire_at'] = token.get('exp') return Response(response)
def post(self, request, *args, **kwargs): if request.user.is_authenticated: return Response({'details': 'You are already authenticated'}, status=400) data = request.data username = data.get('username') password = data.get('password') qs = User.objects.filter( Q(username__iexact=username) | Q(email__iexact=username)).distinct() if (qs.count() == 1): user_obj = qs.first() if user_obj.check_password(password): user = user_obj refresh = RefreshToken.for_user(user) if user.is_staff: return Response({ 'refresh': str(refresh), 'access': str(refresh.access_token), 'user': { "id": user.id, "username": user.username, "email": user.email } }) else: response = {"error": "Not an Admin"} else: response = {"error": "Password Incorrect"} else: response = {"error": "User not found"} return Response(response, status=500)
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() token = RefreshToken.for_user(user).access_token domain = get_current_site(request).domain rel_url = reverse('user_verification') abs_url = f'http://{domain}{rel_url}?token={token}' content = f'''\ Hi {user.username}, Please verify your account by clicking the following url, and then login in to continue. {abs_url} ''' email = { 'subject': 'User email verification', 'email_body': content, 'email_to': user.email } Util.send_verification_mail(email) return Response(serializer.data, status=status.HTTP_201_CREATED)
def post(self, request): """ Endpoint for registering a user """ user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relative_link = reverse('email-verify') redirect_url = request.GET.get('redirect_url', None) absurl = 'https://' + current_site + relative_link + "?token=" + str( token) if redirect_url != None: absurl += "&redirect_url=" + redirect_url email_body = {} email_body['username'] = user.username email_body['message'] = 'Verify your email' email_body['link'] = absurl data = { 'email_body': email_body, 'email_subject': 'Codedigger - Email Confirmation', 'to_email': user.email } Util.send_email(data) return Response({ 'status': "OK", 'result': user_data }, status=status.HTTP_201_CREATED)
def registration(request): if request.method == 'POST': serializer = UserCreateSerializer(data=request.data) if not serializer.is_valid(): return response_validation_error(serializer.errors) user = serializer.save() update_last_login(None, user) log = {'user': user.id, 'action': "register"} log_serializer = UserLogSerializer(data=log) if not log_serializer.is_valid(): return response_validation_error(log_serializer.errors) log_serializer.save() refresh = RefreshToken.for_user(user) serialized_user = UserSerializer(user) data = { "user": serialized_user.data, "refresh": str(refresh), "access": str(refresh.access_token), } return response_created(data)
def test_create_review(self): self.user = User.objects.create_user(first_name="Test", username="******", password="******") token = RefreshToken.for_user(self.user) self.token = str(token.access_token) self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + (self.token)) self.product = Product.objects.create( name='Sample Name', price=0.8, quantity=12, descriptions='Sample Description', sku="0000024") data = {"rating": 5, "comment": "Awesome test review!"} response = self.client.post( "http://localhost:5555/products/{}/reviews/".format( str(self.product.id)), data=data, format='json') # print(response.content) self.assertEqual(response.status_code, (status.HTTP_200_OK))
def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://' + current_site + relativeLink + '?token=' + str( token) email_body = 'Hi ' + user.username + ', \n\nnPlease click the link below to verify your email-id \n\n' + absurl + '\n\nYou are receiving this email because, you signed up at workgent.ml\n\n--\nTeam workgent\nwww.workgent.ml' data = { 'email_body': email_body, 'email_to': user.email, 'email_subject': 'Verify your email - Workgent' } # Util.send_email(data) return Response(user_data, status=status.HTTP_201_CREATED)