Example #1
0
def token_new(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        if username and password:
            user = authenticate(username=username, password=password)

            if user:
                TOKEN_CHECK_ACTIVE_USER = getattr(settings,
                                                  "TOKEN_CHECK_ACTIVE_USER",
                                                  False)

                if TOKEN_CHECK_ACTIVE_USER and not user.is_active:
                    return JsonResponseForbidden("User account is disabled.")

                data = {
                    'token': token_generator.make_token(user),
                    'user': user.pk,
                }
                return JsonResponse(data)
            else:
                return JsonResponseUnauthorized(
                    "Unable to log you in, please try again.")
        else:
            return JsonError(
                "Must include 'username' and 'password' as POST parameters.")
    else:
        return JsonError("Must access via a POST request.")
Example #2
0
def addGrade(request):
    """
        courseid: <courseid>
        homeworkid: <homeworkid>
        
        optional:
         points_received: <# points>

    """

    if check(request) is not None:
        return check(request)
    data = json.loads(request.body.decode('utf-8'))

    if not 'courseid' in data:
        return JsonError("A courseid field is required to create a grade.")
    if not 'homeworkid' in data:
        return JsonError("A homeworkid field is required to create a grade.")

    if not Course.objects.filter(id=data['courseid']).exists():
        return JsonError("The courseid provided for the grade isn't valid.")

    if not Homework.objects.filter(id=data['homeworkid']).exists():
        return JsonError("The homeworkid provided for the grade isn't valid.")

    grade = Grade(course=Course.objects.get(id=data['courseid']),
                  homework=Homework.objects.get(id=data['homeworkid']),
                  user=request.user)

    if 'points_received' in data:
        grade.points_received = data['points_received']

    grade.save()

    return JsonResponse({"data": {"id": grade.id}, "success": True})
Example #3
0
def token_check(request):
    if request.method == 'GET':
        token = request.GET.get('token')
        user = request.GET.get('user')

        if token is not None and user is not None:
            if authenticate(pk=user, token=token) is not None:
                return JsonSuccess()
            else:
                return JsonError("Token did not match user.")
        else:
            return JsonError(
                "Must include 'user' and 'token' parameters with request.")

    elif request.method == 'POST':
        token = request.POST.get('token')
        user = request.POST.get('user')

        if token is not None and user is not None:
            if authenticate(pk=user, token=token) is not None:
                return JsonSuccess()
            else:
                return JsonError("Token did not match user.")
        else:
            return JsonError(
                "Must include 'user' and 'token' parameters with request.")

    else:
        return JsonError("Must access via a POST or GET request.")
Example #4
0
def addHomework(request):
    """
       categoryid: <categoryid>
       name:      <name>

       
       optional:
         points_possible: <# points possible>
    """
    if check(request) is not None:
        return check(request)
    data = json.loads(request.body.decode('utf-8'))

    if not 'name' in data:
        return JsonError("A name field is required to create a homework.")
    if not 'categoryid' in data:
        return JsonError(
            "A categoryid field is required to create a homework.")
    if len(data['name']) < 4:
        return JsonError("The name provided for the homework is too short.")

    if not Category.objects.filter(id=data['categoryid']).exists():
        return JsonError(
            "The categoryid provided for the homework isn't valid.")

    homework = Homework(name=data['name'],
                        category=Category.objects.get(id=data['categoryid']))

    if 'points_possible' in data:
        homework.points_possible = data['points_possible']

    homework.save()

    return JsonResponse({"data": {"id": homework.id}, "success": True})
Example #5
0
def delete(request, id):
    if request.method != "POST":
        return JsonError("Only POST is allowed")
    post = request.POST
    try:
        exp = Expense.objects.get(pk=id)
        print(exp)
        exp.delete()
    except Expense.DoesNotExist:
        return JsonError("Invalid id")
    return JsonResponse({})
Example #6
0
def save_complemento(request):
    if request.method == "POST":
        try:
            producto = Productos.objects.get(
                ns_imei=request.POST.get("ns_imei"))
        except:
            producto = Productos()

        producto.ns_imei = request.POST["ns_imei"]
        producto.detalle = request.POST["detalle"]
        producto.precio_venta = request.POST["precio_venta"].replace(",", ".")
        producto.es_unico = False
        producto.estado = "VT"
        producto.save()

        compra = Compras(codigo_compra=request.POST["codigo_compra"],
                         producto_id=producto.id,
                         usuario_id=request.user.id)
        compra.save()
        datos = {
            "result": True,
            "codigo_compra": compra.codigo_compra,
            "modelo": unicode(producto),
            "ns_imei": producto.ns_imei,
            "precio": str(producto.precio_venta),
            "tipo": producto.get_descripcion_tipo(),
            "descuento": str(producto.descuento),
            "es_unico": producto.es_unico
        }
        return JsonResponse(datos)
    return JsonError("Solo puede ser peticiones POST")
Example #7
0
def getfiles(request):
    if request.method != 'POST' or not 'ID' in request.POST:
        return JsonError("Este servidor solo acepta peticiones POST")

    id_file = request.POST["ID"]
    path = FileController.getPath(id_file)
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(),
                                    content_type="application/octet-stream")
            response[
                'Content-Disposition'] = 'inline; filename=' + os.path.basename(
                    file_path)
            return response
    return JsonError("Pagina no encontrada o un error inesperado")
Example #8
0
def get_documento_firma(request):
    if request.method == "POST":
        dni = request.POST["data"]
        clientes = Clientes.objects.filter(DNI=dni)
        pk = -1
        if len(clientes) >0:
            pk =  clientes[0].pk
        compras = Compras.objects.filter(Q(vendedor_id=pk) & Q(firma=""))
        if len(compras) > 0:
            vendedor = compras[0].get_vendedor()
            producto = compras[0].producto
            return JsonResponse({"result":
                                 [{"nombre": cliente.nombre_completo,
                                   "compra_id": compras[0].id,
                                   "nombre": vendedor["nombre"],
                                   "telefono": vendedor['telefono'],
                                   "DNI": vendedor["DNI"].upper(),
                                   "domicilio": vendedor['domicilio'],
                                   "modelo": str(producto),
                                   "ns_imei": producto.ns_imei,
                                   "precio": producto.precio_compra}]})
        else:
            return JsonResponse({"result": []})
    else:
        return JsonError("Solo acepta peticiones POST")
Example #9
0
def token(request, token, user):
    try:
        user = User.objects.get(pk=user)
    except User.DoesNotExist:
        return JsonError("User does not exist.")

    TOKEN_CHECK_ACTIVE_USER = getattr(settings, "TOKEN_CHECK_ACTIVE_USER",
                                      False)

    if TOKEN_CHECK_ACTIVE_USER and not user.is_active:
        return JsonError("User account is disabled.")

    if token_generator.check_token(user, token):
        return JsonResponse({})
    else:
        return JsonError("Token did not match user.")
Example #10
0
def secrets(request):
    user_id = request.GET['user']
    user = get_object_or_404(User, pk=user_id)

    if request.method == strings.POST:
        description = request.POST['description']
        secret = user.secret_set.create(description=description)
        dict = {}
        dict[strings.ID] = secret.id
        return JsonResponse(dict)

    elif request.method == strings.GET:
        secrets = Secret.objects.filter(user__id=user.id)

        listofsecrets = []
        dictofsecrets = {}

        for secret in secrets:
            listofsecrets.append(
                utility.Secret(secret.id, secret.description,
                               str(secret.pub_date)).__dict__)

        dictofsecrets["secrets"] = listofsecrets

        return JsonResponse(dictofsecrets)
    else:
        return JsonError("only can have post and get requests")
Example #11
0
def get_producto(request):
    ns_imei = request.POST['ns_imei']
    datos = {}
    try:
        producto = Productos.objects.filter(Q(ns_imei__icontains=ns_imei))
        producto = producto[0]
    except:
        return JsonError("No se ha encontrado coincidencias")

    compras = Compras.objects.filter(producto__pk=producto.pk)

    if len(compras) > 0:
        codigo_compra = compras[0].codigo_compra
    else:
        codigo_compra = producto.id + 303450

    datos = {
        "result": True,
        "codigo_compra": codigo_compra,
        "modelo": unicode(producto),
        "ns_imei": producto.ns_imei,
        "precio": str(producto.precio_venta),
        "tipo": producto.get_descripcion_tipo(),
        "descuento": str(producto.descuento),
        "es_unico": producto.es_unico,
        "estado": producto.estado,
        "id": producto.id
    }

    return JsonResponse(datos)
Example #12
0
def save_modelo(request):
    from tokenapi.http import JsonResponse, JsonError
    f_modelo = ModelosForm(request.POST)
    if f_modelo.is_valid():
        modelo = f_modelo.save()
        return JsonResponse({'id': modelo.id})
    else:
        return JsonError("formulario no valido")
Example #13
0
def register(request):
    """
        "username": username
        "password": password
        "email": email
    """
    if check(request) is not None:
        return check(request)
    data = json.loads(request.body.decode('utf-8'))

    #Username
    if not 'username' in data:
        return JsonError("'username' is a required field.")
    if len(data['username']) < 4 or len(data['username']) > 25:
        return JsonError("Usernames must be between 4 and 25 characters.")
    if User.objects.filter(username=data['username']).exists():
        return JsonError("Username already exists")

    if not 'password' in data:
        return JsonError("'password' is a required field.")
    if len(data['password']) < 5:
        return JsonError("A password must be at least 5 characters long.")

    if not 'email' in data:
        return JsonError("'email' is a required field.")
    if len(data['email']) < 5:
        return JsonError("Email is too short")

    user = User(username=data['username'], email=data['email'])
    user.set_password(data['password'])
    user.save()

    return JsonResponse({"success": True, "data": {"id": user.id}})
Example #14
0
def qson_django(request):
    if request.method != 'POST' or not 'data' in request.POST:
        return JsonError("Este servidor solo acepta peticiones POST")
    data = json.loads(request.POST.get("data"))
    JSONResponse = {}
    qson_helper = QSonHelperDjango()
    JSONResponse = qson_helper.decode_qson(data)
    http = JsonResponse(JSONResponse)
    return http
Example #15
0
def modificar_precio_venta(request, id_producto):
    if request.method == "POST":
        producto = Productos.objects.get(pk=id_producto)
        producto.estado = "VT"
        producto.precio_venta = request.POST["precio_venta"]
        producto.save()
        return JsonResponse({'precio': producto.precio_venta})
    else:
        return JsonError("solo peticiones post")
Example #16
0
def addCourse(request):
    """
    name: coursename
    school: school name
    """
    if check(request) is not None:
        return check(request)
    data = json.loads(request.body.decode('utf-8'))

    if not 'name' in data:
        return JsonError("A name field is required to create a course.")
    if not 'school' in data:
        return JsonError("A school field is required to create a course.")
    if len(data['name']) < 4:
        return JsonError("The name provided for the course is too short.")
    if len(data['school']) < 4:
        return JsonError("The name provided for the school is too short.")

    course = Course(name=data['name'], school=data['school'])
    course.save()

    return JsonResponse({"data": {"id": course.id}, "success": True})
Example #17
0
def get(request):
    """Return laptimes according to requested car/track combo."""
    if request.method != 'GET':
        return JsonError('Only GET method is allowed.')

    try:
        track = Track.objects.filter(ac_name=request.GET['track'],
                                     layout=request.GET.get('layout') or '')
        car = Car.objects.filter(ac_name=request.GET['car'])
    except KeyError as err:
        return JsonError('Missing <{}> argument.'.format(err.args[0]))

    if track.count() == 0 or car.count() == 0:
        msg = 'No laptimes found.'
        logger = logging.getLogger(__name__)
        logger.warning(msg, extra={'request': request, 'stack': True})
        return JsonError(msg)

    serializer = LaptimeSerialiser(
        Laptime.objects.filter(car=car, track=track).order_by('user', 'time') \
                                                    .distinct('user'),
        many=True
    )
    return JsonResponse(serializer.data, status=200)
Example #18
0
def edit(request, id):
    if request.method != "POST":
        return JsonError("Only POST is allowed")
    post = request.POST
    try:
        exp = Expense.objects.get(pk=id)
        if post['shop'] != exp.shop:
            shop = Shop.objects.get_or_create(name=post['shop'])[0]
            exp.shop = shop
        exp.date = post['date']
        exp.expenseitem_set.clear()
        for name, price, category in json.loads(post['items']):
            exp.expenseitem_set.create(name=name,
                                       price=price,
                                       category=category)
        exp.save()
        print(exp)
        exp = Expense.objects.get(pk=id)
        print(exp)
    except KeyError as e:
        return JsonError("The following key is not found %s" % e)
    except Expense.DoesNotExist:
        return JsonError("Invalid id")
    return JsonResponse({})
Example #19
0
def add_setup(request):
    """Add a new setup to an existing laptime."""
    if request.method != 'POST':
        return JsonError('Only POST method is allowed.')
    logger = logging.getLogger(__name__)
    try:
        data = json.loads(request.body.decode('utf-8'))
    except json.decoder.JSONDecodeError:
        msg = "Bad data. Can't load parameters."
        logger.warning(msg,
                       exc_info=True,
                       extra={
                           'request': request,
                           'stack': True
                       })
        return JsonError(msg)

    try:
        setup, laptime_id = data['car_setup'], data['laptime_id']
    except KeyError as err:
        return JsonError('Missing <{}> argument.'.format(err.args[0]))

    try:
        laptime = Laptime.objects.get(pk=laptime_id)
    except Laptime.DoesNotExist:
        return JsonError('Laptime not found')

    if laptime.car_setup is not None:
        return JsonError('Setup already exists for the laptime.')

    car_setup, created = Setup.objects.get_or_create(car=laptime.car,
                                                     track=laptime.track,
                                                     **setup)
    laptime.car_setup = car_setup
    laptime.save()
    return JsonResponse(dict(message='Setup was saved for the laptime.'))
Example #20
0
def addCategory(request):
    """
    name: category name

    Optional:
        weight:    <weight>
    """
    if check(request) is not None:
        return check(request)
    data = json.loads(request.body.decode('utf-8'))

    if not 'name' in data:
        return JsonError("A name field is required to create a category.")
    if len(data['name']) < 4:
        return JsonError("The name provided for the category is too short.")

    cat = Category(name=data['name'])

    if 'weight' in data:
        cat.weight = float(data['weight'])

    cat.save()

    return JsonResponse({"data": {"id": cat.id}, "success": True})
Example #21
0
def upload_test_result(request):

    if request.method == 'POST':
        form = TestResultUploadForm(request.POST)
        if form.is_valid():
            repo_url =  form.cleaned_data['repository_url']
            repo_name =  '/'.join(repo_url.split('/')[3:5])
            branch_url = repo_url + '/trees/' + form.cleaned_data['branch_name']
            commit_url = repo_url + '/trees/' + form.cleaned_data['commit_sha']

            test_results = {
                'package': {
                    'name': form.cleaned_data['package'],
                },
                'repository': {
                    'name': repo_name,
                    'url': repo_url,
                },
                'branch': {
                    'name': form.cleaned_data['branch_name'],
                    'url': branch_url,
                },
                'commit': {
                    'name': form.cleaned_data['commit_sha'],
                    'url': commit_url,
                },
                'execution': {
                    'name': form.cleaned_data['execution_name'],
                    'url': form.cleaned_data['execution_url'],
                },
                'environment': {
                    'name': form.cleaned_data['environment_name'],
                },
                'results_url': form.cleaned_data['results_file_url'],
            }

            from testresults.importer import import_test_results
            execution = import_test_results.delay(test_results)
            return JsonResponse({'execution_id': execution.id})
    else:
        return JsonError('Only POST is allowed')
        #form = TestResultUploadForm()

    context = RequestContext(request, {'form': form})

    return render_to_response('testresults/upload_test_result.html', context)
Example #22
0
def set_review(request):
    """
    Set review by user
    """
    user = request.user
    if not user.is_authenticated():
        return JsonError("PermissionDenied")

    review = Review()
    review.title = request.POST.get("title")
    review.rating = request.POST.get("rating")
    review.summary = request.POST.get("summary")
    review.ip_address = get_client_ip(request)
    review.reviewer = user
    review.company_id = request.POST.get("company_id")
    review.save()
    return JsonResponse({'status': 'success', 'review_id': review.id})
Example #23
0
def detail(request, secret_id):
    try:
        user_id = request.GET['user']
    except:
        return JsonError("key error")

    try:
        user = get_object_or_404(User, pk=user_id)
    except ObjectDoesNotExist:
        return JsonError("User " + user_id + "does not exist")

    if request.method == strings.POST:
        description = request.POST['description']

        try:
            selected_secret = user.secret_set.get(pk=secret_id)
        except (ObjectDoesNotExist):
            return JsonError("Secret id " + secret_id + " does not exist")

        selected_secret.description = description
        selected_secret.save()

        return JsonResponse({})

    elif request.method == strings.GET:
        try:
            selected_choice = user.secret_set.get(pk=secret_id)
        except (ObjectDoesNotExist):
            return JsonError("Secret id " + secret_id + " does not exist")

        secret = utility.Secret(selected_choice.id,
                                selected_choice.description,
                                str(selected_choice.pub_date)).__dict__

        return JsonResponse(secret)

    elif request.method == strings.DELETE:
        try:
            selected_secret = user.secret_set.get(pk=secret_id)
        except (ObjectDoesNotExist):
            return JsonError("Secret id " + secret_id + " does not exist")

        selected_secret.delete()
        return JsonResponse({})

    else:
        return JsonError("Only can post, put, get, delete")
Example #24
0
def expense_list_json(request, type):
    print(request.user)
    expenses = Expense.objects.for_user(request.user)

    if type == 'all':
        expenses = expenses.all()
        groups = listify(expenses, True)
    elif type == 'place':
        shops = Shop.objects.filter(lat__isnull=False,
                                    lon__isnull=False).annotate(
                                        Sum('expense__expenseitem__price'))
        groups = []
        for shop in shops:
            groups.append((shop.name, shop.lat, shop.lon,
                           str(shop.expense__expenseitem__price__sum)))
    elif type == 'day':
        expenses = expenses.order_by('date').all()
        groups = []
        for k, g in groupby(expenses, lambda x: x.date):
            groups.append((str(k), listify(g)))
    else:
        return JsonError("Invalid request")
    return JsonResponse(groups)
Example #25
0
    def _wrapped_view(request, *args, **kwargs):
        user = None
        token = None
        basic_auth = request.META.get('HTTP_AUTHORIZATION')

        user = request.POST.get('user', request.GET.get('user'))
        token = request.POST.get('token', request.GET.get('token'))

        if not (user and token) and basic_auth:
            auth_method, auth_string = basic_auth.split(' ', 1)

            if auth_method.lower() == 'basic':
                auth_string = b64decode(auth_string.strip())
                user, token = auth_string.decode().split(':', 1)

        if not (user and token):
            return JsonError("Must include 'user' and 'token' parameters with request.")

        user = authenticate(pk=user, token=token)
        if user:
            request.user = user
            return view_func(request, *args, **kwargs)

        return JsonResponseUnauthorized("You are unauthorized to view this page.")
Example #26
0
def get_ventas_chart(request):
    if request.method == "POST":
        years = 0
        month = 0
        ventas = 0
        compras = 0
        base_imponible = 0
        importe_iva = 0
        importe = 0
        try:
            years = request.POST["years"]
            month = request.POST["month"]
            ventas = Ventas.objects.filter(
                fecha_salida__month__gte=month,
                fecha_salida__year__gte=years,
                fecha_salida__month__lte=month,
                fecha_salida__year__lte=years,
            )

            ventas, compras = get_total_neto(ventas)
            importe = float("{0:.2f}".format((float(ventas) - float(compras))))
            base_imponible, importe_iva = desglose_iva(importe)
        except Exception as e:
            print(e)

        return JsonResponse({
            "years": years,
            "month": month,
            'ventas': ventas,
            'compras': float(compras),
            "importe": importe,
            "beneficio": base_imponible,
            "iva": importe_iva
        })

    return JsonError("Solo peticiones post")
Example #27
0
def save_actuacion(request):
    if request.method == "POST":
        try:
            actuacion = Reparaciones.objects.get(codigo=request.POST.get("codigo"))
        except:
            actuacion = Reparaciones()

        actuacion.codigo=request.POST["codigo"]
        actuacion.detalle=request.POST["detalle"]
        actuacion.precio=request.POST["precio"].replace(",",".")

        actuacion.save()

        datos = {
            "result": True,
            "pk": actuacion.pk,
            "codigo": actuacion.codigo,
            "can": 1,
            "descuento": 0,
            "detalle": actuacion.detalle,
            "precio": actuacion.precio,
        }
        return JsonResponse(datos)
    return JsonError("Solo puede ser peticiones POST")
Example #28
0
def get_producto_abonar(request):
    ns_imei = request.POST['ns_imei']
    cliente_id = request.session["accion_abonos_pk_cliente"]
    datos = {}
    try:
        producto = Productos.objects.get(ns_imei=ns_imei)
    except:
        return JsonError("No se ha encontrado coincidencias")

    linea = LineasVentas.objects.filter(
        Q(ns_imei=ns_imei) & Q(venta__cliente_id=cliente_id))[0]

    datos = {
        "result": True,
        "codigo_compra": linea.codigo_compra,
        "modelo": unicode(producto),
        "ns_imei": producto.ns_imei,
        "precio": linea.p_unidad,
        "descuento": linea.descuento,
        "tipo": producto.get_descripcion_tipo(),
        "es_unico": producto.es_unico
    }

    return JsonResponse(datos)
Example #29
0
def arquear(request):
    if request.method == 'POST':
        arq = json.loads(request.POST["data"])
        efectivo = Pedidos.objects.filter(estado__contains="PG_")
        efectivo = efectivo.exclude(modo_pago="Tarjeta").aggregate(
            Sum("total"))
        efectivo = efectivo[
            "total__sum"] if efectivo["total__sum"] != None else 0
        tarjeta = Pedidos.objects.filter(estado__contains="PG_")
        tarjeta = tarjeta.exclude(modo_pago="Efectivo").aggregate(Sum("total"))
        tarjeta = tarjeta["total__sum"] if tarjeta["total__sum"] != None else 0
        caja_dia = float(efectivo) + float(tarjeta) + float(
            arq['caja_dia']) + float(arq['tarjeta'])
        ef_fisico = float(arq['efectivo']) - float(arq['cambio'])
        tarjeta = float(tarjeta) + float(arq['tarjeta'])
        ef_tickado = float(efectivo) + float(arq['caja_dia'])
        descuadre = (ef_fisico + float(arq['total_gastos'])) - ef_tickado
        arqueo = Arqueos(
            **{
                'caja_dia': caja_dia,
                'efectivo': ef_fisico,
                'cambio': arq['cambio'],
                'total_gastos': arq['total_gastos'],
                'tarjeta': tarjeta,
                'descuadre': descuadre,
            })
        arqueo.save()

        for c in arq["conteo"]:
            conteo = Conteo(**c)
            conteo.save()
            arqueo.conteo.add(conteo)
        for c in arq["extras"]:
            c["importe"] = c["importe"].replace(",", ".")
            e = PedidosExtra(**c)
            e.save()
            arqueo.pedidosextra.add(e)
        for c in arq["gastos"]:
            g = Gastos(**c)
            g.save()
            arqueo.gastos.add(g)
        for c in Pedidos.objects.filter(estado__contains="PG_"):
            c.estado = "AR_SN"
            c.save()
            arqueo.pedidos.add(c)

        desglose = []
        retirar = 0
        for ls in arq["conteo"]:
            if ef_fisico - retirar > 0.1:
                total_linea = ls["total"]
                subtotal = retirar + total_linea
                if subtotal <= ef_fisico:
                    retirar += total_linea
                    desglose.append(ls)
                else:
                    subtotal = ef_fisico - retirar
                    tipo = float(ls["tipo"])
                    num = int(subtotal / tipo)
                    if num > 0:
                        total_linea = num * tipo
                        retirar += total_linea
                        desglose.append({
                            "can": num,
                            "tipo": tipo,
                            "total": total_linea,
                            "texto_tipo": ls["texto_tipo"]
                        })

        return JsonResponse({'desglose': desglose})

    return JsonError("NO ESTA AUTORIZADO")
Example #30
0
def token(request, token, user):
    if authenticate(pk=user, token=token) is not None:
        return JsonResponse({})
    else:
        return JsonError("Token did not match user.")