def update_me(self, request, *args, **kwargs): data = request.data try: avatar = data.get("avatar") data = json.loads(data["data"]) user = request.user if user.username != data["username"]: try: User.objects.get(username=data["username"]) return Response( {"detail": "the chosen username in not available, please pick another"}, status=status.HTTP_400_BAD_REQUEST ) except User.DoesNotExist: pass user.username = data["username"] user.first_name = data["first_name"] user.last_name = data["last_name"] user.email = data.get("email", user.email) perfil, created = Profile.objects.get_or_create(user=user) if avatar is not None: perfil.avatar = File(avatar) profile = data.get("profile") if profile is not None: perfil.phone = profile.get("phone", perfil.phone) perfil.address = profile.get("address", perfil.address) perfil.gender = profile.get("gender", perfil.gender) perfil.nit = profile.get("nit", perfil.nit) user.save() perfil.save() serializer = UserReadSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) except KeyError as e: return Response({"detail": "{} is a required field".format(str(e))}, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): request_data = get_request_data(request, 'post') email = request_data["email"] if request_data.get("email") else None otp = request_data["otp"] if request_data.get("otp") else None user_type = request_data["user_type"] if request_data.get( "user_type") else None if email is not None and otp is not None and user_type is not None: if verify_otp(email, otp): user = User.objects.filter(Q(email=email), Q(user_type=user_type)) if user.exists(): base_user = user[0] if base_user.user_type == CONST_CHOICE_USER_TYPE_BUYER: user = Buyer.objects.filter(id=base_user.id)[0] if base_user.user_type == CONST_CHOICE_USER_TYPE_SELLER: user = Seller.objects.filter(id=base_user.id)[0] if base_user.user_type == CONST_CHOICE_USER_TYPE_ADMIN: user = Admin.objects.filter(id=base_user.id)[0] data = UserReadSerializer(user).data data["auth-token"] = base_user.create_auth_token() return response(data, status.HTTP_200_OK) return error_response(CONST_ERROR_MESSAGE_INVALID_USER_KEY, status.HTTP_400_BAD_REQUEST) return error_response(CONST_ERROR_MESSAGE_INCORRECT_OTP_KEY, status.HTTP_400_BAD_REQUEST) return error_response( CONST_ERROR_MESSAGE_EMAIL_OR_OTP_NOT_PROVIDED_KEY, status.HTTP_400_BAD_REQUEST)
def listProductBySeller(self, request): data = request.data try: with transaction.atomic(): profile = Profile.objects.get(id=data.get("profileId"), activo=True) productos = Producto.objects.filter( profile=data.get("profileId"), activo=True).annotate( total=models.Sum('lote_producto__cantidad', filter=models.Q( lote_producto__activo=True))) productData = ProductoSerializer(productos, many=True) user = UserReadSerializer(profile.user) return Response( { "productos": productData.data, "vendedor": user.data }, status=status.HTTP_200_OK) return Response( {"detail": "Hubo un error al actualizar el producto"}, status=status.HTTP_400_BAD_REQUEST) except KeyError as e: return Response( {"detail": "{} is a required field".format(str(e))}, status=status.HTTP_400_BAD_REQUEST)
def listVendedores(self, request): data = request.data try: with transaction.atomic(): querysetSellers = None if data.get("isSeller") == True: querysetSellers = User.objects.filter( is_active=True).exclude(id=data.get("user").get("id")) else: querysetSellers = User.objects.filter(is_active=True) respuesta = [] if querysetSellers is not None: serializerSellers = UserReadSerializer(querysetSellers, many=True) respuesta = serializerSellers.data return Response({"vendedores": respuesta}, status=status.HTTP_200_OK) return Response( {"detail": "Hubo un error al actualizar el producto"}, status=status.HTTP_400_BAD_REQUEST) except KeyError as e: return Response( {"detail": "{} is a required field".format(str(e))}, status=status.HTTP_400_BAD_REQUEST)
def me(self, request, *args, **kwargs): user = request.user profile = Profile.objects.get(user=user) profileSerializer = TokenProfileSerializer(profile) serializer = UserReadSerializer(user) return Response( { "user": serializer.data, "profile": profileSerializer.data }, status=status.HTTP_200_OK)
def token(self, request, *args, **kwargs): data = request.data try: user = User.objects.get(email=data["username"]) profile = Profile.objects.get(user=user) if profile.activo == False: return Response({"detail": "El usuario esta inactivo"}, status=status.HTTP_400_BAD_REQUEST) if user.check_password(data["password"]): token, created = Token.objects.get_or_create(user=user) try: profile = Profile.objects.get(user=user) profileSerializer = TokenProfileSerializer(profile) serializer = UserReadSerializer(user) return Response( { "user": serializer.data, "token": token.key, "profile": profileSerializer.data }, status=status.HTTP_200_OK) except: profile = "Admin" serializer = UserReadSerializer(user) return Response( { "user": serializer.data, "token": token.key, "rol": profile }, status=status.HTTP_200_OK) return Response({"detail": "Contrasenia incorrecta"}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: return Response({"detail": "Usuario no encontrado"}, status=status.HTTP_404_NOT_FOUND) except KeyError as e: return Response( {"detail": "{} es un campo obligatorio".format(str(e))}, status=status.HTTP_400_BAD_REQUEST)
def token(self, request, *args, **kwargs): data = request.data try: user = User.objects.get(username=data["username"]) if user.check_password(data["password"]): token, created = Token.objects.get_or_create(user=user) serializer = UserReadSerializer(user) return Response({"user": serializer.data, "token": token.key}, status=status.HTTP_200_OK) return Response({"detail": "Password does not match user password"}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: return Response({"detail": "User not found"}, status=status.HTTP_404_NOT_FOUND) except KeyError as e: return Response({"detail": "{} is a required field".format(str(e))}, status=status.HTTP_400_BAD_REQUEST)
def enviarCorreo(self, request, *args, **kwargs): try: data = request.data user = User.objects.get(email=data.get("email")) serializer = UserReadSerializer(user) usuario = serializer.data.get( 'first_name') + ' ' + serializer.data.get('last_name') username = serializer.data.get('username') email = data.get('email') fecha = datetime.datetime.now() hoy = fecha.strftime('%Y-%m-%d %H:%M') encoded_jwt = jwt.encode( { 'usuario': usuario, 'username': username, 'email': email, 'fecha': hoy }, "secret", algorithm="HS256") print(encoded_jwt) ha = jwt.decode(encoded_jwt, "secret", algorithms=["HS256"]) #{'some': 'payload'} print(ha) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login("*****@*****.**", "calderonguillen7") # Construimos el mensaje simple mensaje = MIMEMultipart() mensaje['From'] = "*****@*****.**" mensaje['To'] = email mensaje['Subject'] = "Solicitud de Cambio de ContraseƱa" content = render_to_string('./correo.html', { 'codigo': encoded_jwt, 'usuario': usuario }) #print("mensaje", mensaje) mensaje.attach(MIMEText(content, 'html')) # Envio del mensaje mailServer.sendmail("*****@*****.**", email, mensaje.as_string()) return Response(status=status.HTTP_200_OK) except Exception as e: return Response({'detail': str(e)}, status=status.HTTP_400_BAD_REQUEST)
def put(self, request): request_data = get_request_data(request, 'put') context = self.get_context(request) instance = get_object_or_404( self.model.objects.filter(id=context["user"])) serializer = self.get_serializer_class(instance, data=request_data, partial=True) if serializer.is_valid(): user = serializer.save() data = UserReadSerializer(user).data data['auth-token'] = user.get_auth_token() return response(data, status.HTTP_201_CREATED) else: error_in_valid_serializer_response(serializer)
def post(self, request): request_data = get_request_data(request, 'post') serializer = self.serializer_class(data=request_data) if serializer.is_valid(): user = self.model.objects.filter(username=request_data['username']) if user.exists(): user = user[0] if user.check_password(request_data['password']): data = UserReadSerializer(user).data data['auth-token'] = user.get_auth_token() return response(data, status.HTTP_200_OK) else: return error_response(CONST_ERROR_INVALID_PASSWORD) else: return error_response(CONST_ERROR_INVALID_USERNAME) else: return error_in_valid_serializer_response(serializer)
def post(self, request): request_data = get_request_data(request, 'post') serializer = self.serializer_class(data=request_data) email = request_data["email"] if request_data.get("email") else None otp = request_data["otp"] if request_data.get("otp") else None if email: if verify_otp(email, otp): if serializer.is_valid(): user = serializer.save() data = UserReadSerializer(user).data data["auth-token"] = User.objects.filter( id=user.id)[0].create_auth_token() return response(data, status.HTTP_201_CREATED) return inv_serializer_error_response( serializer, status.HTTP_400_BAD_REQUEST) return error_response(CONST_ERROR_MESSAGE_INCORRECT_OTP_KEY, status.HTTP_400_BAD_REQUEST) return error_response(CONST_ERROR_MESSAGE_EMAIL_NOT_PROVIDED_KEY, status.HTTP_400_BAD_REQUEST)
def update_me(self, request, *args, **kwargs): data = request.data try: avatar = data.get("avatar") data = json.loads(data["data"]) user = request.user user.first_name = data.get("user").get("first_name") user.last_name = data.get("user").get("last_name") perfil, created = Profile.objects.get_or_create(user=user) if avatar is not None: perfil.avatar.delete() perfil.avatar = File(avatar) profile = data.get("profile") if profile is not None: perfil.phone = profile.get("phone", perfil.phone) perfil.address = profile.get("address", perfil.address) user.save() perfil.save() serializer = UserReadSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) except KeyError as e: return Response( {"detail": "{} is a required field".format(str(e))}, status=status.HTTP_400_BAD_REQUEST)
def me(self, request, *args, **kwargs): user = request.user serializer = UserReadSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK)