Exemplo n.º 1
0
        public ActionResult Autherize(_17599075_PROG_POE.Models.STUDENT stuModel)
        {
            using (Db_Entities db = new Db_Entities())
            {
                try
                {
                    var userDetails = db.STUDENTS.Where(x => x.USERNAME == stuModel.USERNAME && x.PASSWORD == stuModel.PASSWORD).FirstOrDefault();

                    if (userDetails == null)
                    {
                        //stuMdbodel.LoginErrorMessage = "Wrong username or password";

                        return(View("Index", stuModel));
                    }
                    else
                    {
                        Session["userName"]  = userDetails.USERNAME;
                        Session["firstName"] = userDetails.FIRSTNAME;
                        Session["surname"]   = userDetails.SURNAME;
                        Session["mark"]      = userDetails.TEST_MARK;

                        return(RedirectToAction("Index", "Home"));
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        protected List <Dictionary <string, object> > LoadData(string sqlSelect, params object[] sqlParameters)
        {
            var table = new List <Dictionary <string, object> >();

            using (Db_Entities db = new Db_Entities())
            {
                db.Database.Connection.Open();
                using (var cmd = db.Database.Connection.CreateCommand())
                {
                    cmd.CommandText    = sqlSelect;
                    cmd.CommandTimeout = 600;
                    foreach (var param in sqlParameters)
                    {
                        cmd.Parameters.Add(param);
                    }
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var row = new Dictionary <string, object>();
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                row[reader.GetName(i)] = reader[i];
                            }
                            table.Add(row);
                        }
                    }
                }
                db.Database.Connection.Close();
            }
            return(table);
        }
Exemplo n.º 3
0
 public override MembershipUser GetUser(string username, bool userIsOnline)
 {
     using (var db = new Db_Entities())
     {
         var user = db.Usuario.FirstOrDefault(o => o.id_usu == username);
         return(user == null ? null : new UsuarioMembership(user));
     }
 }
 public override bool ValidateUser(string username, string password)
 {
     using (var db = new Db_Entities())
     {
         return((from u in db.Usuario join c in db.Cliente on u.id_cliente equals c.id_cliente
                 where (u.pass_usu == password && u.id_usu == username && u.estado == 1 && c.estado == "1")
                 select true).Any());
     }
 }
Exemplo n.º 5
0
 public override bool ValidateUser(string username, string password)
 {
     using (var db = new Db_Entities())
     {
         var pass = password;
         var usu  = db.Usuario.Where(o => o.pass_usu == pass && o.id_usu == username);
         if (usu.Any())
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
        protected Dictionary <int, List <Dictionary <string, string> > > MultiLoadData(List <SqlParameter> parametros, string NombreProcedimiento)
        {
            var table      = new List <Dictionary <string, string> >();
            var multi_list = new Dictionary <int, List <Dictionary <string, string> > >();

            using (Db_Entities db = new Db_Entities()) {
                db.Database.Connection.Open();
                using (var cmd = db.Database.Connection.CreateCommand())
                {
                    cmd.CommandText = NombreProcedimiento;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddRange(parametros.ToArray());
                    cmd.ExecuteNonQuery();
                    using (var reader = cmd.ExecuteReader())
                    {
                        int y = 0;
                        while (reader.HasRows)
                        {
                            var row = new Dictionary <string, string>();
                            while (reader.Read())
                            {
                                if (reader.GetName(0).Equals("valor", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    row[reader[1].ToString()] = reader[0].ToString();
                                }
                                else
                                {
                                    row = new Dictionary <string, string>();
                                    for (int i = 0; i < reader.FieldCount; i++)
                                    {
                                        row[reader.GetName(i)] = reader[i].ToString();
                                    }
                                }
                                table.Add(row);
                            }
                            multi_list[y] = table;
                            y++;
                            reader.NextResult();
                        }
                    }
                }
                db.Database.Connection.Close();
            }
            return(multi_list);
        }
        protected Dictionary <string, string> MultiLoadDataToDictionary(List <SqlParameter> parametros, string NombreProcedimiento)
        {
            var table = new Dictionary <string, string>();

            using (Db_Entities db = new Db_Entities()) {
                db.Database.Connection.Open();
                using (var cmd = db.Database.Connection.CreateCommand())
                {
                    cmd.CommandText = NombreProcedimiento;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddRange(parametros.ToArray());
                    cmd.ExecuteNonQuery();
                    using (var reader = cmd.ExecuteReader())
                    {
                        try
                        {
                            do
                            {
                                while (reader.Read())
                                {
                                    if (reader.GetName(0).Equals("valor", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        table[reader[1].ToString()] = reader[0].ToString();
                                    }
                                    else
                                    {
                                        for (int i = 0; i < reader.FieldCount; i++)
                                        {
                                            table[reader.GetName(i)] = reader[i].ToString();
                                        }
                                    }
                                }
                            } while (reader.NextResult());
                        }
                        catch (Exception ex)
                        {
                            Console.Out.WriteLine(ex.Message);
                        }
                    }
                }
                db.Database.Connection.Close();
            }
            return(table);
        }
        //funcion para leer el periodo vigente al cual pertenece el usuario consultando
        protected int PeriodoVigente(List <SqlParameter> parametros)
        {
            int result = new int();

            using (Db_Entities db = new Db_Entities()) {
                db.Database.Connection.Open();
                using (var cmd = db.Database.Connection.CreateCommand())
                {
                    cmd.CommandText = "sp_selPeriodoUsuario";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddRange(parametros.ToArray());
                    cmd.Parameters["@VALOR_RET"].Direction = ParameterDirection.Output;
                    cmd.ExecuteNonQuery();
                    result = (int)cmd.Parameters["@VALOR_RET"].Value;
                }
                db.Database.Connection.Close();
            }
            return(result);
        }
        public ActionResult getFileData(string Token)
        {
            using (var db = new Db_Entities()) {
                FileCode FileCode = new FileCode()
                {
                    Token = Token
                };
                FileCode.Decode();
                int    id_doc = Int32.Parse(FileCode.values["id_doc"]);
                string type   = FileCode.values["type"];
                string fecha  = FileCode.values["fecha"];
                int    id_usu = 0;// SesionLogin().id;
                Int32.TryParse(FileCode.values["id_usu"], out id_usu);
                string encryptDocument = "S";
                FileCode.values.TryGetValue("encryptDocument", out encryptDocument);
                MemoryStream ms = new MemoryStream();
                PdfReader    pdfReader;
                PdfStamper   pdfStamper;
                AcroFields   pdfFormFields;
                Usuario      usuario = id_usu == 0 ? SesionLogin() : db.Usuario.FirstOrDefault(p => p.id == id_usu);
                Cliente      cliente = id_usu == 0 ? SesionCliente() : db.Cliente.FirstOrDefault(p => p.id_cliente == usuario.id_cliente);

                try
                {
                    if (type == TIPO_LIQUIDACION)
                    {
                        var fecha_set = new string((from c in fecha where char.IsLetterOrDigit(c) select c).ToArray());
                        var fec_sp    = DateTime.ParseExact(fecha_set, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
                        pdfReader     = new PdfReader(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMLIQUI" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                        pdfStamper    = new PdfStamper(pdfReader, ms);
                        pdfFormFields = pdfStamper.AcroFields;
                        var periodo = PeriodoVigente(new List <SqlParameter>()
                        {
                            new SqlParameter("@Fecha", SqlDbType.Date)
                            {
                                Value = fecha
                            },
                            new SqlParameter("@NOM_CLIENTE_DB", SqlDbType.VarChar)
                            {
                                Value = cliente.Nom_cor_emp
                            },
                            new SqlParameter("@VALOR_RET", SqlDbType.Int)
                            {
                                Value = 0
                            }
                        });
                        var datos_liquidacion = MultiLoadDataToDictionary(new List <SqlParameter>()
                        {
                            new SqlParameter("@USU_ID", SqlDbType.VarChar)
                            {
                                Value = usuario.id_usu
                            },
                            new SqlParameter("@NOM_CLIENTE_DB", SqlDbType.VarChar)
                            {
                                Value = cliente.Nom_cor_emp
                            },
                            new SqlParameter("@Mes_consul", SqlDbType.VarChar)
                            {
                                Value = periodo
                            },
                            new SqlParameter("@Fecha", SqlDbType.VarChar)
                            {
                                Value = fec_sp
                            },
                        }, "pa_selDatosLiquidacion");
                        var ficha = usuario.id_usu;
                        if (encryptDocument == "S")
                        {
                            pdfStamper.SetEncryption(Encoding.ASCII.GetBytes(ficha), Encoding.ASCII.GetBytes("PERMICONTRATOS"), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
                        }
                        var campo = LoadData("select tag, campo,label,id_cliente, orden  from configPDF where (id_cliente = -1 or id_cliente =" + cliente.id_cliente + ") order by tag, orden asc").ToList();
                        Fill_pdf(datos_liquidacion, campo, pdfFormFields, fecha); // funcion para llenado de pdf

                        //Estampar imagen de cliente dinamicamente
                        if (SesionLogin().id_cliente != 1)
                        {
                            var estampoImg = pdfStamper.GetOverContent(1);
                            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMLOGOCLI" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                            image.SetAbsolutePosition(25, 730);
                            float percentage = 0.0f;
                            percentage = 100 / image.Width;
                            image.ScalePercent(percentage * 120);
                            estampoImg.AddImage(image);
                        }


                        pdfStamper.FormFlattening = false;
                        pdfStamper.MoreInfo       = new Dictionary <string, string>()
                        {
                            { "Title", "Liquidación_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf" }
                        };
                        pdfStamper.Close();
                        pdfReader.Close();
                        Response.AppendHeader("Content-Disposition", "inline; filename=Liquidación_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf");
                        return(File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf));
                    }
                    else if (type == TIPO_CERTIFICADO_ANTIGUEDAD)
                    {
                        pdfReader     = new PdfReader(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMCERTANT" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                        pdfStamper    = new PdfStamper(pdfReader, ms);
                        pdfFormFields = pdfStamper.AcroFields;
                        var datosCertAntiguedad = LoadData("EXEC  [dbo].[pa_selDatosCertAntiguedad] @USU_ID = N'" + usuario.id_usu + "',@NOM_CLIENTE_DB = N'" + cliente.Nom_cor_emp + "' ");
                        var Texto_Super         = helper.Get_TextCertificado("C_ANTIGUEDAD", datosCertAntiguedad, usuario);
                        var fec_actu            = DateTime.Now.ToString("dd MMMM yyyy");
                        var pie_qr = "CERTIFICADO EMITIDO POR PAYROLL MANAGEMENT SYSTEM\nLa institución o persona ante quien se presente este certificado\npodrá validar su autenticidad mediante el escaneo del codigo QR.";
                        fec_actu = "En Santiago, " + fec_actu;
                        pdfFormFields.SetField("Texto_Super", Texto_Super);
                        pdfFormFields.SetField("fec_actu", fec_actu);
                        pdfFormFields.SetField("pie_qr", pie_qr);
                        var pdfContentByte2         = pdfStamper.GetOverContent(1);
                        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMLOGOCLI" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                        image.SetAbsolutePosition(20, 730);
                        float percentage = 0.0f;
                        percentage = 100 / image.Width;
                        image.ScalePercent(percentage * 150);
                        pdfContentByte2.AddImage(image);
                        if (id_usu == 0)
                        {
                            var       fechaQR    = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                            var       mod11      = Helper.digitoVerificador(Int64.Parse(fechaQR));
                            var       cadena     = fechaQR + "_" + "o" + "_" + mod11 + "_" + usuario.id_usu + "_" + cliente.Nom_cor_emp;
                            var       encriptado = SeguridadUtilidades.Encriptar(cadena);
                            string    url        = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
                            var       QRfinal    = url + "/" + "ValidaDocumento" + "/" + "validaQR" + "?" + "token=" + HttpUtility.UrlEncode(encriptado);
                            QrEncoder qrEncoder  = new QrEncoder(ErrorCorrectionLevel.M);
                            QrCode    qrcode     = new QrCode();
                            qrEncoder.TryEncode(QRfinal, out qrcode);
                            GraphicsRenderer Renderder = new GraphicsRenderer(new FixedCodeSize(50, QuietZoneModules.Zero), Brushes.Black, Brushes.White);
                            MemoryStream     MS        = new MemoryStream();
                            Renderder.WriteToStream(qrcode.Matrix, ImageFormat.Jpeg, MS);
                            var imagentemporal       = new Bitmap(MS);
                            var pdfContentByte       = pdfStamper.GetOverContent(1);
                            iTextSharp.text.Image QR = iTextSharp.text.Image.GetInstance(imagentemporal, ImageFormat.Jpeg);
                            QR.SetAbsolutePosition(500, 40);
                            pdfContentByte.AddImage(QR);
                        }
                        pdfStamper.FormFlattening = false;
                        pdfStamper.MoreInfo       = new Dictionary <string, string>()
                        {
                            { "Title", "Certificado_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf" }
                        };
                        pdfStamper.Close();
                        pdfReader.Close();
                        Response.AppendHeader("Content-Disposition", "inline; filename=" + "Certificado_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf");
                        return(File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf));
                    }
                    if (type == TIPO_OTROS)
                    {
                        var documento = db.Documento.FirstOrDefault(p => p.id_doc == id_doc);
                        Response.AppendHeader("Content-Disposition", "inline; filename=" + documento.nombre_original);
                        using (FileStream file = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(documento.ruta), FileMode.Open, FileAccess.Read))
                        {
                            byte[] bytes = new byte[file.Length];
                            file.Read(bytes, 0, (int)file.Length);
                            ms.Write(bytes, 0, (int)file.Length);
                        }
                        return(File(ms.ToArray(), MimeMapping.GetMimeMapping(System.Web.Hosting.HostingEnvironment.MapPath(documento.ruta))));
                    }
                    if (type == TIPO_CONTRATO_ANEXO || type == TIPO_CONTRATO || type == TIPO_CONTRATO_OFERTA)
                    {
                        var doc        = db.Documento.FirstOrDefault(p => p.id_doc == id_doc && p.categoria == type);
                        var contraseña = db.Usuario.FirstOrDefault(p => p.id == doc.id_usu).id_usu;
                        Response.AppendHeader("Content-Disposition", "inline; filename=" + doc.nombre_original);
                        return(File(pdfDocEncrypt(doc.ruta, contraseña, encryptDocument).ToArray(), MimeMapping.GetMimeMapping(System.Web.Hosting.HostingEnvironment.MapPath(doc.ruta))));
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch (Exception e)
                {
                    return(JsonError("Ocurrió un problema con su solicitud, por favor contacte a IT", e));
                }
            }
        }
Exemplo n.º 10
0
 public Helper(Db_Entities _db)
 {
     this._db = _db;
 }
        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            USERS.RemoveAll(p => p.SessionExpires < DateTime.Now);
            string AuthCookieClientValue = "";

            if (HttpContext.Current.Request.Cookies["AuthCookieClient"] != null && HttpContext.Current.Request.Cookies["AuthCookieClient"][HttpUtility.UrlEncode(SeguridadUtilidades.Encriptar(username))] != null)
            {
                AuthCookieClientValue = SeguridadUtilidades.Desencriptar(HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["AuthCookieClient"][HttpUtility.UrlEncode(SeguridadUtilidades.Encriptar(username))]));
            }
            var _user = USERS.Where(p => p.clientUser.Nom_cor_emp == AuthCookieClientValue && p.user.id_usu == username).Take(1);

            if (_user.Count() > 0)
            {
                var u = _user.FirstOrDefault();
                return(new UsuarioMembership(u.user, u.roles, u.param, u.clientUser, u.clientsUser));
            }

            using (var db = new Db_Entities())
            {
                var user = (from u in db.Usuario
                            join c in db.Cliente on u.id_cliente equals c.id_cliente
                            where (c.estado == "1" && u.estado == 1) &&
                            (u.id_usu == username && c.Nom_cor_emp == AuthCookieClientValue.Trim())
                            select new { u, c }).FirstOrDefault();
                if (user == null)
                {
                    user = (from u in db.Usuario
                            join c in db.Cliente on u.id_cliente equals c.id_cliente
                            where (c.estado == "1" && u.estado == 1) &&
                            (u.id_usu == username)
                            select new { u, c }).FirstOrDefault();
                }

                var roles            = db.Permisos.Where(o => o.id_usu == user.u.id).ToList();
                var param            = db.parametros.Where(o => o.grupo == "PERMI").ToList();
                var Clientes_usuario = (from c in db.Cliente
                                        join u in db.Usuario on c.id_cliente equals u.id_cliente
                                        where u.id_usu == user.u.id_usu &&
                                        c.estado == "1" && u.estado == 1
                                        orderby c.nom_emp ascending
                                        select c).ToList();
                HttpCookie AuthCookieClient;
                if (HttpContext.Current.Request.Cookies["AuthCookieClient"] != null)
                {
                    AuthCookieClient = HttpContext.Current.Request.Cookies["AuthCookieClient"];
                    AuthCookieClient[HttpUtility.UrlEncode(SeguridadUtilidades.Encriptar(user.u.id_usu))] = HttpUtility.UrlEncode(SeguridadUtilidades.Encriptar(user.c.Nom_cor_emp));
                }
                else
                {
                    AuthCookieClient = new HttpCookie("AuthCookieClient");
                    AuthCookieClient[HttpUtility.UrlEncode(SeguridadUtilidades.Encriptar(user.u.id_usu))] = HttpUtility.UrlEncode(SeguridadUtilidades.Encriptar(user.c.Nom_cor_emp));
                }
                AuthCookieClient.Expires = DateTime.Now.AddYears(1);
                HttpContext.Current.Response.Cookies.Add(AuthCookieClient);
                deleteFromCacheUSER(user.u.id_usu);
                USERS.Add(new SessionUser()
                {
                    user = user.u, clientsUser = Clientes_usuario, clientUser = user.c, param = param, roles = roles, SessionExpires = DateTime.Now.AddMinutes(5)
                });
                return(user == null ? null : new UsuarioMembership(user.u, roles, param, user.c, Clientes_usuario));
            }
        }