Beispiel #1
0
    def gesttare_comentario_publico(self, model, oParam, cursor):
        user_name = qsatype.FLUtil.nameUser()
        msg = ""
        response = {}

        if not oParam or "confirmacion" not in oParam:

            response["status"] = 2
            response[
                "confirm"] = "Vas a cambiar la visibilidad del comentario para observador. </br></br> ¿Quieres continuar?"
            response["serverAction"] = "comentario_publico"

            return response

        response["resul"] = True

        params = {"pk": cursor.valueBuffer("idcomentario")}
        APIQSA.entry_point('post', "gt_comentarios", user_name, params,
                           "comentario_publico")
        publico = cursor.valueBuffer("publico")
        if not publico:
            msg = "Comentario visible para observador"
        else:
            msg = "Comentario no visible para observador"
        response["msg"] = msg

        return response
Beispiel #2
0
 def gesttare_cambiaplan_request(self, request, idcompany, descripcion,
                                 modalidad, cantidad_usuarios):
     # id_compania = qsatype.FLUtil.sqlSelect("aqn_user", "idcompany", "idusuario = " + str(request.user))
     # email = qsatype.FLUtil.sqlSelect("aqn_user", "email", "idusuario = " + str(request.user))
     # print("el id es: ",id_compania)
     # print("el email es: ",email)
     idusuario_activo = qsatype.FLUtil.nameUser()
     nuevo_plan = qsatype.FLUtil.sqlSelect(
         "aqn_planes", "idplan", "descripcion = '" + str(descripcion) +
         "' AND modalidad = '" + str(modalidad) + "'")
     params = {
         "pk": idcompany,
         "can_usuarios": cantidad_usuarios,
         "id_plan": nuevo_plan
     }
     url_pago = APIQSA.entry_point('post', "aqn_companies",
                                   idusuario_activo, params, "url_pago")
     url_pago = url_pago.decode("utf-8")
     url_pago = url_pago[10:-2]
     return render(
         request, "portal/pago.html", {
             "idcompany": idcompany,
             "idplan": nuevo_plan,
             "url_pago": url_pago,
             "cantidad_usuarios": cantidad_usuarios
         })
Beispiel #3
0
    def dameuseracl(self, request):
        params = None
        if request.method in ["POST", "DELETE", "PUT"]:
            print("pasa")
            try:
                params = {}
                # print(request.body)
                params["data"] = json.loads(request.body.decode("utf-8"))
                # print("por")

            except Exception as e:
                print(e)
                params = {}
                print(request._data)
                params['data'] = filtersPagination._generaPostParam(
                    request._data)["POST"]

        elif request.method == "GET":
            params = filtersPagination._generaGetParam(request.query_params)
        try:
            username = request.user.username
            print("____________")
            print(username)
            print(params)
            obj = APIQSA.getuseracl('post', params, username)
            result = HttpResponse(json.dumps(obj),
                                  status=200,
                                  content_type='application/json')
            result['Access-Control-Allow-Origin'] = '*'
            return result

        except Exception as e:
            print("______")
            print(bcolors.FAIL + "Excepcion " + str(e) + bcolors.ENDC)

            ex_type, ex_value, ex_traceback = sys.exc_info()

            # Extract unformatter stack traces as tuples
            trace_back = traceback.extract_tb(ex_traceback)

            # Format stacktrace
            stack_trace = list()

            for trace in trace_back:
                stack_trace.append(
                    "File : %s , Line : %d, Func.Name : %s, Message : %s" %
                    (trace[0], trace[1], trace[2], trace[3]))

            print("Exception type : %s " % ex_type.__name__)
            print("Exception message : %s" % ex_value)
            print("Stack trace : \n")
            for index, l in enumerate(stack_trace):
                if index < len(stack_trace) - 1:
                    print(l)
                else:
                    print(bcolors.WARNING + l + bcolors.ENDC)

            resp = HttpResponseServerError(str(e))
            resp['Access-Control-Allow-Origin'] = '*'
            return resp
