Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Data.Entity.Validation;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- using System.Web.Security;
- using ACCSOC.Models.Data;
- using ACCSOC.ViewModel;
- using System.Web.Configuration;
- using PagedList;
- using ACCSOC.Utils;
- using UFV.ACCSOC.Utils;
- using System.Data.Entity;
- namespace ACCSOC.Controllers
- {
- [Authorize]
- public class AccountController : BaseController
- {
- //Clave para la cache de Usuarios
- private const string KEY_CACHE_USUARIOS = "AllUsers";
- public static readonly int PageSize = 50;
- #region Assign Users UFV
- public ActionResult AllUsers(int? page, string filterText)
- {
- string key = KEY_CACHE_USUARIOS;
- int pageIndex = page.HasValue ? page.Value : 1;
- key = key + "_p" + pageIndex;
- FilterUsersVM filtros = GetNewFilterUsersVM(filterText);
- SendViewBagFilter(filtros);
- //Si hay filtro del nombre de usuarios
- if (!String.IsNullOrEmpty(filterText) || !String.IsNullOrWhiteSpace(filterText))
- {
- key = key + "_UsuarioBuscado_" + filterText;
- }
- AllUsersModel model = new AllUsersModel();
- var users = Membership.GetAllUsers();
- //Cache para los usuarios
- IEnumerable<UserModel> usuarios = GlobalCachingProvider.Instance.GetItem(key, false) as IEnumerable<UserModel>;
- //Si no hay usuarios en cache los obtenemos y los guardamos en cache
- if (usuarios == null)
- {
- usuarios = from user in users.OfType<MembershipUser>()
- orderby GetUserUfvCompleto((Guid)user.ProviderUserKey)
- select new UserModel()
- {
- UserKey = (Guid)user.ProviderUserKey,
- UserName = user.UserName,
- Email = user.Email,
- IsApproved = user.IsApproved,
- IsInternalUser = GetUserUfv((Guid)user.ProviderUserKey).IsInternalUser,
- Roles = ConcatWithComma(Roles.GetRolesForUser(user.UserName)),
- Name = GetUserUfvCompleto((Guid)user.ProviderUserKey)
- };
- //Si hemos filtrado por nombre del usuario
- if (!string.IsNullOrEmpty(filtros.filterText))
- {
- usuarios = usuarios.Where(user => UserNameCompare(GetUserUfvCompleto(user.UserKey), filtros.filterText)).OrderBy(user => user.UserName);
- }
- //Añadimos los datos en la cache
- GlobalCachingProvider.Instance.AddItem(key, usuarios, 86400);
- }
- int? numUsuarios = usuarios.Count();
- usuarios = usuarios
- .Skip((pageIndex - 1) * Constantes.PAGE_SIZE)
- .Take(Constantes.PAGE_SIZE)
- .ToList();
- model.usuariosList = usuarios.ToList();
- model.Users = new StaticPagedList<UserModel>(model.usuariosList, pageIndex, Constantes.PAGE_SIZE, numUsuarios.GetValueOrDefault());
- model.Filtros = filtros;
- return View(model);
- }
- #endregion
- #region Manage Users UFV
- protected bool UserNameCompare(string UserUfvCompleto, string filterText)
- {
- UserUfvCompleto = FormatUserReplace(UserUfvCompleto).ToLower();
- filterText = FormatUserReplace(filterText).ToLower();
- if (UserUfvCompleto.Contains(filterText))
- return true;
- return false;
- }
- protected string FormatUserReplace(string text)
- {
- string textFormat;
- textFormat = text.Replace("Á", "A");
- textFormat = textFormat.Replace("á", "a");
- textFormat = textFormat.Replace("É", "E");
- textFormat = textFormat.Replace("é", "e");
- textFormat = textFormat.Replace("Í", "I");
- textFormat = textFormat.Replace("í", "i");
- textFormat = textFormat.Replace("Ó", "O");
- textFormat = textFormat.Replace("ó", "o");
- textFormat = textFormat.Replace("Ú", "U");
- textFormat = textFormat.Replace("ú", "u");
- return textFormat;
- }
- protected string ConcatWithComma(string[] roles)
- {
- if (roles == null || roles.Length == 0)
- return string.Empty;
- StringBuilder builder = new StringBuilder(roles[0]);
- for (int i = 1; i < roles.Length; i++)
- builder.AppendFormat(", {0} ", roles[i]);
- return builder.ToString();
- }
- private IEnumerable<RolePerUser> GetRolesPerUser(string userName)
- {
- string[] allRoles = Roles.GetAllRoles();
- string[] userRoles = Roles.GetRolesForUser(userName);
- for (int i = 0; i < allRoles.Length; i++)
- yield return new RolePerUser()
- {
- Role = allRoles[i],
- IsIn = userRoles.Contains(allRoles[i])
- };
- }
- private IEnumerable<RolePerUser> GetRoles()
- {
- string[] allRoles = Roles.GetAllRoles();
- for (int i = 0; i < allRoles.Length; i++)
- yield return new RolePerUser()
- {
- Role = allRoles[i],
- IsIn = false
- };
- }
- public IEnumerable<Institucion> GetInstituciones()
- {
- CursoAcad cursoVigente = db.CursoAcad.First(t => t.cursoSeg == 1);
- IEnumerable<Institucion> instituciones = GlobalCachingProvider.Instance.GetItem("AllInstituciones", false) as IEnumerable<Institucion>; ;
- instituciones = repoFactory.GetInstitucionEntity().GetAll().Where(t => t.desact == false && t.cursoAcad.id == cursoVigente.id).OrderBy(t => t.denominacion);
- return instituciones;
- }
- public bool institucionSeleccionada(int? instSelect)
- {
- if (instSelect != null)
- {
- int listUsuarioInst = db.UsuarioInstitucion.Count(t => t.institucion.id == instSelect);
- if (listUsuarioInst != 0) return true;
- return false;
- }
- return false;
- }
- public bool isInInstictucion(bool isIn, int? instSelect)
- {
- if (isIn == true && instSelect == null) return true;
- return false;
- }
- public void crearUsuarioInstitucion(UserUfv usuario, int? instSelect)
- {
- UsuarioInstitucion usuarioInstitucion = new UsuarioInstitucion();
- usuarioInstitucion.user = usuario;
- usuarioInstitucion.institucion = db.Institucion.Find(instSelect);
- try
- {
- db.UsuarioInstitucion.Add(usuarioInstitucion);
- db.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- public ActionResult Edit(string userName)
- {
- MembershipUser user = Membership.GetUser(userName);
- if (Membership.GetUser().ProviderUserKey.Equals(user.ProviderUserKey))
- {
- UserUfv userUfv = GetUserUfv((Guid)user.ProviderUserKey);
- string roles = string.Empty;
- bool first = true;
- foreach (string rol in GetRolesPerUser(user.UserName).Where(rol => rol.IsIn).Select(rol => rol.Role))
- {
- if (!first) roles += ", ";
- roles += rol;
- first = false;
- }
- return View(new EditUserDataModel()
- {
- UserKey = (Guid)user.ProviderUserKey,
- UserName = user.UserName,
- Email = user.Email,
- Roles = roles,
- nombre = userUfv.nombre,
- apellido1 = userUfv.apellido1,
- apellido2 = userUfv.apellido2,
- despacho = userUfv.despacho,
- IsInternalUser = userUfv.IsInternalUser,
- IsProfSincronizado = userUfv.IsProfSincronizado
- });
- }
- else
- {
- return RedirectToAction("Index", "Asignacion");
- }
- }
- [HttpPost]
- public ActionResult Edit(EditUserDataModel user)
- {
- string errorEmail = string.Empty;
- try
- {
- if (ModelState.IsValid)
- {
- //Borramos la cache de los uaurios
- GlobalCachingProvider.Instance.RemoveItem("AllUsers");
- //Comprobar que el email sea único
- if (string.IsNullOrEmpty(Membership.GetUserNameByEmail(user.Email)) || user.UserName.ToLower().Equals((Membership.GetUserNameByEmail(user.Email)).ToLower()))
- {
- MembershipUser membershipUser = Membership.GetUser(user.UserKey);
- membershipUser.Email = user.Email;
- Membership.UpdateUser(membershipUser);
- UpdateUsuarioUfv(user.UserKey, user.nombre, user.apellido1, user.apellido2, user.despacho);
- if (CheckPermisosPorRoll(user.UserName))
- {
- return RedirectToAction("Index", "Asignacion");
- }
- return RedirectToAction("Index", "Asignacion");
- }
- else
- {
- ViewBag.ErrorEmail = "El email introducido ya existe. Por favor, introduzca otro.";
- }
- }
- }
- catch { }
- return View(user);
- }
- public ActionResult EditUser(Guid userKey)
- {
- MembershipUser user = Membership.GetUser(userKey);
- UserUfv userUfv = GetUserUfv((Guid)user.ProviderUserKey);
- return View(new EditUserModel()
- {
- UserKey = (Guid)user.ProviderUserKey,
- UserName = user.UserName,
- Email = user.Email,
- IsApproved = user.IsApproved,
- Roles = GetRolesPerUser(user.UserName),
- nombre = userUfv.nombre,
- apellido1 = userUfv.apellido1,
- apellido2 = userUfv.apellido2,
- despacho = userUfv.despacho,
- IsInternalUser = userUfv.IsInternalUser,
- IsProfSincronizado = userUfv.IsProfSincronizado,
- listInstitucion = GetInstituciones()
- });
- }
- [HttpPost]
- public ActionResult EditUser(EditUserModel user)
- {
- try
- {
- if (ModelState.IsValid)
- {
- if(isInInstictucion(user.Roles.Skip(2).First().IsIn, user.instSelectInstitucion))
- {
- ModelState.AddModelError("instSelectInstitucion", "* Introduzca institución");
- user.listInstitucion = GetInstituciones();
- return View(user);
- }
- if (institucionSeleccionada(user.instSelectInstitucion) == true)
- {
- ModelState.AddModelError("ErrorInstitucion", "La institución ya pertenece a un usuario");
- user.listInstitucion = GetInstituciones();
- return View(user);
- }
- if (string.IsNullOrEmpty(Membership.GetUserNameByEmail(user.Email)) || user.UserName.ToLower().Equals((Membership.GetUserNameByEmail(user.Email)).ToLower()))
- {
- MembershipUser membershipUser = Membership.GetUser(user.UserKey);
- membershipUser.Email = user.Email;
- membershipUser.IsApproved = user.IsApproved;
- Membership.UpdateUser(membershipUser);
- bool wasIn;
- foreach (RolePerUser role in user.Roles)
- {
- wasIn = Roles.IsUserInRole(user.UserName, role.Role);
- if (role.IsIn != wasIn)
- {
- if (wasIn) Roles.RemoveUserFromRole(user.UserName, role.Role);
- else Roles.AddUserToRole(user.UserName, role.Role);
- }
- }
- UserUfv userUfv = GetUserUfv((Guid)membershipUser.ProviderUserKey);
- IEnumerable<UsuarioInstitucion> usuarioInstitucion = db.UsuarioInstitucion.Where(t => t.user.id == userUfv.id);
- if (user.Roles.Skip(2).First().IsIn)
- {
- if (usuarioInstitucion.Count() == 0)
- {
- crearUsuarioInstitucion(userUfv, user.instSelectInstitucion);
- }
- else
- {
- usuarioInstitucion.Skip(0).First().user = userUfv;
- usuarioInstitucion.Skip(0).First().institucion = db.Institucion.Find(user.instSelectInstitucion);
- try
- {
- db.UsuarioInstitucion.Attach(usuarioInstitucion.Skip(0).First());
- db.Entry(usuarioInstitucion.Skip(0).First()).State = EntityState.Modified;
- db.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- else
- {
- if(usuarioInstitucion.Count() != 0)
- {
- try
- {
- db.UsuarioInstitucion.Attach(usuarioInstitucion.Skip(0).First());
- db.UsuarioInstitucion.Remove(usuarioInstitucion.Skip(0).First());
- db.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- }
- else
- {
- ViewBag.ErrorEmail = "El email introducido ya existe. Por favor, introduzca otro.";
- user.listInstitucion = GetInstituciones();
- return View(user);
- }
- }
- else
- {
- user.listInstitucion = GetInstituciones();
- return View(user);
- }
- }
- catch
- {
- user.listInstitucion = GetInstituciones();
- return View(user);
- }
- //Borramos la cache de los usuarios
- GlobalCachingProvider.Instance.RemoveItem("AllUsers");
- return RedirectToAction("AllUsers");
- }
- public ActionResult ResetPassword(Guid userKey)
- {
- MembershipUser membershipUser = Membership.GetUser(userKey);
- if (membershipUser.IsLockedOut)
- membershipUser.UnlockUser();
- string newPassword = membershipUser.ResetPassword();
- //Borramos la cache de los usuarios
- GlobalCachingProvider.Instance.RemoveItem("AllUsers");
- Membership.UpdateUser(membershipUser);
- return RedirectToAction("ResetPasswordSuccess", new ResetPasswordModel()
- {
- Email = membershipUser.Email,
- UserName = membershipUser.UserName,
- Password = newPassword,
- });
- }
- public ActionResult ResetPasswordSuccess(ResetPasswordModel model)
- {
- return View(model);
- }
- #endregion
- #region Autenticación
- protected string GenerateStandarPassword(string userName)
- {
- string pass;
- using (MD5 md5Has = MD5.Create()) { pass = GetMd5Hash(md5Has, userName); }
- return pass;
- }
- protected string GetUserByP1(string userP)
- {
- string user = string.Empty;
- foreach (char letra in userP) { user += TraducirLetra(letra); }
- return user;
- }
- protected char TraducirLetra(char letra)
- {
- string recibido = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
- string resultad = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- return resultad.ElementAt(recibido.IndexOf(letra));
- }
- protected bool VerifyMd5Hash(string user, string hashP2)
- {
- string clave = "qR2a7pmC";
- string internalString = user + clave + DateTime.Now.ToString("ddMMyyyy");
- using (MD5 md5Hash = MD5.Create())
- {
- string hashInternal = GetMd5Hash(md5Hash, internalString);
- // Create a StringComparer an compare the hashes.
- StringComparer comparer = StringComparer.OrdinalIgnoreCase;
- if (0 == comparer.Compare(hashInternal, hashP2))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- protected string GetMd5Hash(MD5 md5Hash, string internalString)
- {
- // Convert the input string to a byte array and compute the hash.
- byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(internalString));
- // Create a new Stringbuilder to collect the bytes
- // and create a string.
- StringBuilder sBuilder = new StringBuilder();
- // Loop through each byte of the hashed data
- // and format each one as a hexadecimal string.
- for (int i = 0; i < data.Length; i++)
- {
- sBuilder.Append(data[i].ToString("x2"));
- }
- // Return the hexadecimal string.
- return sBuilder.ToString();
- }
- // GET: /Account/Login
- [AllowAnonymous]
- public ActionResult Login()
- {
- return View();
- }
- public void UpgradePasswOracle()
- {
- bool changePasswordSucceeded = false;
- bool isLocked = false;
- UserUfv userUFV;
- foreach (MembershipUser actualUser in Membership.GetAllUsers())
- {
- try
- {
- isLocked = actualUser.IsLockedOut;
- if (isLocked)
- actualUser.UnlockUser();
- userUFV = GetUserUfv((Guid)actualUser.ProviderUserKey);
- if (userUFV.IsInternalUser)
- {
- if (actualUser.UserName.Equals("dvega"))
- {
- changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "Trip01multi");
- }
- else if (actualUser.UserName.Equals("ufv"))
- {
- changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "plataformaufv");
- }
- else if (actualUser.UserName.Equals("idiomas"))
- {
- changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "idiomas");
- }
- else if (actualUser.UserName.Equals("desarrollo"))
- {
- changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "desarrollo01");
- }
- else if (actualUser.UserName.Equals("rrii"))
- {
- changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "gdPolanco01");
- }
- }
- else
- {
- changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), GenerateStandarPassword(actualUser.UserName));
- }
- }
- catch (Exception) { }
- }
- } //Actualizar las contraseñas del Membership con el Provider Actual
- // POST: /Account/Login
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Login(LoginModel model, string returnUrl)
- {
- if (ModelState.IsValid)
- {
- if (Membership.ValidateUser(model.UserName, model.Password))
- {
- SetAuthCookie(Membership.GetUser(model.UserName), model.RememberMe);
- if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
- && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
- {
- return Redirect(returnUrl);
- }
- else
- {
- if (CheckPermisosPorRoll(model.UserName))
- {
- return RedirectToAction("AllUsers", "Account");
- }
- if (Roles.IsUserInRole(model.UserName, "Mentor") || Roles.IsUserInRole(model.UserName, "Profesor"))
- {
- return RedirectToAction("Index", "Seguimiento");
- }
- if (Roles.IsUserInRole(model.UserName, "Institucion"))
- {
- MembershipUser user = Membership.GetUser(model.UserName);
- UserUfv userufv = GetUserUfv((Guid)user.ProviderUserKey);
- IEnumerable<UsuarioInstitucion> usuarioInstitucions = db.UsuarioInstitucion.Where(p => p.user.id == userufv.id);
- return RedirectToAction("Index", "Programa", new { id = usuarioInstitucions.Skip(0).First().institucion.id });
- }
- else
- {
- return RedirectToAction("Index", "Asignacion");
- }
- }
- }
- }
- // If we got this far, something failed, redisplay form
- ModelState.AddModelError("", "El usuario o la contraseña introducidos son incorrectos.");
- return View(model);
- }
- protected bool CheckPermisosPorRoll(string userName)
- {
- string[] roles = Roles.GetRolesForUser(userName);
- // Aquí van todos los roles que se quieren determinar como agrupados
- if (roles.Contains(AppRoles.Administrador.ToString()))
- return true;
- return false;
- }
- protected virtual void SetAuthCookie(MembershipUser user, bool rememberMe)
- {
- string fullUserName = this.GetUserUfvCompleto((Guid)user.ProviderUserKey);
- /// In order to pickup the settings from config, we create a default cookie and use its values to create a new one.
- HttpCookie cookie = FormsAuthentication.GetAuthCookie(user.UserName, rememberMe);
- FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
- FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, fullUserName, ticket.CookiePath);
- string encTicket = FormsAuthentication.Encrypt(newTicket);
- /// Use existing cookie. Could create new one but would have to copy settings over...
- cookie.Value = encTicket;
- this.Response.Cookies.Add(cookie);
- }
- // POST: /Account/LogOff
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult LogOff()
- {
- FormsAuthentication.SignOut();
- return RedirectToAction("Login", "Account");
- }
- // GET: /Account/Register
- [AllowAnonymous]
- public ActionResult Register()
- {
- return View(new RegisterModel()
- {
- listInstitucion = GetInstituciones(),
- Roles = GetRoles()
- });
- }
- // POST: /Account/Register
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Register(RegisterModel model)
- {
- if (ModelState.IsValid)
- {
- if (isInInstictucion(model.Roles.Skip(2).First().IsIn, model.instSelectInstitucion))
- {
- ModelState.AddModelError("instSelectInstitucion", "* Introduzca institución");
- model.listInstitucion = GetInstituciones();
- return View(model);
- }
- if (institucionSeleccionada(model.instSelectInstitucion) == true)
- {
- ModelState.AddModelError("ErrorInstitucion", "La institución ya pertenece a un usuario");
- model.listInstitucion = GetInstituciones();
- return View(model);
- }
- // Attempt to register the user
- MembershipCreateStatus createStatus;
- //Comprobar email
- string emailRegistrado = Membership.GetUserNameByEmail(model.Email);
- //Si ese email pertenece a algun usuario, devuelvo un error
- if (String.IsNullOrEmpty(emailRegistrado))
- {
- Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
- }
- else
- {
- createStatus = MembershipCreateStatus.DuplicateEmail;
- }
- if (createStatus == MembershipCreateStatus.Success)
- {
- //Creamos un objeto Usuario
- UserUfv usuario = new UserUfv();
- //Agregamos los campos que va a tener
- usuario.nombre = model.nombre;
- usuario.apellido1 = model.apellido1;
- usuario.apellido2 = model.apellido2;
- usuario.id = (Guid)Membership.GetUser(model.UserName).ProviderUserKey;
- usuario.IsInternalUser = true;
- //Tratamos de agregarlo a la base de datos
- try
- {
- db.UserUfv.Add(usuario);
- db.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- bool wasIn;
- foreach (RolePerUser role in model.Roles)
- {
- wasIn = Roles.IsUserInRole(model.UserName, role.Role);
- if (role.IsIn != wasIn)
- {
- if (wasIn) Roles.RemoveUserFromRole(model.UserName, role.Role);
- else Roles.AddUserToRole(model.UserName, role.Role);
- }
- }
- if (model.Roles.Skip(2).First().IsIn)
- {
- crearUsuarioInstitucion(usuario, model.instSelectInstitucion);
- }
- //Borramos la cache de los usuarios
- GlobalCachingProvider.Instance.RemoveItem("AllUsers");
- return RedirectToAction("AllUsers", "Account");
- }
- else
- {
- ModelState.AddModelError("ErrorRegistro", ErrorCodeToString(createStatus));
- }
- }
- model.listInstitucion = GetInstituciones();
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- // GET: /Account/ChangePassword
- [Authorize]
- public ActionResult ChangePassword()
- {
- return View();
- }
- //
- // POST: /Account/ChangePassword
- [Authorize]
- [HttpPost]
- public ActionResult ChangePassword(LocalPasswordModel model)
- {
- if (ModelState.IsValid)
- {
- // ChangePassword will throw an exception rather
- // than return false in certain failure scenarios.
- bool changePasswordSucceeded;
- try
- {
- MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true);
- changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
- //Borramos la cache de los usuarios
- GlobalCachingProvider.Instance.RemoveItem("AllUsers");
- }
- catch (Exception)
- {
- changePasswordSucceeded = false;
- }
- if (changePasswordSucceeded)
- {
- return RedirectToAction("ChangePasswordSuccess");
- }
- else
- {
- ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
- }
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- //
- // GET: /Account/ChangePasswordSuccess
- public ActionResult ChangePasswordSuccess()
- {
- return View();
- }
- #region Helpers
- private ActionResult RedirectToLocal(string returnUrl)
- {
- if (Url.IsLocalUrl(returnUrl))
- {
- return Redirect(returnUrl);
- }
- else
- {
- return RedirectToAction("Login", "Account");
- }
- }
- public enum ManageMessageId
- {
- ChangePasswordSuccess,
- SetPasswordSuccess,
- RemoveLoginSuccess,
- }
- private static string ErrorCodeToString(MembershipCreateStatus createStatus)
- {
- // See http://go.microsoft.com/fwlink/?LinkID=177550 for
- // a full list of status codes.
- switch (createStatus)
- {
- case MembershipCreateStatus.DuplicateUserName:
- return "El nombre de usuario ya existe. Por favor, introduzca un nombre de usuario diferente.";
- case MembershipCreateStatus.DuplicateEmail:
- return "Ya existe el correo electrónico para un usuario. Por favor, introduzca otro correo electrónico.";
- case MembershipCreateStatus.InvalidPassword:
- return "La contraseña introducida no es válida. Por favor, introduzca una contraseña válida.";
- case MembershipCreateStatus.InvalidEmail:
- return "El correo electrónico introducido no es válido. Por favor, introduzca un correo electrónico válido.";
- case MembershipCreateStatus.InvalidAnswer:
- return "The password retrieval answer provided is invalid. Please check the value and try again.";
- case MembershipCreateStatus.InvalidQuestion:
- return "The password retrieval question provided is invalid. Please check the value and try again.";
- case MembershipCreateStatus.InvalidUserName:
- return "El nombre de usuario no es válido. Introduzca un nombre de usuario válido";
- case MembershipCreateStatus.ProviderError:
- return "El sistema de autenticación devolvió un error. Compruebe los datos e inténtelo de nuevo más tarde. Si el problema persiste, contacte con su administrador de sistemas.";
- case MembershipCreateStatus.UserRejected:
- return "La solicitud de creación del usuario ha sido cancelada. Compruebe los datos e inténtelo de nuevo más tarde. Si el problema persiste, contacte con su administrador de sistemas.";
- default:
- return "Se ha producido un error desconocido. Inténtelo de nuevo más tarde. Si el problema persiste, contacte con su administrador de sistemas.";
- }
- }
- #endregion
- #endregion
- public void SendViewBagFilter(FilterUsersVM filter)
- {
- ViewBag.nombre = filter.filterText;
- }
- public override bool AuthenticationRequired(string actionName, string controller)
- {
- return !"Login".Equals(actionName);
- }
- }
- // Cada Controlador tendrá una región y dentro de esa región
- // cada una de las acciones que contenga tendrá un método
- // de forma que determine qué usuarios tienen acceso
- public static class AuthorizationRules
- {
- #region Account
- public static bool AccountUpgradePasswOracle(AuthorizationModel authMdl) { return true; }
- public static bool AccountAllUsers(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
- public static bool AccountEdit(AuthorizationModel authMdl) { return true; }
- public static bool AccountEditUser(AuthorizationModel authMdl) { return AccountAllUsers(authMdl); }
- public static bool AccountRegister(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
- public static bool AccountResetPassword(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
- public static bool AccountResetPasswordSuccess(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
- #endregion
- #region Comun
- public static bool ComunIndex(AuthorizationModel authMdl) { return true; }
- #endregion
- #region Convocatoria
- public static bool ConvocatoriaImportarInformacion(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement