Exemple #1
0
	def put(self, request, user_id):
		user = self.get_object(user_id)
		serializer = UserSerializer(instance = user, data = request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		return Response({"error": serializer.errors})
Exemple #2
0
    def init_users(self, request, pk=None):
        url = request.data['url']
        print(url)
        print(":next")
        response = urllib.request.urlopen(url)
        reader = csv.DictReader(response.read().decode('utf-8').splitlines())
        header = ["name", "roll_number", "status", "card_no", "image_url"]

        if request.data['mode'] == 'create':
            for each in reader:
                print(each)
                row = {}
                for field in header:
                    row[field] = each[field]
                serializer = UserSerializer(data=row)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return Response(serializer.errors,
                                    status=status.HTTP_400_BAD_REQUEST)
        elif request.data['mode'] == 'update':
            for each in reader:
                print(each)
                row = {}
                user = User.objects.get(pk=each["roll_number"])
                for field in header:
                    row[field] = each[field]
                serializer = UserSerializer(user, data=row)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return Response(serializer.errors,
                                    status=status.HTTP_400_BAD_REQUEST)

        return Response(data=None, status=status.HTTP_201_CREATED)
Exemple #3
0
 def post(self, request):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response({"error": serializer.errors},
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemple #4
0
    def post(self, request, format=None):
        """
        회원가입

        ---
        parameters:
        - username: string (필수)
        - email: email (필수)
        - password: string (필수)
        - department: string
        - enterYear: integer
        - github: string
        """
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()

            subject = 'UniDev 인증 메일입니다.'
            message = render_to_string(
                'user_activate.html', {
                    'user':
                    user,
                    'domain':
                    get_current_site(request).domain,
                    'uid':
                    urlsafe_base64_encode(force_bytes(
                        user.pk)).decode('utf-8'),
                    'token':
                    account_activation_token.make_token(user),
                })
            email = EmailMessage(subject, message, to=[user.email])
            email.send()

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #5
0
	def post(self,request,format=None):
		postData=request.data
		postData['is_active']=False
		postData['profile']['validatedcode']= self.get_validationcode()
		
		serializer=UserSerializer(data=postData)
		if serializer.is_valid() :
			serializer.save()
			
			## send email
			pending_message="Hello %s,\n\nThank you for your registration.\n Your account is pendinng. We will review and activate in a due course and send you a notification then.\nRegards,\nSite admin\n\n" % (serializer.data['first_name'],)
			
			send_mail("Pending account",pending_message,"*****@*****.**",[serializer.data['email']], fail_silently=True)
			
			url="http://%s/accounts/validate" % (request.get_host,)
			pending_message="Hello %s,\n\nA new account as been added. Please reivew and activate it by clicking on the below url:\n%s\n\nSite admin\n\n" % ('Admin',url,)
			mail_admins("Pending account",pending_message, fail_silently=True)
			
			
			return Response(serializer.data)
		
		error =ResponseRes.get_serializer_error(serializer.errors)
		
		return Response({
			'status': 'Failed',
			'message': 'This account could not be created. Reason:' + error})
Exemple #6
0
 def post(self, request, *args, **kwargs):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         user = User.objects.create_user(username=request.data['username'], email=request.data['email'], password=request.data['password'])
         user.save()
         return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #7
0
 def post(self, request, format='json'):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.save()
         if user:
             return Response(serializer.data,
                             status=status.HTTP_201_CREATED)
Exemple #8
0
 def post(self) -> tuple:
     user_data = self.user_service.get(**request.get_json())
     user_serializer = UserSerializer(many=True)
     return {
         'data': user_serializer.dump(list(user_data['query'])),
         'records_total': user_data['records_total'],
         'records_filtered': user_data['records_filtered'],
     }, 200
Exemple #9
0
class ProfileSer(serializers.ModelSerializer):
    """Сериализация профиля"""
    user = UserSerializer()
    follow = UserSerializer(many=True)

    class Meta:
        model = Profile
        fields = ('__all__')
Exemple #10
0
    def post(self, req, id):
        owner_id = checkCredentials(req)

        if not owner_id:
            return add_access_headers(
                HttpResponse(
                    json.dumps({
                        'status': 'err',
                        'msg': 'User NOT logged in!'
                    }),
                    content_type="application/json",
                ))

        user = None
        try:
            user = User.objects.get(pk=id)
        except:
            return add_access_headers(
                HttpResponse(
                    json.dumps({
                        'status': 'err',
                        'msg': 'User CANNOT be updated!'
                    }),
                    content_type="application/json",
                ))

        if user.role != 'admin':
            return add_access_headers(
                HttpResponse(
                    json.dumps({
                        'status':
                        'err',
                        'msg':
                        'Not sufficient rights for this operation!'
                    }),
                    content_type="application/json",
                ))

        data = req.data.copy()
        data['password'] = user.password
        serializer = UserSerializer(user, data=data)
        if not serializer.is_valid():
            return add_access_headers(
                HttpResponse(
                    json.dumps({
                        'status': 'err',
                        'msg': 'User CANNOT be updated!'
                    }),
                    content_type="application/json",
                ))

        serializer.save()

        return add_access_headers(
            HttpResponse(
                json.dumps({'status': 'ok'}),
                content_type="application/json",
            ))
Exemple #11
0
 def post(self, request):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response({
             'status': 'successs',
             'message': 'user created successfully'
         })
     return Response({'status': 'errors', 'message': serializer.errors})
    def post(self, request):

        secret_key = os.getenv("GOOGLE_RECAPTCHA_SECRET")
        data = {
            'secret': secret_key,
            'response': request.data.get('g-recaptcha-response', None)
        }

        resp = requests.post('https://www.google.com/recaptcha/api/siteverify',
                             data=data)

        print(resp.json())

        if not resp.json().get('success'):
            return Response(data={'error': 'ReCAPTCHA not verified.'},
                            status=status.HTTP_406_NOT_ACCEPTABLE)

        user_data = {}
        user_data['email'] = request.data.get("email", None)
        user_data['username'] = request.data.get("username", None)
        user_data['platform'] = request.data.get("platform", 0)
        user_data['password'] = request.data.get("password", None)
        if len(user_data['password']) < 6:
            return Response({"Invalid Password"},
                            status=status.HTTP_400_BAD_REQUEST)
        serializer = UserSerializer(data=user_data)

        if serializer.is_valid():
            serializer.save()

            user = User.objects.filter(
                Q(username__iexact=user_data['username'])
                & Q(email=user_data['email']))
            user = user[0]
            token = get_token({
                "username": user.username,
                "platform": user.platform,
                "date_time": str(datetime.datetime.today())
            })
            user_data['token'] = token
            del user_data['password']
            try:
                usertoken = UserToken.objects.get(user=user.id)
                return Response({"message": "User Already Logged in"},
                                status=status.HTTP_400_BAD_REQUEST)
            except UserToken.DoesNotExist:
                UserToken.objects.create(token=token, user=user)
                return Response(
                    {
                        "message": "User Signed up successfully",
                        "User": user_data
                    },
                    status=status.HTTP_201_CREATED)
        else:
            return Response({"message": serializer.errors},
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #13
0
    def post(self, request):
        serializer = UserSerializer()

        try:
            user = serializer.load(request.json)
        except ValidationError as error:
            return response.json(error.messages, status=400)

        register(user)
        return response.empty(status=201)
Exemple #14
0
 def update(self, request, pk=None):
     try:
         item = User.objects.get(pk=pk)
     except User.DoesNotExist:
         return Response(status=404)
     serializer = UserSerializer(item, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=400)
Exemple #15
0
 def post(self, request, *args, **kwargs):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         user = User.objects.create_user(username=request.data['username'],
                                         email=request.data['email'],
                                         password=request.data['password'])
         user.save()
         return Response(UserSerializer(user).data,
                         status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #16
0
    def post(self, request, *args, **kwargs):
        if not request.data:
            raise ValidationError('You must provide arguments for create.')

        if not isinstance(request.data, list):
            raise ValidationError('You must provide a list of objects.')

        serializer = UserSerializer(data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return serializer.data
Exemple #17
0
def usuario_lista(request):
    """
    Lista (GET) todos los usuarios o crea (POST) un nuevo usuario
    :param request:
    :return:
    """
    # LISTA TODOS LOS USUARIOS
    if request.method == 'GET':
        try:
            lista_json = []
            lista_users = Usuario.objects.all()

            for user in lista_users:
                if user.user.is_active and not user.user.is_staff:
                    user_json = {
                        'username': user.user.username,
                        'first_name': user.user.first_name,
                        'last_name': user.user.last_name,
                        'email': user.user.email,
                        'id': user.id,
                        'balance': user.balance
                    }
                    lista_json.append(user_json)

            return Response(lista_json)
        except KeyError:
            return Response({"message": "Atributos incorrectos"}, status=status.HTTP_400_BAD_REQUEST)

    # CREA UN USUARIO
    elif request.method == 'POST':
        try:
            data = JSONParser().parse(request)

            # Verifica que los datos no sean vacios
            if not data:
                return Response({"message": "No se enviaron datos"}, status=status.HTTP_400_BAD_REQUEST)

            # ENCRIPTA EL PASSWORD
            data['password'] = make_password(data['password'])
            serializer = UserSerializer(data=data)

            if serializer.is_valid():
                serializer.save()
                return Response({
                    'username': serializer.data['username'],
                    'first_name': serializer.data['first_name'],
                    'last_name': serializer.data['last_name'],
                    'email': serializer.data['email']
                }, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except KeyError:
            return Response({"message": "Atributos incorrectos"}, status=status.HTTP_400_BAD_REQUEST)
        except IntegrityError:
            return Response({"message": "Atributos duplicados"}, status=status.HTTP_400_BAD_REQUEST)
Exemple #18
0
    def put(self, request):
        user = get_object_or_404(User, id=request.user.id)
        user_serializer = UserSerializer(user, data=request.data, partial=True)

        if user_serializer.is_valid():
            user_serializer.update(user)
            data = {"success": "successfully updated settings"}
        else:
            return Response(user_serializer.errors,
                            status=HTTP_400_BAD_REQUEST)

        return Response(data)
 def post(self, request, format="json"):
     try:
         serializer = UserSerializer(data=request.data)
         if serializer.is_valid(raise_exception=True):
             user = serializer.save()
             if user:
                 token = Token.objects.create(user=user)
                 response = serializer.data
                 response["token"] = token.key
                 return Response(response, status=status.HTTP_201_CREATED)
     except IntegrityError as e:
         raise serializers.ValidationError()
Exemple #20
0
def _get_user_data(request_data: dict) -> list:
    page_number, items_per_page, order_by = rqo.get_request_query_fields(
        UserModel, request_data)

    query = UserModel.select()
    query = rqo.create_search_query(UserModel, query, request_data)
    query = (query.order_by(*order_by).paginate(page_number, items_per_page))

    user_serializer = UserSerializer(many=True)
    user_list = user_serializer.dump(list(query))

    return user_list
Exemple #21
0
def login(request, format=None):
    if request.user.is_authenticated:
        return Response(UserSerializer(request.user).data)

    user = authenticate(username=request.data['email'],
                        password=request.data['password'])
    if user is None:
        return Response({'error': 'User cannot be found'}, 401)

    token, created = Token.objects.get_or_create(user=user)
    response_data = UserSerializer(user).data
    response_data['token'] = token.key
    return Response(response_data)
Exemple #22
0
    def put(self, request, id, *args, **kwargs):
        if not request.data:
            raise ValidationError('You must provide an updated instance.')

        session = settings.SQLALCHEMY_SESSION()
        instance = session.query(User).filter(User.id == id).first()
        if not instance:
            raise ValidationError('Object does not exist')

        serializer = UserSerializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        data = serializer.data
        session.close()
        return data
Exemple #23
0
    def test_balance_positivo(self):
        usuario = Usuario()

        data = {
            "username": "******",
            "first_name": "jose",
            "last_name": "perez",
            "password": "******",
            "email": "*****@*****.**",
            "balance": 1000
        }

        serializer = UserSerializer(usuario, data=data)

        self.assertEqual(serializer.is_valid(), True)
Exemple #24
0
    def test_balance_positivo(self):
        usuario = Usuario()

        data = {
            "username": "******",
            "first_name": "jose",
            "last_name": "perez",
            "password": "******",
            "email": "*****@*****.**",
            "balance": 1000
        }

        serializer = UserSerializer(usuario, data=data)

        self.assertEqual(serializer.is_valid(), True)
 def post(self, request):
     """Register new user and create user profile"""
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.save()
         profile = Profile.objects.create(user=user,
                                          fname=user.first_name,
                                          lname=user.last_name)
         profile.save()
         location = Location.objects.create(profile=profile)
         location.save()
         if user:
             json = serializer.data
             return Response(json, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #26
0
class UserView(BaseView):
    _model = User
    _serializer = UserSerializer()
    _deserializer = UserDeserializer()

    @api_func('Get user', item_name='user', url_tail='/users/2',
              response=ExampleUsers.USER1.get())
    def get(self, id: int):
        return self._get(id=id)

    @api_func('Update user', item_name='user', url_tail='/users/2',
              request=ExampleUsers.USER1.set(change={'username': '******'}),
              response=ExampleUsers.USER1.get(change={'username': '******'}),
              status_codes={403: 'user can not modify other users', 422: '{original} / user is already exist'})
    def put(self, id: int):
        user = self._put_populate(id=id)
        if not self._current_user.admin and not user.id == self._current_user.id:
            abort(403, message="Can not modify another user")

        _set_password(user)
        return self._put_commit(user)

    @api_func('Delete user', item_name='user', url_tail='/users/2',
              admin_required=True,
              response=None,
              status_codes={403: 'user can not remove itself'})
    def delete(self, id: int):
        user = self._delete_get_model_object(id=id)
        if user.id == self._current_user.id:
            abort(403, message="User can not remove itself")
        return self._delete_commit(user)
Exemple #27
0
def get_user_info(request):
    ALLOWED_METHODS = ['GET']
    AUTH_HEADER = 'HTTP_AUTHORIZATION'
    TOKEN_PREFIX = 'Token '

    if request.method not in ALLOWED_METHODS:
        return http.HttpResponse(status=405)  # method not allowed

    headers = request.META

    if AUTH_HEADER not in headers:
        return http.HttpResponse(status=401)  # unauthorized

    token = headers[AUTH_HEADER]

    if not token.startswith(TOKEN_PREFIX):
        return http.HttpResponseBadRequest()

    token = token[len(TOKEN_PREFIX):]

    try:
        user = User.objects.get(auth_token=token)
        return http.JsonResponse(UserSerializer(user).data)
    except User.DoesNotExist:
        return http.HttpResponseNotFound()
Exemple #28
0
class PostSerializer(serializers.ModelSerializer):
  owner = UserSerializer(read_only=True)
  comment_set = CommentSerializer(many=True, read_only=True)

  class Meta:
    model = Post
    fields = ['id', 'title', 'date', 'description', 'owner', 'comment_set']
Exemple #29
0
def create(request):
    if not request.data:
        return Response({'detail': 'Missing body'},
                        status=status.HTTP_400_BAD_REQUEST)

    data = request.data

    try:
        if User.all_objects.get(email=data['email']):
            return Response({'detail': 'User with this email already exists'},
                            status=status.HTTP_400_BAD_REQUEST)
    except User.DoesNotExist:
        pass

    password = data['password']
    user_validate = UserCreateSerializer(data=data)
    user_validate.is_valid(raise_exception=True)
    user_validate.save()
    user = User.objects.get(pk=user_validate.data['id'])
    user.set_password(password)
    user.save()

    serialized_user = UserSerializer(user)

    return Response(serialized_user.data, status=status.HTTP_200_OK)
Exemple #30
0
class SessionView(restful.Resource):
    _serializer = UserSerializer()
    _deserializer = SessionDeserializer()

    @api_func('Get current session', url_tail='/session',
              response=ExampleUsers.ADMIN.get())
    def get(self):
        user = User.query.filter_by(username=g.user.username).first()
        return self._serializer.dump(user)

    @api_func('Login user', url_tail='/session',
              login_required=False,
              request=ExampleUsers.ADMIN.login(),
              response=ExampleUsers.ADMIN.get(),
              status_codes={401: 'bad authentication data or user is disabled'})
    def post(self):
        try:
            data = get_validated_request(self._deserializer)
        except RequestProcessingError as e:
            abort(422, message=e.message)

        user = User.query.filter_by(username=data['username']).first()
        if not user or not user.check_password(data['password']):
            abort(401, message='login error')
        if not login_user(user, remember=data['remember']):
            abort(401, message='login error')
        return self._serializer.dump(user), 201

    @api_func('Logout user', url_tail='/session',
              response=None)
    def delete(self):
        logout_user()
        return
def login(data):
    """
    Function that logins an user in the API.
    :param data: JSON with the credentials: username and password.
    :return: JSON with the username and the token associated.
    """
    login_serializer = LoginSerializer(data=data)
    if not login_serializer.is_valid():
        response = ErrorResponseSerializer({'detail': 'Invalid body'}).data
        return False, response, None

    user = authenticate(username=login_serializer.data["username"],
                        password=login_serializer.data["password"])

    if not user:
        response = ErrorResponseSerializer({
            'detail': 'Invalid credentials'
        }).data
        return False, response, None

    token, _ = Token.objects.get_or_create(user=user)
    data = UserSerializer(user).data

    response = LoginResponseSerializer({'data': data, 'token': token}).data
    return True, None, response
Exemple #32
0
	def put(self,request):
		postData=request.data
		user = User.objects.get(pk=postData['id'])
		serializer = UserSerializer(user,data=postData)
		
		if serializer.is_valid():
			serializer.save()
			res=ResponseRes.get_serializer_res(serializer,'Profile has been updated successfully')
			
			
			
			return Response(res)
		
		return Response({'status': 'Modify error', 
						'message':'Profile could not be modified. Reason:' + ResponseRes.get_serializer_error(serializer.errors)}, 
					status=status.HTTP_400_BAD_REQUEST)
Exemple #33
0
 def retrieve(self, request, pk=None):
     if pk == 'i':
         return HttpResponse(
             UserSerializer(request.user, context={
                 'request': request
             }).data)
     return super(UserViewSet, self).retrieve(request, pk)
Exemple #34
0
def login(request):
    if not request.data:
        return Response({'detail': 'Email and password required'},
                        status=status.HTTP_400_BAD_REQUEST)
    data = request.data
    login_validate = LoginSerializer(data=data)
    login_validate.is_valid(raise_exception=True)

    try:
        user = User.objects.get(email=data['email'])
    except User.DoesNotExist:
        raise exceptions.AuthenticationFailed("Wrong login credentials")

    if not user.check_password(data['password']):
        raise exceptions.AuthenticationFailed('Wrong login credentials')

    token, _ = Token.objects.get_or_create(user=user)

    if token_expire_handler(token):
        token.delete()
        token = Token.objects.create(user=token.user)

    serializer = UserSerializer(user)
    data = serializer.data

    data['token'] = token.key
    return Response({'data': data}, status=status.HTTP_200_OK)
Exemple #35
0
class PostSerializer(serializers.ModelSerializer):
    """Serializer твитов"""
    user = UserProfileSerialiser()
    user_like = UserSerializer(many=True)

    class Meta:
        model = Post
        fields = ("id", "user", "text", "date", "parent", "like", "user_like")
Exemple #36
0
def register(request):
    user_serializer = UserSerializer(data=request.data)
    if user_serializer.is_valid():
        user = user_serializer.save()
        request.data['user_id'] = user.id
    else:
        return Response(user_serializer.errors, status=HTTP_400_BAD_REQUEST)

    client_serializer = ClientSerializer(data=request.data)
    data = {}
    if client_serializer.is_valid():
        client = client_serializer.save()
        data['response'] = 'successfully registered a new client'
        data['token'] = Token.objects.get(user=client.user).key
    else:
        return Response(client_serializer.errors, status=HTTP_400_BAD_REQUEST)
    return Response(data)
Exemple #37
0
def my_jwt_response_handler(token, user=None, request=None):
    user = UserSerializer(user, context={'request': request}).data
    return_user = {
        'uuid': user.get('uuid'),
        'data': {
            'email': user.get('email'),
            'mobile_number': user.get('mobile_number'),
            'first_name': user.get('first_name'),
            'last_name': user.get('last_name'),
            'gender': user.get('gender'),
            'birthdate': user.get('birthdate')
        },
    }
    return {'token': token, 'user': return_user}
Exemple #38
0
def signup(request):
	try:
		User.objects.get(username=request.data.get("username"))
		return Response({'msg':"Username taken."}, status=status.HTTP_400_BAD_REQUEST)
	except User.DoesNotExist:
		pass

	usertype = request.data.get("usertype")

	serializer = UserSerializer(data=request.data)
	if serializer.is_valid():
		user_instance = serializer.save()
		if usertype != 'seeker' and usertype != 'provider':
			return Response(status=status.HTTP_400_BAD_REQUEST)
		user_instance.profile.usertype = usertype
		user_instance.profile.save()

		return Response(serializer.data, status=status.HTTP_201_CREATED)
	return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def register(request):
    if not is_client_known(request):
        return Response('Forbidden', status=401)

    serialized = UserSerializer(data=request.data)

    if serialized.is_valid():
        user = User.objects.create_user(
            username=serialized.validated_data['username'],
            password=serialized.validated_data['password'],
        )

        user.email = serialized.validated_data['email']
        user.save()

        user.profile = UserProfile()
        user.profile.save()
        createMail(user)
        return get_access_token(user)

    return Response(serialized._errors, status=400)
Exemple #40
0
def usuario_datos(request, id_user):
    """
    Obtiene (GET), modifica (PUT) o borra (DELETE) un usuario
    :param request:
    :param id_user: el id del usuario que se quiere obtener, borrar o modificar
    :return:
    """
    if id_user.isdigit():
        usuario = get_object_or_404(User, pk=int(id_user))
    else:
        usuario = get_object_or_404(User, username=id_user)
    usuario = get_object_or_404(Usuario, user_id=usuario.id)

    # VERIFICA QUE EL USUARIO ESTE ACCEDIENDO A SUS DATOS Y NO A LOS DE OTRO
    if not request.user.is_staff:
        if request.user.id != usuario.user_id:
            return Response({"message": "No tiene permisos para acceder"}, status=status.HTTP_401_UNAUTHORIZED)

    # OBTIENE UN USUARIO
    if request.method == 'GET':
        return Response({
            'username': usuario.user.username,
            'first_name': usuario.user.first_name,
            'last_name': usuario.user.last_name,
            'email': usuario.user.email,
            'id': usuario.id,
            'balance': usuario.balance
        })

    # ACTUALIZA LOS DATOS DE UN USUARIO VALIDANDO LOS CAMPOS INGRESADOS
    elif request.method == 'PUT':
        try:
            data = JSONParser().parse(request)
            # ENCRIPTA EL PASSWORD
            if 'password' in data:
                data['password'] = make_password(data['password'])

            serializer = UserSerializer(usuario, data=data)

            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response({
                    'username': serializer.data['username'],
                    'first_name': serializer.data['first_name'],
                    'last_name': serializer.data['last_name'],
                    'email': serializer.data['email']
                })
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        except KeyError:
            return Response({"message": "Atributos incorrectos"}, status=status.HTTP_400_BAD_REQUEST)
        except IntegrityError:
            return Response({"message": "Atributos duplicados"}, status=status.HTTP_400_BAD_REQUEST)

    # BORRA UN USUARIO
    elif request.method == 'DELETE':
        if usuario.validar_delete():
            usuario.user.delete()
            usuario.delete()
            return Response({"message": "El usuario ha sido borrado"}, status=status.HTTP_204_NO_CONTENT)
        return Response({"message": "No puede borrar"}, status=status.HTTP_400_BAD_REQUEST)
Exemple #41
0
 def post(self, request, *args, **kwargs):
     serializer = UserSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return serializer.data