private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                USUARIOS u = new USUARIOS();

                u.ID_Personal = Convert.ToInt32(IdPersonal);
                u.UserName    = txtusuario.Text.Trim();
                u.Pass        = txtcontrasena.Text.Trim();
                u.Estado      = Convert.ToInt32(EstadoUsuario);

                R_Humanos.ModificarUsuario(u);
                MessageBox.Show("Usuario Modificado correctamente");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public ActionResult Create([Bind(Include = "ID_USUARIO,CONTRASEÑA,TIPO,ID_EMPLEADO,ACTIVO")] USUARIOS uSUARIOS)
        {
            if (Session["MiUsuario"] != null && Session["MiTipo"] != null)
            {
                if (ModelState.IsValid)
                {
                    db.USUARIOS.Add(uSUARIOS);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }

                ViewBag.ID_EMPLEADO = new SelectList(db.EMPLEADOS, "ID_EMPLEADO", "DNI", uSUARIOS.ID_EMPLEADO);
                return(View(uSUARIOS));
            }
            else
            {
                return(RedirectToAction("Index", "Login"));
            }
        }
Esempio n. 3
0
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     try
     {
         base.OnActionExecuting(filterContext);
         usuarios = (USUARIOS)HttpContext.Current.Session["user"];
         if (usuarios == null)
         {
             if (filterContext.Controller is AccesoController == false)
             {
                 filterContext.HttpContext.Response.Redirect("/Acceso/Login");
             }
         }
     }
     catch (Exception)
     {
         filterContext.Result = new RedirectResult("/Acceso/Login");
     }
 }
Esempio n. 4
0
        public ActionResult Edit(long?id)
        {
            USUARIOS perfil = (USUARIOS)Session["LoginCredentials"];
            //if ((long?)perfil.ID_USUARIO == null)
            //{
            //    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            //}
            CLIENTES cLIENTES = db.CLIENTES.Find(perfil.ID_USUARIO);

            if (cLIENTES == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ID_COMUNA  = new SelectList(db.COMUNAS, "ID_COMUNA", "COMUNA", cLIENTES.ID_COMUNA);
            ViewBag.ID_TIPO    = new SelectList(db.TIPO_CLIENTE, "ID_TIPO_CLIENTE", "NOMBRE_TIPO", cLIENTES.ID_TIPO);
            ViewBag.ID_PLAN    = new SelectList(db.PLAN_PAGO, "ID_PAGO", "PLAN", cLIENTES.ID_PLAN);
            ViewBag.ID_USUARIO = new SelectList(db.USUARIOS, "ID_USUARIO", "USER", cLIENTES.ID_USUARIO);
            return(View(cLIENTES));
        }
        public ActionResult Login(String usuario, String pass)
        {
            ModeloUsuarios modelo = new ModeloUsuarios();
            USUARIOS       user   = modelo.ExisteUsuario(usuario, pass);

            if (user != null)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.userName, DateTime.Now, DateTime.Now.AddHours(1), true, "", FormsAuthentication.FormsCookiePath);
                String     datosCifrados         = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie("cookieUsuario", datosCifrados);
                Response.Cookies.Add(cookie);
                return(RedirectToAction("Acceso", "Validacion"));
            }
            else
            {
                ViewBag.Mensaje = "Usuario/Contraseña incorrecta!";
            }
            return(View());
        }
        public ActionResult Login(string login, string senha)
        {
            string   senhaCrypto = new Crypto.Crypto().Encrypt(senha);
            USUARIOS uSUARIOS    = db.USUARIOS.FirstOrDefault(x => (x.CPF == login || x.EMAIL == login) && x.SENHA == senhaCrypto);

            if (uSUARIOS != null)
            {
                Session["Usuario"] = uSUARIOS;
                Session["Nome"]    = uSUARIOS.NOME;

                if (((USUARIOS)Session["Usuario"]).TIPO_ACESSO == 2)
                {
                    return(RedirectToAction("ConsultasMedico", "CONSULTAS"));
                }

                return(RedirectToAction("Agendadas", "CONSULTAS"));
            }

            return(RedirectToAction("Index", "LOGIN", new { mensagem = "Usuario ou senha invalidos!" }));
        }