Beispiel #4
0
    def gesttare_newcompany_request(self, request):
        if request.method == "POST":
            action = request.POST.get("action", None)
            username = request.POST.get("username", None)
            nombre = request.POST.get("nombre", None)
            email = request.POST.get("email", None)
            apellidos = request.POST.get("apellidos", None)
            password = request.POST.get("password", None)
            password2 = request.POST.get("password2", None)
            nombre_company = request.POST.get("nombrecompany", None)
            descripcion = request.POST.get("planes", None)
            modalidad = request.POST.get("modalidad", None)

            # if not re.match('^[(a-z0-9\_\-\.)]+@[(a-z0-9\_\-\.)]+\.[(a-z)]{2,15}$', email.lower()):
            #     return self.iface.newcompany(request, email, "El email no tiene el formato correcto")
            if action == "newcompany":
                id_plan = qsatype.FLUtil.sqlSelect(
                    "aqn_planes", "idplan",
                    "descripcion = '" + str(descripcion) +
                    "' AND modalidad = '" + str(modalidad) + "'")
                params = {
                    'nombre': nombre_company,
                    "idplan": id_plan,
                    "descripcion": nombre_company,
                    "usuario": {
                        'email': email,
                        'usuario': username,
                        'nombre': nombre,
                        'apellidos': apellidos,
                        'password': password,
                        'password2': password2,
                    }
                }
                try:
                    resultado = APIQSA.entry_point('post', "aqn_companies",
                                                   username, params)
                    id_compania = resultado[0]
                    id_usuario = resultado[1]
                    hashcode = resultado[2]
                except Exception as exc:
                    return self.iface.newcompany(request, str(exc))
                if not id_compania:
                    return self.iface.newcompany(
                        request, "Error no se puede crear usuario y compañía")

                user = User.objects.create_user(username=id_usuario,
                                                password="******",
                                                first_name=username)
                user.save()
                if not qsatype.FLUtil.sqlUpdate(
                        "auth_user", "is_superuser", True,
                        "username = '******'"):
                    return False
                # return self.iface.login(request, None, "Bienvenido a dailyjob, es necesario validar email")
                url = "/emailenviado/" + hashcode
                return HttpResponseRedirect(url)

        return self.iface.newcompany(request, "")
Beispiel #5
0
    def gesttare_soporte_request(self, request, idusuario):
        if request.method == "GET":
            action = request.GET.get("action", None)
            asunto = request.GET.get("subject", None)
            cuerpo = request.GET.get("body", None)
            # imagen = request.GET.get("imagen", None)

            # print("imagen:", imagen)

            idusuario_activo = qsatype.FLUtil.nameUser()
            email = qsatype.FLUtil.sqlSelect(
                "aqn_user", "email", "idusuario = " + str(idusuario_activo))

            if action == "enviarEmail":
                params = {"asunto": asunto, "cuerpo": cuerpo, "email": email}
                APIQSA.entry_point('post', "aqn_user", idusuario, params,
                                   "soporte")

                url = "/soporteenviado"
                return HttpResponseRedirect(url)
        return render(request, "portal/soporte.html")
Beispiel #6
0
    def gesttare_borrarAdjuntoTarea(self, model, oParam):
        # iddocumento = model.iddocumento
        # idUsuario = qsatype.FLUtil.nameUser()
        # resul = {}
        # try:
        #     params = {
        #         'pk': iddocumento
        #     }
        #     APIQSA.entry_point('post', "gd_documentos", idUsuario, params, 'delete')

        # except Exception as e:
        #     print('Excepcion', str(e))

        #     ex_type, ex_value, ex_traceback = sys.exc_info()

        #     # Extract unformatter stack traces as tuples
        #     trace_back = traceback.extract_tb(ex_traceback)

        #     # Format stacktrace
        #     stack_trace = list()

        #     for trace in trace_back:
        #         stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))

        #     print("Exception type : %s " % ex_type.__name__)
        #     print("Exception message : %s" %ex_value)
        #     print("Stack trace : %s" %"\n".join(stack_trace))

        #     raise(e)

        # resul["return_data"] = False
        # resul["msg"] = "Adjunto eliminado"
        iddocumento = model.iddocumento
        idUsuario = qsatype.FLUtil.nameUser()
        resul = {}
        if "confirmacion" in oParam and oParam["confirmacion"]:
            params = {
                'pk': iddocumento
            }
            msg = "Adjunto eliminado"
            if not APIQSA.entry_point('post', "gd_documentos", idUsuario, params, 'delete'):
                msg = "Error al eliminar adjunto"
                resul['status'] = 1
            resul["return_data"] = False
            resul["msg"] = msg
            return resul


        resul['status'] = 2
        resul["confirm"] = "El adjunto será eliminado"
        resul["serverAction"] = "borrarAdjuntoTarea"
        # return resul
        return resul
