def post(self, request): username = request.data.get('username') password = request.data.get('password') errors = [] if not username: errors.append('username cannot be empty') if not password: errors.append('password cannot be empty') if errors: return Response( {'info': errors}, status=status.HTTP_400_BAD_REQUEST, ) user = authenticate( request, username=username, password=password, ) if user is None: return Response( {'info': ['Invalid login credentials']}, status=status.HTTP_400_BAD_REQUEST, ) serializer = TokenObtainPairSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: # TODO: why would this happen? raise InvalidToken(e.args[0]) jwtResponse = Response(serializer.validated_data, status=status.HTTP_200_OK) jwtResponse.data['username'] = user.username return jwtResponse
def token_obtain_pair_handler(username, password): """ Takes a set of user credentials and returns an access and refresh JSON web token pair to prove the authentication of those credentials. """ ser = TokenObtainPairSerializer(data={ get_username_field(): username, 'password': password }) ser.is_valid(raise_exception=True) update_last_login(None, ser.user) res = dict(refresh=ser.validated_data.get('refresh'), access=ser.validated_data.get('access'), user=UserSerializer(ser.user).data) return res
def get_token(self, username, password): s = TokenObtainPairSerializer(data={ TokenObtainPairSerializer.username_field: self.username, 'password': self.password, }) self.assertTrue(s.is_valid()) return s.validated_data['access']
def post(self, request, *args, **kwargs): if not request.data.get("password"): return Response(responsedata(False, "Password is required"), status=status.HTTP_400_BAD_REQUEST) if not User.objects.filter(email=request.data.get('email')).exists(): return Response(responsedata(False, "No User found"), status=status.HTTP_404_NOT_FOUND) if not User.objects.get( email=request.data.get('email')).check_password( request.data.get("password")): return Response(responsedata(False, "Incorrect Password"), status=status.HTTP_400_BAD_REQUEST) if request.data.get('email'): user = User.objects.get(email=request.data.get('email')) request.data['uuid'] = user.uuid user = authenticate(email=request.data.get('email'), password=request.data.get('password')) login(request, user) serializer = TokenObtainPairSerializer(data=request.data) if serializer.is_valid(raise_exception=True): data = serializer.validate(request.data) data['user'] = User.objects.filter( uuid=request.data.get('uuid')).values() return Response(responsedata(True, "Sign in Successful", data), status=status.HTTP_200_OK) return Response(responsedata(False, "Something went wrong"), status=status.HTTP_400_BAD_REQUEST)
def signup(request): if request.method == "POST": if request.data['password1'] == request.data["password2"]: user = {} if request.data['university'] is not '': universityObject, created = University.objects.get_or_create( title=request.data["university"]) if universityObject is None: universityObject = created user = User.objects.create_user( email=request.data['email'], password=request.data['password1'], university=request.data["university"], nickname=request.data['nickname'], ) else: user = User.objects.create_user( email=request.data['email'], password=request.data['password1'], nickname=request.data['nickname'], ) serializer = TokenObtainPairSerializer( data={ 'email': request.data['email'], 'password': request.data['password1'] }) if serializer.is_valid(): serializer.validated_data['university'] = request.data[ 'university'] serializer.validated_data['nickname'] = request.data[ 'nickname'] return Response(serializer.validated_data)
def token(self, request, *args, **kwargs): """ Token Takes a set of user credentials and returns an access and refresh JSON web token pair to prove the authentication of those credentials. """ serializer = TokenObtainPairSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) return response.Response(serializer.validated_data, status=status.HTTP_200_OK)
def post(self, request): errors = [] if not request.data.get('username'): errors.append('username cannot be empty') if not request.data.get('email'): errors.append('email cannot be empty') if not request.data.get('password'): errors.append('password cannot be empty') elif len(request.data['password']) < 8: errors.append('password must be at least 8 characters long') if errors: return Response( {'info': errors}, status=status.HTTP_400_BAD_REQUEST, ) # create the user user_serializer = UserSerializer(data=request.data) try: user_serializer.is_valid(raise_exception=True) except Exception as e: return Response( {'info': list(e.detail.values())}, status=status.HTTP_400_BAD_REQUEST, ) new_user = user_serializer.save() # create the profile profile_data = {'user': new_user.pk} profile_serializer = ProfileSerializer(data=profile_data) profile_serializer.is_valid(raise_exception=True) new_profile = profile_serializer.save() # create and return the jwts jwt_serializer = TokenObtainPairSerializer(data=request.data) try: jwt_serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) jwtResponse = Response(jwt_serializer.validated_data, status=status.HTTP_200_OK) jwtResponse.data['username'] = new_user.username return jwtResponse
def mock_token(django_user_model): """Mock token""" data = {"name": "icaro", "email": "*****@*****.**", "password": "******"} django_user_model.objects.create_user(username="******", **data) data = {"email": data["email"], "password": data["password"]} token = TokenObtainPairSerializer(data=data) if token.is_valid(): headers = { "HTTP_AUTHORIZATION": f'Bearer {token.validated_data["access"]}' } return headers
def tokens(self, request, *args, **kwargs): token_obtain_pair_serializer = TokenObtainPairSerializer( data=request.data) token_obtain_pair_serializer.is_valid(raise_exception=True) user = User.objects.get(email=request.data['email']) is_exist_profile = hasattr(user, 'profile') response_data = { **token_obtain_pair_serializer.validated_data, 'user': user, 'profile': user.profile if is_exist_profile else None, 'coin_history': CoinHistory.objects.filter(profile=user.profile).order_by('-id') if is_exist_profile else [], } serializer = self.get_serializer(response_data) return Response(data=serializer.data, status=status.HTTP_200_OK)
def post(self, request): # TG_REACT_UPGRADE: Code is copied over to correctly create Organizations serializer = self.serializer_class(data=request.data, context={'request': request}) if serializer.is_valid(): data: dict = serializer.validated_data.copy() password = data.pop('password', None) user = get_user_model()(**data) user.set_password(password) user.save() serializer = TokenObtainPairSerializer(data={ 'email': user.email, 'password': password }) serializer.is_valid() # serializer = TokenObtainPairSerializer(data=request.data) return Response(serializer.validated_data) return Response({'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
def test_it_should_produce_a_json_web_token_when_valid(self): s = TokenObtainPairSerializer(context=MagicMock(), data={ TokenObtainPairSerializer.username_field: self.username, 'password': self.password, }) self.assertTrue(s.is_valid()) self.assertIn('access', s.validated_data) self.assertIn('refresh', s.validated_data) # Expecting token type claim to be correct for both tokens. If this is # the case, instantiating appropriate token subclass instances with # encoded tokens should not raise an exception. AccessToken(s.validated_data['access']) RefreshToken(s.validated_data['refresh'])
def post(self, request, *args, **kwargs): try: info = list( User.objects.filter(email=request.data.get("email")).values( 'uuid', 'email', 'username')) info = info[0] except: return Response(responsedata(False, "No User found"), status=status.HTTP_404_NOT_FOUND) if not request.data.get('email'): return Response(responsedata(False, "Email Id is required"), status=status.HTTP_405_METHOD_NOT_ALLOWED) if not request.data.get("password"): return Response(responsedata(False, "Password is required"), status=status.HTTP_405_METHOD_NOT_ALLOWED) if not User.objects.filter(email=request.data.get("email")).exists(): return Response(responsedata(False, "No user found with this Email Id"), status=status.HTTP_404_NOT_FOUND) if User.objects.filter(email=request.data.get("email")).exists(): user = list( User.objects.filter( email=request.data.get("email")).values())[0] if not User.objects.get( email=request.data.get("email")).check_password( request.data.get("password")): print( User.objects.get( email=request.data.get("email")).get_password()) return Response(responsedata(False, "Incorrect Password"), status=status.HTTP_404_NOT_FOUND) serializer = TokenObtainPairSerializer(data=request.data) if serializer.is_valid(raise_exception=True): data = serializer.validate(request.data) data.update({"Access-Control-Expose-Headers": "access"}) data.update(info) if serializer.User.is_active: return Response(responsedata(True, "Login Successfull", data), status=200) else: return Response(responsedata(False, "Please Validate Your Email Id"), status=400)
def post(self, request, *args, **kwargs): if request.data: request.POST._mutable = True data = request.data data['Pass'] = data.get('password') if User.objects.filter(email=data.get('email')).values().exists(): Response(responsedata(False, "User already present"), status=status.HTTP_409_CONFLICT) data['is_active'] = True serializer = UserSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() tokenserializer = TokenObtainPairSerializer( data={ "email": request.data.get("email"), "password": request.data.get("password") }) if tokenserializer.is_valid(raise_exception=True): data = tokenserializer.validate({ "email": request.data.get("email"), "password": request.data.get("password") }) tempid = serializer.data.get("uuid") else: return Response(responsedata(False, "Can't insert data"), status=400) respdata = { 'uuid': tempid, 'data': data, 'username': serializer.data['username'], 'email': serializer.data['email'], } return Response(responsedata(True, "Data Inserted", respdata), status=200) else: return Response(responsedata(False, "No data provided"), status=412)
def login(self, request): serializer = TokenObtainPairSerializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.validated_data , status=200)
def post(self, request): """Authenticate user through the provider and access_token""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) provider = serializer.data.get('provider', None) strategy = load_strategy(request) try: backend = load_backend(strategy=strategy, name=provider, redirect_uri=None) except MissingBackend: return Response({'error': 'Please provide a valid provider'}, status=status.HTTP_400_BAD_REQUEST) try: if isinstance(backend, BaseOAuth2): print(serializer.data) access_token = serializer.data.get('access_token') #password = serializer.data.get('password') user = backend.do_auth(access_token) #,password) print(user) except HTTPError as error: print('here2') return Response( { "error": { "access_token": "Invalid token", "details": str(error) } }, status=status.HTTP_400_BAD_REQUEST) except AuthTokenError as error: print('here3') return Response( { "error": "Invalid credentials", "details": str(error) }, status=status.HTTP_400_BAD_REQUEST) try: print('here3') print(user) authenticated_user = backend.do_auth(access_token, user=user) print('here4') except HTTPError as error: print('here5') return Response({ "error": "invalid token", "details": str(error) }, status=status.HTTP_400_BAD_REQUEST) except AuthForbidden as error: return Response({ "error": "invalid token", "details": str(error) }, status=status.HTTP_400_BAD_REQUEST) if authenticated_user and authenticated_user.is_active: #generate JWT token login(request, authenticated_user) data = {"token": jwt_encode_handler(jwt_payload_handler(user))} #customize the response to your needs response = { "email": authenticated_user.email, "username": authenticated_user.username, #"gender": authenticated_user.gender, #"birthday": authenticated_user.birthday, #"profile": authenticated_user.profile, "token": data.get('token') } # try: #self.user_activate(authenticated_user) # except: # pass authenticated_user.is_active = True authenticated_user.save() password = jwt.encode({'username': authenticated_user.username}, 'secret', algorithm='HS256') d = { 'username': authenticated_user.username, 'password': password.decode("utf-8") } #,'csrfmiddlewaretoken':request.data['csrfmiddlewaretoken']} query_dict = QueryDict('', mutable=True) query_dict.update(d) response = TokenObtainPairSerializer(data=query_dict) response.is_valid() serialized_user = UserSerializer(authenticated_user) serialized = { 'token': response.validated_data, 'user': serialized_user.data } print(serialized) return Response(status=status.HTTP_200_OK, data=serialized)