Esempio n. 7
0
        async void DeixarSeguirUsuario(object s)
        {
            int IdUsuario = (int)s;

            try
            {
                using (APIHelper API = new APIHelper())
                {
                    await API.PUT("api/usuario/deixar-seguir/" + IdUsuario, null);
                }

                USUARIOS.First(uu => uu.Id == IdUsuario).Sigo = false;
            }
            catch (HTTPException EX)
            {
            }
            catch (Exception EX)
            {
            }
        }
 // GET: USUARIOS/Details/5
 public ActionResult Details(string id)
 {
     if (Session["MiUsuario"] != null && Session["MiTipo"] != null)
     {
         if (id == null)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
         }
         USUARIOS uSUARIOS = db.USUARIOS.Find(id);
         if (uSUARIOS == null)
         {
             return(HttpNotFound());
         }
         return(View(uSUARIOS));
     }
     else
     {
         return(RedirectToAction("Index", "Login"));
     }
 }
Esempio n. 9
0
 // - - - - - - - - - - - - - - - - - - - - - Abre opcion BORRA entidad
 private void eliminarToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (dataGridViewListaSocios.CurrentRow != null && dataGridViewListaSocios.CurrentRow.Index >= 0)
     {
         USUARIOS     _entidad = (USUARIOS)dataGridViewListaSocios.CurrentRow.DataBoundItem;
         String       mnsj     = "Está seguro de eliminar definitivamente a " + _entidad.email + " ?";
         DialogResult isOK     = MessageBox.Show(mnsj, "Atención", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
         if (isOK == DialogResult.OK)
         {
             mnsj = DBAccess.UsuariosORM.DeleteEntidad(_entidad);
             if (!mnsj.Equals(""))
             {
                 MessageBox.Show(mnsj, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             else
             {
                 loadDataToGrid();
             }
         }
     }
 }
 // GET: USUARIOS/Edit/5
 public ActionResult Edit(string id)
 {
     if (Session["MiUsuario"] != null && Session["MiTipo"] != null)
     {
         if (id == null)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
         }
         USUARIOS uSUARIOS = db.USUARIOS.Find(id);
         if (uSUARIOS == null)
         {
             return(HttpNotFound());
         }
         ViewBag.ID_EMPLEADO = new SelectList(db.EMPLEADOS, "ID_EMPLEADO", "DNI", uSUARIOS.ID_EMPLEADO);
         return(View(uSUARIOS));
     }
     else
     {
         return(RedirectToAction("Index", "Login"));
     }
 }
        /// <summary>
        /// Converts this instance of <see cref="Usuarios"/> to an instance of <see cref="USUARIOS"/>.
        /// </summary>
        /// <param name="dto"><see cref="Usuarios"/> to convert.</param>
        public static USUARIOS ToTable(this Usuarios dto)
        {
            if (dto == null)
            {
                return(null);
            }

            var entity = new USUARIOS();

            entity.id              = dto.id;
            entity.PrimerNombre    = dto.PrimerNombre;
            entity.SegundoNombre   = dto.SegundoNombre;
            entity.PrimerApellido  = dto.PrimerApellido;
            entity.SegundoApellido = dto.SegundoApellido;
            entity.Usuario         = dto.Usuario;
            entity.Fecha_creacion  = DateTime.Now;

            dto.OnEntity(entity);

            return(entity);
        }
Esempio n. 12
0
        public void CreateUsuario(UsuarioDTO usuario)
        {
            try
            {
                using (LOGINEntities entities = new LOGINEntities())
                {
                    USUARIOS u = new USUARIOS();
                    u.USUARIO     = usuario.Usuario;
                    u.NOMBRE      = usuario.Nombre;
                    u.NOMBRE_AREA = usuario.NombreArea;
                    u.CONTRASENIA = usuario.Contrasenia;

                    entities.USUARIOS.Add(u);
                    entities.SaveChanges();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Converts this instance of <see cref="USUARIOS"/> to an instance of <see cref="Usuarios"/>.
        /// </summary>
        /// <param name="entity"><see cref="USUARIOS"/> to convert.</param>
        public static Usuarios ToModel(this USUARIOS entity)
        {
            if (entity == null)
            {
                return(null);
            }

            var dto = new Usuarios();

            dto.id              = entity.id;
            dto.PrimerNombre    = entity.PrimerNombre;
            dto.SegundoNombre   = entity.SegundoNombre;
            dto.PrimerApellido  = entity.PrimerApellido;
            dto.SegundoApellido = entity.SegundoApellido;
            dto.Usuario         = entity.Usuario;
            dto.Fecha_creacion  = entity.Fecha_creacion;

            entity.OnDTO(dto);

            return(dto);
        }
Esempio n. 14
0
 public static bool loggin(string Usuario, string Contraceña)
 {
     try
     {
         using (CapaDatos.bulonera2Entities1 db = new CapaDatos.bulonera2Entities1())
         {
             UsuarioActual = (from x in db.USUARIOS where x.nombre_usuario == Usuario && x.contraseña == Contraceña select x).FirstOrDefault();
             if (UsuarioActual != null)
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
        // GET: USUARIOS/Details/5
        public ActionResult Details(decimal id)
        {
            metodo     = "LEER";
            datoSesion = (DatoSesion)Session["datoSesion"];
            if (!datoSesion.RevisarPermiso(nombre, metodo))
            {
                ViewBag.funcion = datoSesion.getFuncion(nombre);
                var users = db.USUARIOS.Include(u => u.ROLES);
                return(View("Index", users.ToList()));
            }
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            USUARIOS uSUARIOS = db.USUARIOS.Find(id);

            if (uSUARIOS == null)
            {
                return(HttpNotFound());
            }
            return(View(uSUARIOS));
        }
Esempio n. 16
0
        // GET: USUARIOS/Edit/5
        public ActionResult Edit(long?id)
        {
            if (Session["LoginCredentials"] == null)
            {
                Response.Redirect("/USUARIOS/Login");
            }
            ;
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            USUARIOS uSUARIOS = db.USUARIOS.Find(id);

            if (uSUARIOS == null)
            {
                return(HttpNotFound());
            }
            ViewBag.RUT    = new SelectList(db.ASISTENTES, "RUT", "NOMBRES", uSUARIOS.ASISTENTES);
            ViewBag.RUT    = new SelectList(db.CLIENTES, "RUT", "NOMBRE_RAZON_SOCIAL", uSUARIOS.CLIENTES);
            ViewBag.ID_ROL = new SelectList(db.TIPO_ROL, "ID_ROL", "NOMBRE_ROL", uSUARIOS.ID_ROL);
            return(View(uSUARIOS));
        }
        public ActionResult Edit(UsuarioViewModel usuarioViewModel)
        {
            USUARIOS usu = this.Convertir(usuarioViewModel);
            {
                try
                {
                    using (UnidadDeTrabajo <USUARIOS> unidad = new UnidadDeTrabajo <USUARIOS>(new BDContext()))
                    {
                        unidad.genericDAL.Update(usu);
                        unidad.Complete();
                    }
                    TempData["mensaje"] = "Registro modificado satisfactoriamente";
                    return(RedirectToAction("Index"));
                }
                catch (Exception)
                {
                    TempData["mensaje"] = "Error al modificar el registro";

                    return(RedirectToAction("Edit"));
                }
            }
        }
Esempio n. 18
0
    protected void btnEliminaUserDep_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
        {
            using (Entities c = new Entities())
            {
                try
                {
                    string id = (Request["__EVENTARGUMENT"]);

                    USUARIOS usuario = c.USUARIOS.Find(id);

                    usuario.DEPARTAMENTOID = null;
                    c.USUARIOS.Attach(usuario);
                    c.Entry(usuario).State = EntityState.Modified;
                    c.SaveChanges();

                    SuccessMessage         = "Usuario eliminado correctamente.";
                    successMessage.Visible = true;
                    logger.Info("Usuario: " + usuario.USUARIOID + " desasignado del dpto: " + Convert.ToInt32(Request["id"]));

                    //No eliminamos el usuario porque tendrá seguramente información asociada de contenido (autor...), le desasignamos el departamento

                    /*c.USUARIOS.Remove(u);
                     * AspNetUsers anu = c.AspNetUsers.Find(id);
                     * c.AspNetUsers.Remove(anu);
                     * c.SaveChanges();
                     * Response.Redirect("AdmUsuariosDep?id=" + Request["id"] + "&m=" + "Usuario eliminado correctamente.", false);*/
                }
                catch (Exception ex)
                {
                    ErrorMessage         = "Error al eliminar el usuario.";
                    errorMessage.Visible = true;
                    logger.Error("ERROR: AdmnUsuariosDep.aspx Error al eliminar usuario " + Request["__EVENTARGUMENT"] + ". Error: " + ex.Message + " " + ex.InnerException);
                    Notificaciones.NotifySystemOps(ex);
                }
            }
        }
    }
Esempio n. 19
0
 public IHttpActionResult UpdateUser([FromBody] USUARIOS user)
 {
     if (ModelState.IsValid)
     {
         var id            = user.Id;
         var usuarioExiste = dbcontext.USUARIOS.Count(c => c.Id == id) > 0;
         if (usuarioExiste)
         {
             dbcontext.Entry(user).State = EntityState.Modified;
             dbcontext.SaveChanges();
             return(Ok());
         }
         else
         {
             return(NotFound());
         }
     }
     else
     {
         return(BadRequest());
     }
 }
Esempio n. 20
0
        public USUARIO_INFO get_info(string NOM_USUARIO, string CONTRASENIA)
        {
            USUARIO_INFO info = new USUARIO_INFO();

            using (Entities_general Context = new Entities_general())
            {
                USUARIOS Entity = Context.USUARIOS.FirstOrDefault(q => q.USUARIO == NOM_USUARIO && q.CLAVE == CONTRASENIA);
                if (Entity == null)
                {
                    return(null);
                }
                info = new USUARIO_INFO
                {
                    USUARIO1 = Entity.USUARIO,
                    CLAVE    = Entity.CLAVE,
                    CODIGO   = Entity.CODIGO,
                    ROL_APRO = Entity.ROL_APRO,
                    NOMBRE   = Entity.NOMBRE
                };
            }
            return(info);
        }
Esempio n. 21
0
        public ActionResult ActualizarEstudiante(USUARIOS estudiante)
        {
            USUARIOS estudianteActualizado = db.USUARIOS.Find(estudiante.ID_USUARIO);

            if (!ModelState.IsValid)
            {
                ViewBag.institucion = db.INSTITUCION.ToList();
                return(View(estudiante)); // returns the view with errors
            }

            ViewBag.institucion = db.INSTITUCION.ToList();

            estudianteActualizado.APELLIDO1      = estudiante.APELLIDO1;
            estudianteActualizado.APELLIDO2      = estudiante.APELLIDO2;
            estudianteActualizado.NOMBRE         = estudiante.NOMBRE;
            estudianteActualizado.TELEFONO       = estudiante.TELEFONO;
            estudianteActualizado.ID_INSTITUCION = estudiante.ID_INSTITUCION;

            db.Entry(estudianteActualizado).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            return(RedirectToAction("RegistrarEstudiante"));
        }
Esempio n. 22
0
        private void dataGridViewListaSocios_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // obtiene los valores de objeto de la fila
            USUARIOS _entidad = (USUARIOS)dataGridViewListaSocios.Rows[e.RowIndex].DataBoundItem;

            // controla valor de estadoi del objeto
            if (e.ColumnIndex == 3) // Estado string Activo / Inactivo
            {
                e.CellStyle.ForeColor = Color.White;
                if (_entidad.estado == 0)
                {
                    e.CellStyle.SelectionBackColor = Color.Red;
                    e.CellStyle.BackColor          = Color.Red;
                    e.Value = "Inactive";
                }
                else
                {
                    e.CellStyle.SelectionBackColor = Color.ForestGreen;
                    e.CellStyle.BackColor          = Color.ForestGreen;
                    e.Value = "Active";
                }
            }
        }
        public async Task <IHttpActionResult> PutUSUARIOS(decimal id, USUARIOS uSUARIOS)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != uSUARIOS.IDUSUARIO)
            {
                return(BadRequest());
            }

            db.Entry(uSUARIOS).State = EntityState.Modified;

            try
            {
                List <String> alerta = new List <string> {
                    "Modificacion Exitosa"
                };
                await db.SaveChangesAsync();

                return(Ok(alerta));//nose si quedran que regrese algo :v a esperar nomas.
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!USUARIOSExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 24
0
        public ActionResult CompletarPerfil()
        {
            USUARIOS _UsuarioLogued = (USUARIOS)Session["LoginCredentials"];

            if (_UsuarioLogued.CLIENTES.Count() == 0)
            {
                ViewBag.ID_COMUNA  = new SelectList(db.COMUNAS, "ID_COMUNA", "COMUNA");
                ViewBag.ID_TIPO    = new SelectList(db.TIPO_CLIENTE, "ID_TIPO_CLIENTE", "NOMBRE_TIPO");
                ViewBag.ID_PLAN    = new SelectList(db.PLAN_PAGO, "ID_PAGO", "PLAN");
                ViewBag.ID_USUARIO = new SelectList(db.USUARIOS, "ID_USUARIO", "USER");
                return(View());
            }

            //CLIENTES cLIENTES = db.CLIENTES.Find(_UsuarioLogued.CLIENTES.Where(w => w.ID_USUARIO == _UsuarioLogued.ID_USUARIO));
            //if (cLIENTES == null)
            //{
            //    return HttpNotFound();
            //}
            //ViewBag.ID_COMUNA = new SelectList(db.COMUNAS, "ID_COMUNA", "COMUNA", cLIENTES.ID_COMUNA);
            //ViewBag.ID_TIPO = new SelectList(db.TIPO_CLIENTE, "ID_TIPO_CLIENTE", "NOMBRE_TIPO", cLIENTES.ID_TIPO);
            //ViewBag.ID_PLAN = new SelectList(db.PLAN_PAGO, "ID_PAGO", "PLAN", cLIENTES.ID_PLAN);
            //ViewBag.ID_USUARIO = new SelectList(db.USUARIOS, "ID_USUARIO", "USER", cLIENTES.ID_USUARIO);
            return(View());
        }
Esempio n. 25
0
        public void Inicial()
        {
            using (Entities c = new Entities())
            {
                try
                {
                    /*Falta AspNetUsers  */
                    u = c.USUARIOS.FirstOrDefault(); //cogemos el primer usuario que haya en la BBDD
                }
                catch (Exception ex)
                {
                    Assert.Fail(" ERROR USUARIO" + ex.Message);
                }

                /*
                 * try
                 * {
                 *  OBJETIVO o = new OBJETIVO()
                 *  {
                 *      AUTOR_CREACION = u,
                 *      DEPARTAMENTO_ID = 1,
                 *      ESTADO_VALIDACION_ID = ESTADOS_VALIDACION.PDTE_VALIDAR,
                 *      FECHA_CREACION = DateTime.Now,
                 *      TIPO_CAMBIO_CONTENIDO_ID = TIPO_CAMBIO_CONTENIDO.ALTA,
                 *      VISIBLE = false
                 *  };
                 *  c.CONTENIDO.Add(o);
                 *  c.SaveChanges();
                 *
                 * }
                 * catch (Exception ex)
                 * {
                 *  Assert.Fail(" ERROR OBJETIVO: " + ex.Message);
                 * }*/
            }
        }
Esempio n. 26
0
        //Método para Javascript para eliminar una persona, se llama en el jquery
        public ActionResult eliminarPersona(string id)
        {
            var correos = db.CORREOS.Where(c => c.CEDULA == id);//elimina los correos asociados al usuario

            foreach (var c in correos)
            {
                db.CORREOS.Remove(c);
            }
            var telefonos = db.TELEFONOS.Where(t => t.CEDULA == id);//elimina los telefonos asociados al usuario

            foreach (var t in telefonos)
            {
                db.TELEFONOS.Remove(t);
            }
            USUARIOS persona = db.USUARIOS.Find(id);
            string   aspId   = persona.ID_ASP;

            db.USUARIOS.Remove(persona);//elimina al usuario
            var user = db.AspNetUsers.Find(aspId);

            db.AspNetUsers.Remove(user);//elimina al usuario de ASP (asociado) del sistema
            db.SaveChanges();
            return(Json(new { success = true }));
        }
Esempio n. 27
0
        public ActionResult Login(USUARIOS _login)
        {
            try
            {
                TIPO_ROL Rol = new TIPO_ROL();
                using (ODAO Menu = new ODAO())
                {
                    ViewBag.Rol = new SelectList(Menu.TIPO_ROL.ToList(), "ID_ROL", "NOMBRE_ROL", "CATEGORIA", 1);
                }

                if (ModelState.IsValid) //validating the user inputs
                {
                    string cualquira = Request["LoginType"];
                    string hash      = ConfigurationManager.AppSettings["Encryption"];
                    bool   isExist   = false;

                    _login.TIMESTAMP = DateTime.Now;

                    _login.IP = System.Web.HttpContext.Current.Request.UserHostAddress;

                    if (cualquira != null)
                    {
                        switch (Request["LoginType"].ToString())
                        {
                        case ("Login"):
                            using (ODAO _entity = new ODAO())      // out Entity name is "SampleMenuMasterDBEntites"
                            {
                                string passEncriptado = Encrypt.EncryptString(_login.PASS, hash);
                                isExist = _entity.USUARIOS.Where(x => x.USER.Trim().ToLower() == _login.USER.Trim().ToLower() && x.PASS.ToString() == passEncriptado.ToString()).Any();     //validating the user name in tblLogin table whether the user name is exist or not
                                if (isExist)
                                {
                                    USUARIOS _loginCredentials = _entity.USUARIOS.Where(x => x.USER.Trim().ToLower() == _login.USER.Trim().ToLower()).FirstOrDefault(); // Get the login user details and bind it to LoginModels class

                                    FormsAuthentication.SetAuthCookie(_loginCredentials.USER, false);                                                                   // set the formauthentication cookie
                                    Session["LoginCredentials"] = _loginCredentials;                                                                                    // Bind the _logincredentials details to "LoginCredentials" session
                                    Session["MenuMaster"]       = db.MENU.Include("MENU_SUB").Where(w => w.ID_ROL == _loginCredentials.ID_ROL).ToList();                //Bind the _menus list to MenuMaster session
                                    Session["UserName"]         = _loginCredentials.USER;
                                    Session["Binary_File"]      = _login.BINARY_IMAGE;
                                    ViewBag.USUARIO_LOG         = _loginCredentials;


                                    var asd = _entity.ASISTENTES.Where(x => x.ID_USUARIO == _loginCredentials.ID_USUARIO).FirstOrDefault();

                                    if (_entity.CLIENTES.Where(x => x.ID_USUARIO == _loginCredentials.ID_USUARIO).FirstOrDefault() == null && _loginCredentials.ID_ROL == 41)
                                    {
                                        ViewBag.Message = "Debe Competar Su Perfil de Cliente";     // personas
                                        return(RedirectToAction("CompletarPerfil", "CLIENTES"));
                                    }
                                    else if (_entity.CLIENTES.Where(x => x.ID_USUARIO == _loginCredentials.ID_USUARIO).FirstOrDefault() == null && _loginCredentials.ID_ROL == 61)
                                    {
                                        ViewBag.Message = "Debe Competar Su Perfil de Cliente";    // empresas
                                        return(RedirectToAction("CompletarPerfil", "CLIENTES"));
                                    }
                                    else if (_entity.ASISTENTES.Where(x => x.ID_USUARIO == _loginCredentials.ID_USUARIO).FirstOrDefault() == null && _loginCredentials.ID_ROL != 41 && _loginCredentials.ID_ROL != 61)
                                    {
                                        ViewBag.Message = "Debe Competar Su Perfil de ASISTENTE";    // ASISTENTE
                                        return(RedirectToAction("CompletarPerfil", "ASISTENTES"));
                                    }
                                    else
                                    {
                                        if (_loginCredentials.ID_ROL == 41 | _loginCredentials.ID_ROL == 61)
                                        {
                                            Session["PerfilCliente"] = _entity.CLIENTES.Where(x => x.ID_USUARIO == _loginCredentials.ID_USUARIO).FirstOrDefault();
                                            return(RedirectToAction("Index", "CLIENTES"));
                                        }
                                        else
                                        {
                                            return(RedirectToAction("Index", "ASISTENTES"));
                                        }
                                    }
                                }
                                else
                                {
                                    ViewBag.Message = "Las credenciales no son validas!...";
                                    return(View());
                                }
                            }

                        case ("Register"):
                            using (ODAO _entity = new ODAO())
                            {
                                isExist = _entity.USUARIOS.Where(x => x.USER.Trim().ToLower() == _login.USER.Trim().ToLower()).Any();
                                if (isExist)
                                {
                                    ViewBag.Message = "Este usuario ya existe en nuestros sistemas";
                                    return(View());
                                }
                                else
                                {
                                    HttpPostedFileBase File = Request.Files["IMG_PROFILE"];
                                    _login.IMG_PROFILE  = File.FileName;
                                    _login.BINARY_IMAGE = ConvertToByte(File);
                                    _login.PASS         = Encrypt.EncryptString(_login.PASS.ToString(), hash);
                                    db.USUARIOS.Add(_login);
                                    db.SaveChanges();

                                    return(View());
                                }
                            }

                        default:
                            return(View());
                        }
                    }
                }

                return(View());
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return(View());
            }
        }
Esempio n. 28
0
        public static void Actualizar_Clave_Usuario(USUARIOS obj)
        {
            D_Usuario Metodo = new D_Usuario();

            Metodo.Actualizar_Clave_Usuario(obj);
        }
Esempio n. 29
0
        public static void Insertar_Usuario(USUARIOS obj)
        {
            D_Usuario Metodo = new D_Usuario();

            Metodo.Insertar_Usuario(obj);
        }
Esempio n. 30
0
        public AuthenticationResult SignIn(String username, String password)
        {
            ContextType authenticationType = ContextType.Domain;
            var         DBContext          = new DBEntities();
            var         user = from USUARIOS in DBContext.USUARIOS where (USUARIOS.USUARIO == username) select USUARIOS;
            USUARIOS    u    = new USUARIOS();
            AUDITORIAS  au   = new AUDITORIAS();

            if (user.Any())
            {
                foreach (var iuser in user)
                {
                    u = iuser;
                }
            }
            else
            {
                u.CONTRASENA = password;
                u.USUARIO    = username;
                u.IDROLE     = 2;
                DBContext.USUARIOS.Add(u);
                DBContext.SaveChanges();
            }
            au.USUARIOS  = u;
            au.ACCION    = "LDAP_REQUEST";
            au.TIMESTAMP = DateTime.Now;
            DBContext.AUDITORIAS.Add(au);
            DBContext.SaveChanges();

            PrincipalContext principalContext = new PrincipalContext(authenticationType);
            bool             isAuthenticated  = false;
            UserPrincipal    userPrincipal    = new UserPrincipal(principalContext);

            userPrincipal.SamAccountName = username;
            var searcher = new PrincipalSearcher(userPrincipal);

            try
            {
                isAuthenticated = principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate);
                au           = new AUDITORIAS();
                au.USUARIOS  = u;
                au.ACCION    = "LDAP_CONNECT";
                au.TIMESTAMP = DateTime.Now;
                DBContext.AUDITORIAS.Add(au);
                DBContext.SaveChanges();
                if (isAuthenticated)
                {
                    userPrincipal = searcher.FindOne() as UserPrincipal;
                }
            }
            catch (Exception)
            {
                au           = new AUDITORIAS();
                au.USUARIOS  = u;
                au.ACCION    = "LDAP_FAILED";
                au.TIMESTAMP = DateTime.Now;
                DBContext.AUDITORIAS.Add(au);
                DBContext.SaveChanges();
                isAuthenticated = false;
                userPrincipal   = null;
            }

            if (!isAuthenticated || userPrincipal == null)
            {
                au           = new AUDITORIAS();
                au.USUARIOS  = u;
                au.ACCION    = "LDAP_BADLOGIN";
                au.TIMESTAMP = DateTime.Now;
                DBContext.AUDITORIAS.Add(au);
                DBContext.SaveChanges();
                return(new AuthenticationResult("Usuario o Contraseña incorrectos"));
            }

            if (userPrincipal.IsAccountLockedOut())
            {
                au           = new AUDITORIAS();
                au.USUARIOS  = u;
                au.ACCION    = "LDAP_LOCKED";
                au.TIMESTAMP = DateTime.Now;
                DBContext.AUDITORIAS.Add(au);
                DBContext.SaveChanges();
                return(new AuthenticationResult("Cuenta bloqueada"));
            }

            if (userPrincipal.Enabled.HasValue && userPrincipal.Enabled.Value == false)
            {
                au           = new AUDITORIAS();
                au.USUARIOS  = u;
                au.ACCION    = "LDAP_DISABLED";
                au.TIMESTAMP = DateTime.Now;
                DBContext.AUDITORIAS.Add(au);
                DBContext.SaveChanges();
                return(new AuthenticationResult("Cuenta deshabilitada"));
            }
            au           = new AUDITORIAS();
            au.USUARIOS  = u;
            au.ACCION    = "LDAP_SUCCESS";
            au.TIMESTAMP = DateTime.Now;
            DBContext.AUDITORIAS.Add(au);
            DBContext.SaveChanges();
            var identity = CreateIdentity(userPrincipal);

            authenticationManager.SignOut(MyAuthentication.ApplicationCookie);
            authenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = false
            }, identity);


            return(new AuthenticationResult());
        }