Beispiel #7
0
    def gesttare_emailenviado_request(self, request, hashparam):

        if request.method == "POST":
            action = request.POST.get("action", None)

            if action == "reenviaremail":

                email = qsatype.FLUtil.sqlSelect(
                    "aqn_invitations", "email",
                    "hashcode = '" + str(hashparam) + u"'")
                id_compania = qsatype.FLUtil.sqlSelect(
                    "aqn_invitations", "idcompany",
                    "hashcode = '" + str(hashparam) + u"'")

                params = {
                    "email": email,
                    "hashcode": hashparam,
                    "id_compania": id_compania
                }
                APIQSA.entry_point('post', "aqn_companies", "", params,
                                   "reenviar")
        return self.iface.emailenviado(request, hashparam)
Beispiel #8
0
def login(request):
    try:
        params = json.loads(request.body.decode("utf-8"))
        username = params["username"]
        password = params["password"]

    except Exception:
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)

    # Comprobamos usuario con pineboo
    try:
        apiuser = APIQSA.login(username, password)
        responseUser = {}
        if type(apiuser) is int or type(apiuser) is str:
            authusername = apiuser
            responseUser["user"] = apiuser
        else:
            authusername = apiuser["user"]
            responseUser = apiuser
        if authusername:
            user = User.objects.filter(username=str(authusername))
            if user.exists():
                authuser = authenticate(username=str(authusername),
                                        password=password)
                if authuser is None:
                    user = User.objects.get(username__exact=str(authusername))
                    user.set_password(password)
                    user.save()
                    authuser = authenticate(username=str(authusername),
                                            password=password)
            else:
                user = User.objects.create_user(username=str(authusername),
                                                password=password)
                user.is_staff = False
                user.save()
                authuser = authenticate(username=str(authusername),
                                        password=password)
            token, _ = Token.objects.get_or_create(user=authuser)
            print(responseUser)
            responseUser["token"] = token.key
            resul = HttpResponse(json.dumps(responseUser), status=200)
    except Exception as e:
        print("-----------------------")
        print(e)
        resul = HttpResponse(json.dumps({'error': str(e)}), status=404)
    resul['Access-Control-Allow-Origin'] = '*'
    return resul
Beispiel #9
0
    def gesttare_activecompany_request(self, request, hashparam):

        # API.sdsd(hashparam)
        cursor = qsatype.FLSqlCursor(u"aqn_invitations")
        cursor.select("hashcode = '{}'".format(hashparam))
        if not cursor.first():
            return HttpResponseRedirect("/403")
        cursor.setModeAccess(cursor.Browse)
        cursor.refreshBuffer()
        email = cursor.valueBuffer("email")
        id_company = cursor.valueBuffer("idcompany")
        params = {"email": email, "id_company": id_company}
        # idinvitation = cursor.valueBuffer("id")
        # Activamos compañia la damos por validada y activamos el usuario
        if not APIQSA.entry_point('post', "aqn_companies", "", params,
                                  'validar'):
            return False
            # return self.iface.error_activar(request)

        return self.iface.activecompany(request)
Beispiel #10
0
    def gesttare_token_auth(self, request):
        try:
            params = json.loads(request.body.decode("utf-8"))
            username = params["username"]
            password = params["password"]

        except Exception:
            username = request.POST.get("username", None)
            password = request.POST.get("password", None)

        # Comprobamos usuario con pineboo
        try:
            authuser = APIQSA.login(username, password)
            if authuser:
                # user = User.objects.filter(username=str(authusername))
                # if user.exists():
                #     authuser = authenticate(username=str(authusername), password=password)
                #     if authuser is None:
                #         user = User.objects.get(username__exact=str(authusername))
                #         user.set_password(password)
                #         user.save()
                #         authuser = authenticate(username=str(authusername), password=password)
                # else:
                #     user = User.objects.create_user(username=str(authusername), password=password)
                #     user.is_staff = False
                #     user.save()
                #     authuser = authenticate(username=str(authusername), password=password)
                # token, _ = Token.objects.get_or_create(user=authuser)
                resul = HttpResponse(json.dumps({'token': authuser["token"]}),
                                     status=200)
        except Exception as e:
            print("-----------------------")
            print(e)
            resul = HttpResponse(json.dumps({'error': str(e)}), status=404)
        resul['Access-Control-Allow-Origin'] = '*'
        return resul
Beispiel #11
0
    def gesttare_auth_login(self, request):
        if request.method == "POST":
            action = request.POST.get("action", None)
            username = request.POST.get("username", None)
            password = request.POST.get("password", None)
            redirect_uri = None
            state = None
            try:
                redirect_uri = request.POST.get("redirect_uri", None)
                state = request.POST.get("state", None)
                print(redirect_uri, "    ", state)
            except Exception as e:
                print(e)

            if action == "login":
                if username == "admin":
                    user = authenticate(username=username, password=password)
                    if user is not None:
                        login_auth(request, user)
                        accessControl.accessControl.registraAC()
                    else:
                        return self.iface.login(request,
                                                'Error de autentificación')
                    return HttpResponseRedirect("/")
                try:
                    authuser = APIQSA.login(username, password)
                    authusername = authuser["user"]

                    if authusername:
                        id_usuario = qsatype.FLUtil.sqlSelect(
                            "aqn_user", "idusuario",
                            "email = '" + str(username) + "'")

                        # ultimo_login = qsatype.FLUtil.sqlSelect("auth_user", "last_login", "username = '******'")
                        # if ultimo_login is None:
                        #     APIQSA.entry_point('post', "aqn_companies", "", str(username), "enviar_wiki")
                        # APIQSA.entry_point('post', "aqn_companies", "", "", "enviar_wiki")
                        usuario = aqn_user.objects.filter(
                            email__exact=username)
                        if usuario.exists():
                            authuser = authenticate(username=str(authusername),
                                                    password=password)
                            id_compania = qsatype.FLUtil.sqlSelect(
                                "aqn_user", "idcompany",
                                "idusuario = " + str(authusername))
                            cantidad_compania = qsatype.FLUtil.sqlSelect(
                                "aqn_user", "COUNT(idusuario)",
                                "idcompany = " + str(id_compania))
                            is_superuser = qsatype.FLUtil.sqlSelect(
                                "auth_user", "is_superuser",
                                "username = '******'")
                            if cantidad_compania == 1 and not is_superuser:
                                # user = User.objects.create_user(username=id_usuario, password="******", first_name=username)
                                nombre = qsatype.FLUtil.sqlSelect(
                                    "aqn_user", "usuario",
                                    "idusuario = " + str(authusername))

                                user = User.objects.get(
                                    username__exact=str(authusername))
                                user.is_superuser = True
                                user.first_name = nombre
                                user.save()
                                # qsatype.FLUtil.sqlUpdate("auth_user", "is_superuser", True, "username = '******'")
                                # qsatype.FLUtil.sqlUpdate("auth_user", "is_superuser", True, "username = '******'")
                            if authuser is None:
                                user = User.objects.get(
                                    username__exact=str(authusername))
                                user.set_password(password)
                                user.save()
                                authuser = authenticate(
                                    username=str(authusername),
                                    password=password)
                        else:
                            usuario = User.objects.create_user(
                                username=str(authusername), password=password)
                            usuario.is_staff = False
                            usuario.save()
                            authuser = authenticate(username=str(authusername),
                                                    password=password)

                        # if len(usuario) == 0:
                        #     return self.iface.login(request, 'No existe el usuario')
                        # if usuario[0].activo is False:
                        #     return self.iface.login(request, 'No existe el usuario')
                        # md5passwd = hashlib.md5(password.encode('utf-8')).hexdigest()
                        # # print("falla por aqui??", md5passwd, usuario[0].password)
                        # if usuario[0].password != md5passwd:
                        #     return self.iface.login(request, 'Error de autentificación')
                        idusuario = authusername
                        if redirect_uri and redirect_uri != None and redirect_uri != "None":
                            url = redirect_uri + "?state=" + state + "&code=" + username + "&token=prueba"
                            return HttpResponseRedirect(url)
                        # user = authenticate(username=idusuario, password="******")
                        if authuser is not None:
                            login_auth(request, authuser)
                        else:
                            return self.iface.login(
                                request, "Error de autentificación")
                        accessControl.accessControl.registraAC()
                        return HttpResponseRedirect("/")
                    else:
                        return self.iface.login(request,
                                                'No existe el usuario')
                except Exception as e:
                    print("_____________________")
                    print(e)
                    return self.iface.login(request, str(e))
        return self.iface.login(request)
Beispiel #12
0
    def ejecutaraccioncontrolador(self, request, modulo, accion=None, pk=None):
        # current_user = request.user
        username = request.user.username

        print("USER: "******"ejecutaraccioncontrolador!!", str(modulo), str(accion), str(pk))
        print(bcolors.OKBLUE + "METHOD: " + request.method + bcolors.ENDC)
        method = request.method.lower()
        # print(request.__dict__)
        params = {}
        if pk:
            params["pk"] = pk
        if method == "get":
            data = filtersPagination._generaGetParam(request.query_params)
            if data:
                params["params"] = data
        else:
            if "CONTENT_TYPE" in request.META and request.META[
                    "CONTENT_TYPE"].startswith("multipart/form-data"):
                params["params"] = request.POST
            else:
                try:
                    params["params"] = json.loads(request.body.decode("utf-8"))
                except Exception as e:
                    params["params"] = str(request.body.decode("utf-8"))

        params = self.dame_params_from_request(request, params)
        if "data" in params and not params["data"]:
            del (params["data"])
        elif "params" in params and not params["params"]:
            del (params["params"])
        try:
            # if method == "get":
            #     obj = APIQSA.entry_point(method, modulo, username, params, accion)
            #     if isinstance(obj, (Response, HttpResponse)):
            #         result = obj
            #     else:
            #         result = HttpResponse(json.dumps(obj, default=str), status=200, content_type='application/json')

            # else:
            #     obj = APIQSA.entry_point(method, modulo, username, params, accion)
            #     # result = HttpResponse(json.dumps(obj), status=200, content_type='application/json')
            #     result = self.get_response(obj)
            print(method, modulo, username, params, accion)
            obj = APIQSA.entry_point(method, modulo, username, params, accion)
            result = self.get_response(obj, method)

            if not isinstance(result, (Response, HttpResponse)):
                raise Exception('La respuesta no es Response o HttpResponse')

            result['Access-Control-Allow-Origin'] = '*'
            return result

        except Exception as e:
            print(bcolors.FAIL + "Excepcion " + str(e) + bcolors.ENDC)

            ex_type, ex_value, ex_traceback = sys.exc_info()

            # Extract unformatter stack traces as tuples
            trace_back = traceback.extract_tb(ex_traceback)
            # Format stacktrace
            stack_trace = list()

            for trace in trace_back:
                if isinstance(trace, (tuple, list)):
                    stack_trace.append(
                        "File : %s , Line : %d, Func.Name : %s, Message : %s" %
                        (trace[0], trace[1], trace[2], trace[3]))
                else:
                    stack_trace.append("    " + repr(trace))

            print("Exception type : %s " % ex_type.__name__)
            print("Exception message : %s" % ex_value)
            print("Stack trace : \n")
            for index, l in enumerate(stack_trace):
                if index < len(stack_trace) - 1:
                    print(l)
                else:
                    print(bcolors.WARNING + l + bcolors.ENDC)

            resp = HttpResponseServerError(str(e))
            resp['Access-Control-Allow-Origin'] = '*'
            return resp