Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 35.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity.Validation;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Web;
  8. using System.Web.Mvc;
  9. using System.Web.Routing;
  10. using System.Web.Security;
  11. using ACCSOC.Models.Data;
  12. using ACCSOC.ViewModel;
  13.  
  14. using System.Web.Configuration;
  15. using PagedList;
  16. using ACCSOC.Utils;
  17. using UFV.ACCSOC.Utils;
  18. using System.Data.Entity;
  19.  
  20. namespace ACCSOC.Controllers
  21. {
  22.  
  23.  
  24. [Authorize]
  25. public class AccountController : BaseController
  26. {
  27.  
  28. //Clave para la cache de Usuarios
  29. private const string KEY_CACHE_USUARIOS = "AllUsers";
  30.  
  31. public static readonly int PageSize = 50;
  32.  
  33. #region Assign Users UFV
  34.  
  35. public ActionResult AllUsers(int? page, string filterText)
  36. {
  37. string key = KEY_CACHE_USUARIOS;
  38.  
  39. int pageIndex = page.HasValue ? page.Value : 1;
  40.  
  41. key = key + "_p" + pageIndex;
  42.  
  43. FilterUsersVM filtros = GetNewFilterUsersVM(filterText);
  44.  
  45. SendViewBagFilter(filtros);
  46.  
  47. //Si hay filtro del nombre de usuarios
  48. if (!String.IsNullOrEmpty(filterText) || !String.IsNullOrWhiteSpace(filterText))
  49. {
  50. key = key + "_UsuarioBuscado_" + filterText;
  51. }
  52.  
  53. AllUsersModel model = new AllUsersModel();
  54.  
  55. var users = Membership.GetAllUsers();
  56.  
  57. //Cache para los usuarios
  58. IEnumerable<UserModel> usuarios = GlobalCachingProvider.Instance.GetItem(key, false) as IEnumerable<UserModel>;
  59.  
  60. //Si no hay usuarios en cache los obtenemos y los guardamos en cache
  61. if (usuarios == null)
  62. {
  63. usuarios = from user in users.OfType<MembershipUser>()
  64. orderby GetUserUfvCompleto((Guid)user.ProviderUserKey)
  65. select new UserModel()
  66. {
  67. UserKey = (Guid)user.ProviderUserKey,
  68. UserName = user.UserName,
  69. Email = user.Email,
  70. IsApproved = user.IsApproved,
  71. IsInternalUser = GetUserUfv((Guid)user.ProviderUserKey).IsInternalUser,
  72. Roles = ConcatWithComma(Roles.GetRolesForUser(user.UserName)),
  73. Name = GetUserUfvCompleto((Guid)user.ProviderUserKey)
  74. };
  75.  
  76. //Si hemos filtrado por nombre del usuario
  77. if (!string.IsNullOrEmpty(filtros.filterText))
  78. {
  79. usuarios = usuarios.Where(user => UserNameCompare(GetUserUfvCompleto(user.UserKey), filtros.filterText)).OrderBy(user => user.UserName);
  80. }
  81.  
  82.  
  83. //Añadimos los datos en la cache
  84. GlobalCachingProvider.Instance.AddItem(key, usuarios, 86400);
  85. }
  86.  
  87. int? numUsuarios = usuarios.Count();
  88.  
  89. usuarios = usuarios
  90. .Skip((pageIndex - 1) * Constantes.PAGE_SIZE)
  91. .Take(Constantes.PAGE_SIZE)
  92. .ToList();
  93.  
  94. model.usuariosList = usuarios.ToList();
  95. model.Users = new StaticPagedList<UserModel>(model.usuariosList, pageIndex, Constantes.PAGE_SIZE, numUsuarios.GetValueOrDefault());
  96. model.Filtros = filtros;
  97.  
  98. return View(model);
  99. }
  100. #endregion
  101.  
  102. #region Manage Users UFV
  103.  
  104. protected bool UserNameCompare(string UserUfvCompleto, string filterText)
  105. {
  106.  
  107. UserUfvCompleto = FormatUserReplace(UserUfvCompleto).ToLower();
  108. filterText = FormatUserReplace(filterText).ToLower();
  109.  
  110. if (UserUfvCompleto.Contains(filterText))
  111. return true;
  112.  
  113. return false;
  114. }
  115.  
  116. protected string FormatUserReplace(string text)
  117. {
  118.  
  119. string textFormat;
  120. textFormat = text.Replace("Á", "A");
  121. textFormat = textFormat.Replace("á", "a");
  122. textFormat = textFormat.Replace("É", "E");
  123. textFormat = textFormat.Replace("é", "e");
  124. textFormat = textFormat.Replace("Í", "I");
  125. textFormat = textFormat.Replace("í", "i");
  126. textFormat = textFormat.Replace("Ó", "O");
  127. textFormat = textFormat.Replace("ó", "o");
  128. textFormat = textFormat.Replace("Ú", "U");
  129. textFormat = textFormat.Replace("ú", "u");
  130.  
  131. return textFormat;
  132. }
  133.  
  134. protected string ConcatWithComma(string[] roles)
  135. {
  136. if (roles == null || roles.Length == 0)
  137. return string.Empty;
  138. StringBuilder builder = new StringBuilder(roles[0]);
  139.  
  140. for (int i = 1; i < roles.Length; i++)
  141. builder.AppendFormat(", {0} ", roles[i]);
  142.  
  143. return builder.ToString();
  144. }
  145.  
  146. private IEnumerable<RolePerUser> GetRolesPerUser(string userName)
  147. {
  148. string[] allRoles = Roles.GetAllRoles();
  149. string[] userRoles = Roles.GetRolesForUser(userName);
  150.  
  151. for (int i = 0; i < allRoles.Length; i++)
  152. yield return new RolePerUser()
  153. {
  154. Role = allRoles[i],
  155. IsIn = userRoles.Contains(allRoles[i])
  156. };
  157. }
  158. private IEnumerable<RolePerUser> GetRoles()
  159. {
  160. string[] allRoles = Roles.GetAllRoles();
  161. for (int i = 0; i < allRoles.Length; i++)
  162. yield return new RolePerUser()
  163. {
  164. Role = allRoles[i],
  165. IsIn = false
  166. };
  167. }
  168. public IEnumerable<Institucion> GetInstituciones()
  169. {
  170. CursoAcad cursoVigente = db.CursoAcad.First(t => t.cursoSeg == 1);
  171.  
  172. IEnumerable<Institucion> instituciones = GlobalCachingProvider.Instance.GetItem("AllInstituciones", false) as IEnumerable<Institucion>; ;
  173. instituciones = repoFactory.GetInstitucionEntity().GetAll().Where(t => t.desact == false && t.cursoAcad.id == cursoVigente.id).OrderBy(t => t.denominacion);
  174. return instituciones;
  175. }
  176.  
  177. public bool institucionSeleccionada(int? instSelect)
  178. {
  179. if (instSelect != null)
  180. {
  181. int listUsuarioInst = db.UsuarioInstitucion.Count(t => t.institucion.id == instSelect);
  182. if (listUsuarioInst != 0) return true;
  183.  
  184. return false;
  185. }
  186. return false;
  187. }
  188.  
  189. public bool isInInstictucion(bool isIn, int? instSelect)
  190. {
  191. if (isIn == true && instSelect == null) return true;
  192.  
  193. return false;
  194. }
  195.  
  196. public void crearUsuarioInstitucion(UserUfv usuario, int? instSelect)
  197. {
  198. UsuarioInstitucion usuarioInstitucion = new UsuarioInstitucion();
  199. usuarioInstitucion.user = usuario;
  200. usuarioInstitucion.institucion = db.Institucion.Find(instSelect);
  201. try
  202. {
  203. db.UsuarioInstitucion.Add(usuarioInstitucion);
  204. db.SaveChanges();
  205. }
  206. catch (Exception ex)
  207. {
  208. Console.WriteLine(ex.Message);
  209. }
  210. }
  211.  
  212. public ActionResult Edit(string userName)
  213. {
  214.  
  215. MembershipUser user = Membership.GetUser(userName);
  216.  
  217.  
  218. if (Membership.GetUser().ProviderUserKey.Equals(user.ProviderUserKey))
  219. {
  220. UserUfv userUfv = GetUserUfv((Guid)user.ProviderUserKey);
  221.  
  222. string roles = string.Empty;
  223. bool first = true;
  224. foreach (string rol in GetRolesPerUser(user.UserName).Where(rol => rol.IsIn).Select(rol => rol.Role))
  225. {
  226. if (!first) roles += ", ";
  227. roles += rol;
  228. first = false;
  229. }
  230.  
  231. return View(new EditUserDataModel()
  232. {
  233. UserKey = (Guid)user.ProviderUserKey,
  234. UserName = user.UserName,
  235. Email = user.Email,
  236. Roles = roles,
  237. nombre = userUfv.nombre,
  238. apellido1 = userUfv.apellido1,
  239. apellido2 = userUfv.apellido2,
  240. despacho = userUfv.despacho,
  241. IsInternalUser = userUfv.IsInternalUser,
  242. IsProfSincronizado = userUfv.IsProfSincronizado
  243. });
  244. }
  245. else
  246. {
  247. return RedirectToAction("Index", "Asignacion");
  248. }
  249. }
  250.  
  251. [HttpPost]
  252. public ActionResult Edit(EditUserDataModel user)
  253. {
  254.  
  255. string errorEmail = string.Empty;
  256. try
  257. {
  258. if (ModelState.IsValid)
  259. {
  260. //Borramos la cache de los uaurios
  261. GlobalCachingProvider.Instance.RemoveItem("AllUsers");
  262. //Comprobar que el email sea único
  263. if (string.IsNullOrEmpty(Membership.GetUserNameByEmail(user.Email)) || user.UserName.ToLower().Equals((Membership.GetUserNameByEmail(user.Email)).ToLower()))
  264. {
  265.  
  266. MembershipUser membershipUser = Membership.GetUser(user.UserKey);
  267. membershipUser.Email = user.Email;
  268. Membership.UpdateUser(membershipUser);
  269.  
  270. UpdateUsuarioUfv(user.UserKey, user.nombre, user.apellido1, user.apellido2, user.despacho);
  271.  
  272. if (CheckPermisosPorRoll(user.UserName))
  273. {
  274. return RedirectToAction("Index", "Asignacion");
  275. }
  276. return RedirectToAction("Index", "Asignacion");
  277.  
  278. }
  279. else
  280. {
  281. ViewBag.ErrorEmail = "El email introducido ya existe. Por favor, introduzca otro.";
  282. }
  283. }
  284. }
  285. catch { }
  286.  
  287. return View(user);
  288. }
  289.  
  290. public ActionResult EditUser(Guid userKey)
  291. {
  292. MembershipUser user = Membership.GetUser(userKey);
  293.  
  294. UserUfv userUfv = GetUserUfv((Guid)user.ProviderUserKey);
  295. return View(new EditUserModel()
  296. {
  297. UserKey = (Guid)user.ProviderUserKey,
  298. UserName = user.UserName,
  299. Email = user.Email,
  300. IsApproved = user.IsApproved,
  301. Roles = GetRolesPerUser(user.UserName),
  302. nombre = userUfv.nombre,
  303. apellido1 = userUfv.apellido1,
  304. apellido2 = userUfv.apellido2,
  305. despacho = userUfv.despacho,
  306. IsInternalUser = userUfv.IsInternalUser,
  307. IsProfSincronizado = userUfv.IsProfSincronizado,
  308. listInstitucion = GetInstituciones()
  309. });
  310. }
  311.  
  312. [HttpPost]
  313. public ActionResult EditUser(EditUserModel user)
  314. {
  315. try
  316. {
  317. if (ModelState.IsValid)
  318. {
  319.  
  320. if(isInInstictucion(user.Roles.Skip(2).First().IsIn, user.instSelectInstitucion))
  321. {
  322. ModelState.AddModelError("instSelectInstitucion", "* Introduzca institución");
  323. user.listInstitucion = GetInstituciones();
  324. return View(user);
  325. }
  326.  
  327. if (institucionSeleccionada(user.instSelectInstitucion) == true)
  328. {
  329. ModelState.AddModelError("ErrorInstitucion", "La institución ya pertenece a un usuario");
  330. user.listInstitucion = GetInstituciones();
  331. return View(user);
  332. }
  333.  
  334. if (string.IsNullOrEmpty(Membership.GetUserNameByEmail(user.Email)) || user.UserName.ToLower().Equals((Membership.GetUserNameByEmail(user.Email)).ToLower()))
  335. {
  336.  
  337. MembershipUser membershipUser = Membership.GetUser(user.UserKey);
  338.  
  339. membershipUser.Email = user.Email;
  340. membershipUser.IsApproved = user.IsApproved;
  341.  
  342. Membership.UpdateUser(membershipUser);
  343.  
  344. bool wasIn;
  345. foreach (RolePerUser role in user.Roles)
  346. {
  347. wasIn = Roles.IsUserInRole(user.UserName, role.Role);
  348. if (role.IsIn != wasIn)
  349. {
  350. if (wasIn) Roles.RemoveUserFromRole(user.UserName, role.Role);
  351. else Roles.AddUserToRole(user.UserName, role.Role);
  352. }
  353. }
  354.  
  355. UserUfv userUfv = GetUserUfv((Guid)membershipUser.ProviderUserKey);
  356.  
  357. IEnumerable<UsuarioInstitucion> usuarioInstitucion = db.UsuarioInstitucion.Where(t => t.user.id == userUfv.id);
  358.  
  359. if (user.Roles.Skip(2).First().IsIn)
  360. {
  361. if (usuarioInstitucion.Count() == 0)
  362. {
  363. crearUsuarioInstitucion(userUfv, user.instSelectInstitucion);
  364. }
  365. else
  366. {
  367. usuarioInstitucion.Skip(0).First().user = userUfv;
  368. usuarioInstitucion.Skip(0).First().institucion = db.Institucion.Find(user.instSelectInstitucion);
  369.  
  370. try
  371. {
  372. db.UsuarioInstitucion.Attach(usuarioInstitucion.Skip(0).First());
  373. db.Entry(usuarioInstitucion.Skip(0).First()).State = EntityState.Modified;
  374.  
  375. db.SaveChanges();
  376. }
  377. catch (Exception ex)
  378. {
  379. Console.WriteLine(ex.Message);
  380. }
  381. }
  382. }
  383. else
  384. {
  385. if(usuarioInstitucion.Count() != 0)
  386. {
  387. try
  388. {
  389. db.UsuarioInstitucion.Attach(usuarioInstitucion.Skip(0).First());
  390. db.UsuarioInstitucion.Remove(usuarioInstitucion.Skip(0).First());
  391. db.SaveChanges();
  392. }
  393. catch (Exception ex)
  394. {
  395. Console.WriteLine(ex.Message);
  396. }
  397.  
  398. }
  399. }
  400. }
  401. else
  402. {
  403. ViewBag.ErrorEmail = "El email introducido ya existe. Por favor, introduzca otro.";
  404. user.listInstitucion = GetInstituciones();
  405. return View(user);
  406. }
  407. }
  408. else
  409. {
  410. user.listInstitucion = GetInstituciones();
  411. return View(user);
  412. }
  413. }
  414. catch
  415. {
  416. user.listInstitucion = GetInstituciones();
  417. return View(user);
  418. }
  419. //Borramos la cache de los usuarios
  420. GlobalCachingProvider.Instance.RemoveItem("AllUsers");
  421. return RedirectToAction("AllUsers");
  422. }
  423.  
  424. public ActionResult ResetPassword(Guid userKey)
  425. {
  426. MembershipUser membershipUser = Membership.GetUser(userKey);
  427.  
  428. if (membershipUser.IsLockedOut)
  429. membershipUser.UnlockUser();
  430.  
  431. string newPassword = membershipUser.ResetPassword();
  432.  
  433. //Borramos la cache de los usuarios
  434. GlobalCachingProvider.Instance.RemoveItem("AllUsers");
  435.  
  436. Membership.UpdateUser(membershipUser);
  437.  
  438. return RedirectToAction("ResetPasswordSuccess", new ResetPasswordModel()
  439. {
  440. Email = membershipUser.Email,
  441. UserName = membershipUser.UserName,
  442. Password = newPassword,
  443. });
  444. }
  445.  
  446. public ActionResult ResetPasswordSuccess(ResetPasswordModel model)
  447. {
  448. return View(model);
  449. }
  450. #endregion
  451.  
  452. #region Autenticación
  453.  
  454. protected string GenerateStandarPassword(string userName)
  455. {
  456.  
  457. string pass;
  458.  
  459. using (MD5 md5Has = MD5.Create()) { pass = GetMd5Hash(md5Has, userName); }
  460.  
  461. return pass;
  462. }
  463.  
  464. protected string GetUserByP1(string userP)
  465. {
  466.  
  467. string user = string.Empty;
  468.  
  469. foreach (char letra in userP) { user += TraducirLetra(letra); }
  470.  
  471. return user;
  472. }
  473.  
  474. protected char TraducirLetra(char letra)
  475. {
  476.  
  477. string recibido = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  478. string resultad = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  479.  
  480. return resultad.ElementAt(recibido.IndexOf(letra));
  481. }
  482.  
  483. protected bool VerifyMd5Hash(string user, string hashP2)
  484. {
  485.  
  486. string clave = "qR2a7pmC";
  487. string internalString = user + clave + DateTime.Now.ToString("ddMMyyyy");
  488.  
  489. using (MD5 md5Hash = MD5.Create())
  490. {
  491.  
  492. string hashInternal = GetMd5Hash(md5Hash, internalString);
  493.  
  494. // Create a StringComparer an compare the hashes.
  495. StringComparer comparer = StringComparer.OrdinalIgnoreCase;
  496.  
  497. if (0 == comparer.Compare(hashInternal, hashP2))
  498. {
  499. return true;
  500. }
  501. else
  502. {
  503. return false;
  504. }
  505. }
  506. }
  507. protected string GetMd5Hash(MD5 md5Hash, string internalString)
  508. {
  509.  
  510. // Convert the input string to a byte array and compute the hash.
  511. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(internalString));
  512.  
  513. // Create a new Stringbuilder to collect the bytes
  514. // and create a string.
  515. StringBuilder sBuilder = new StringBuilder();
  516.  
  517. // Loop through each byte of the hashed data
  518. // and format each one as a hexadecimal string.
  519. for (int i = 0; i < data.Length; i++)
  520. {
  521. sBuilder.Append(data[i].ToString("x2"));
  522. }
  523.  
  524. // Return the hexadecimal string.
  525. return sBuilder.ToString();
  526. }
  527.  
  528. // GET: /Account/Login
  529. [AllowAnonymous]
  530. public ActionResult Login()
  531. {
  532. return View();
  533. }
  534.  
  535. public void UpgradePasswOracle()
  536. {
  537.  
  538. bool changePasswordSucceeded = false;
  539. bool isLocked = false;
  540. UserUfv userUFV;
  541.  
  542. foreach (MembershipUser actualUser in Membership.GetAllUsers())
  543. {
  544.  
  545. try
  546. {
  547. isLocked = actualUser.IsLockedOut;
  548.  
  549. if (isLocked)
  550. actualUser.UnlockUser();
  551.  
  552. userUFV = GetUserUfv((Guid)actualUser.ProviderUserKey);
  553.  
  554. if (userUFV.IsInternalUser)
  555. {
  556. if (actualUser.UserName.Equals("dvega"))
  557. {
  558. changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "Trip01multi");
  559. }
  560. else if (actualUser.UserName.Equals("ufv"))
  561. {
  562. changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "plataformaufv");
  563. }
  564. else if (actualUser.UserName.Equals("idiomas"))
  565. {
  566. changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "idiomas");
  567. }
  568. else if (actualUser.UserName.Equals("desarrollo"))
  569. {
  570. changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "desarrollo01");
  571. }
  572. else if (actualUser.UserName.Equals("rrii"))
  573. {
  574. changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), "gdPolanco01");
  575. }
  576. }
  577. else
  578. {
  579. changePasswordSucceeded = actualUser.ChangePassword(actualUser.ResetPassword(), GenerateStandarPassword(actualUser.UserName));
  580. }
  581. }
  582. catch (Exception) { }
  583. }
  584. } //Actualizar las contraseñas del Membership con el Provider Actual
  585.  
  586. // POST: /Account/Login
  587. [HttpPost]
  588. [AllowAnonymous]
  589. [ValidateAntiForgeryToken]
  590. public ActionResult Login(LoginModel model, string returnUrl)
  591. {
  592. if (ModelState.IsValid)
  593. {
  594. if (Membership.ValidateUser(model.UserName, model.Password))
  595. {
  596. SetAuthCookie(Membership.GetUser(model.UserName), model.RememberMe);
  597. if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
  598. && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
  599. {
  600. return Redirect(returnUrl);
  601. }
  602. else
  603. {
  604. if (CheckPermisosPorRoll(model.UserName))
  605. {
  606. return RedirectToAction("AllUsers", "Account");
  607. }
  608. if (Roles.IsUserInRole(model.UserName, "Mentor") || Roles.IsUserInRole(model.UserName, "Profesor"))
  609. {
  610. return RedirectToAction("Index", "Seguimiento");
  611. }
  612. if (Roles.IsUserInRole(model.UserName, "Institucion"))
  613. {
  614. MembershipUser user = Membership.GetUser(model.UserName);
  615.  
  616. UserUfv userufv = GetUserUfv((Guid)user.ProviderUserKey);
  617.  
  618. IEnumerable<UsuarioInstitucion> usuarioInstitucions = db.UsuarioInstitucion.Where(p => p.user.id == userufv.id);
  619.  
  620. return RedirectToAction("Index", "Programa", new { id = usuarioInstitucions.Skip(0).First().institucion.id });
  621. }
  622. else
  623. {
  624. return RedirectToAction("Index", "Asignacion");
  625. }
  626.  
  627. }
  628. }
  629. }
  630.  
  631. // If we got this far, something failed, redisplay form
  632. ModelState.AddModelError("", "El usuario o la contraseña introducidos son incorrectos.");
  633. return View(model);
  634. }
  635.  
  636. protected bool CheckPermisosPorRoll(string userName)
  637. {
  638.  
  639. string[] roles = Roles.GetRolesForUser(userName);
  640.  
  641. // Aquí van todos los roles que se quieren determinar como agrupados
  642. if (roles.Contains(AppRoles.Administrador.ToString()))
  643. return true;
  644.  
  645. return false;
  646. }
  647.  
  648. protected virtual void SetAuthCookie(MembershipUser user, bool rememberMe)
  649. {
  650. string fullUserName = this.GetUserUfvCompleto((Guid)user.ProviderUserKey);
  651.  
  652. /// In order to pickup the settings from config, we create a default cookie and use its values to create a new one.
  653. HttpCookie cookie = FormsAuthentication.GetAuthCookie(user.UserName, rememberMe);
  654. FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
  655.  
  656. FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, fullUserName, ticket.CookiePath);
  657. string encTicket = FormsAuthentication.Encrypt(newTicket);
  658.  
  659. /// Use existing cookie. Could create new one but would have to copy settings over...
  660. cookie.Value = encTicket;
  661.  
  662. this.Response.Cookies.Add(cookie);
  663. }
  664.  
  665. // POST: /Account/LogOff
  666. [HttpPost]
  667. [ValidateAntiForgeryToken]
  668. public ActionResult LogOff()
  669. {
  670. FormsAuthentication.SignOut();
  671.  
  672. return RedirectToAction("Login", "Account");
  673. }
  674.  
  675. // GET: /Account/Register
  676. [AllowAnonymous]
  677. public ActionResult Register()
  678. {
  679. return View(new RegisterModel()
  680. {
  681. listInstitucion = GetInstituciones(),
  682. Roles = GetRoles()
  683. });
  684. }
  685.  
  686. // POST: /Account/Register
  687. [HttpPost]
  688. [AllowAnonymous]
  689. [ValidateAntiForgeryToken]
  690. public ActionResult Register(RegisterModel model)
  691. {
  692. if (ModelState.IsValid)
  693. {
  694.  
  695. if (isInInstictucion(model.Roles.Skip(2).First().IsIn, model.instSelectInstitucion))
  696. {
  697. ModelState.AddModelError("instSelectInstitucion", "* Introduzca institución");
  698. model.listInstitucion = GetInstituciones();
  699. return View(model);
  700. }
  701.  
  702. if (institucionSeleccionada(model.instSelectInstitucion) == true)
  703. {
  704. ModelState.AddModelError("ErrorInstitucion", "La institución ya pertenece a un usuario");
  705. model.listInstitucion = GetInstituciones();
  706. return View(model);
  707. }
  708.  
  709. // Attempt to register the user
  710. MembershipCreateStatus createStatus;
  711.  
  712. //Comprobar email
  713. string emailRegistrado = Membership.GetUserNameByEmail(model.Email);
  714.  
  715. //Si ese email pertenece a algun usuario, devuelvo un error
  716. if (String.IsNullOrEmpty(emailRegistrado))
  717. {
  718. Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
  719. }
  720. else
  721. {
  722. createStatus = MembershipCreateStatus.DuplicateEmail;
  723. }
  724.  
  725.  
  726. if (createStatus == MembershipCreateStatus.Success)
  727. {
  728. //Creamos un objeto Usuario
  729. UserUfv usuario = new UserUfv();
  730. //Agregamos los campos que va a tener
  731. usuario.nombre = model.nombre;
  732. usuario.apellido1 = model.apellido1;
  733. usuario.apellido2 = model.apellido2;
  734. usuario.id = (Guid)Membership.GetUser(model.UserName).ProviderUserKey;
  735. usuario.IsInternalUser = true;
  736.  
  737. //Tratamos de agregarlo a la base de datos
  738. try
  739. {
  740.  
  741. db.UserUfv.Add(usuario);
  742. db.SaveChanges();
  743. }
  744. catch (Exception ex)
  745. {
  746. Console.WriteLine(ex.Message);
  747. }
  748.  
  749. bool wasIn;
  750. foreach (RolePerUser role in model.Roles)
  751. {
  752. wasIn = Roles.IsUserInRole(model.UserName, role.Role);
  753. if (role.IsIn != wasIn)
  754. {
  755. if (wasIn) Roles.RemoveUserFromRole(model.UserName, role.Role);
  756. else Roles.AddUserToRole(model.UserName, role.Role);
  757. }
  758. }
  759.  
  760. if (model.Roles.Skip(2).First().IsIn)
  761. {
  762. crearUsuarioInstitucion(usuario, model.instSelectInstitucion);
  763.  
  764. }
  765.  
  766. //Borramos la cache de los usuarios
  767. GlobalCachingProvider.Instance.RemoveItem("AllUsers");
  768. return RedirectToAction("AllUsers", "Account");
  769. }
  770. else
  771. {
  772. ModelState.AddModelError("ErrorRegistro", ErrorCodeToString(createStatus));
  773. }
  774. }
  775.  
  776. model.listInstitucion = GetInstituciones();
  777. // If we got this far, something failed, redisplay form
  778. return View(model);
  779. }
  780.  
  781. // GET: /Account/ChangePassword
  782. [Authorize]
  783. public ActionResult ChangePassword()
  784. {
  785. return View();
  786. }
  787.  
  788. //
  789. // POST: /Account/ChangePassword
  790. [Authorize]
  791. [HttpPost]
  792. public ActionResult ChangePassword(LocalPasswordModel model)
  793. {
  794. if (ModelState.IsValid)
  795. {
  796.  
  797. // ChangePassword will throw an exception rather
  798. // than return false in certain failure scenarios.
  799. bool changePasswordSucceeded;
  800. try
  801. {
  802. MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true);
  803. changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
  804. //Borramos la cache de los usuarios
  805. GlobalCachingProvider.Instance.RemoveItem("AllUsers");
  806. }
  807. catch (Exception)
  808. {
  809. changePasswordSucceeded = false;
  810. }
  811.  
  812. if (changePasswordSucceeded)
  813. {
  814. return RedirectToAction("ChangePasswordSuccess");
  815. }
  816. else
  817. {
  818. ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
  819. }
  820. }
  821.  
  822. // If we got this far, something failed, redisplay form
  823. return View(model);
  824. }
  825.  
  826. //
  827. // GET: /Account/ChangePasswordSuccess
  828. public ActionResult ChangePasswordSuccess()
  829. {
  830. return View();
  831. }
  832.  
  833. #region Helpers
  834.  
  835. private ActionResult RedirectToLocal(string returnUrl)
  836. {
  837. if (Url.IsLocalUrl(returnUrl))
  838. {
  839. return Redirect(returnUrl);
  840. }
  841. else
  842. {
  843. return RedirectToAction("Login", "Account");
  844. }
  845. }
  846.  
  847. public enum ManageMessageId
  848. {
  849. ChangePasswordSuccess,
  850. SetPasswordSuccess,
  851. RemoveLoginSuccess,
  852. }
  853.  
  854. private static string ErrorCodeToString(MembershipCreateStatus createStatus)
  855. {
  856. // See http://go.microsoft.com/fwlink/?LinkID=177550 for
  857. // a full list of status codes.
  858. switch (createStatus)
  859. {
  860. case MembershipCreateStatus.DuplicateUserName:
  861. return "El nombre de usuario ya existe. Por favor, introduzca un nombre de usuario diferente.";
  862.  
  863. case MembershipCreateStatus.DuplicateEmail:
  864. return "Ya existe el correo electrónico para un usuario. Por favor, introduzca otro correo electrónico.";
  865.  
  866. case MembershipCreateStatus.InvalidPassword:
  867. return "La contraseña introducida no es válida. Por favor, introduzca una contraseña válida.";
  868.  
  869. case MembershipCreateStatus.InvalidEmail:
  870. return "El correo electrónico introducido no es válido. Por favor, introduzca un correo electrónico válido.";
  871.  
  872. case MembershipCreateStatus.InvalidAnswer:
  873. return "The password retrieval answer provided is invalid. Please check the value and try again.";
  874.  
  875. case MembershipCreateStatus.InvalidQuestion:
  876. return "The password retrieval question provided is invalid. Please check the value and try again.";
  877.  
  878. case MembershipCreateStatus.InvalidUserName:
  879. return "El nombre de usuario no es válido. Introduzca un nombre de usuario válido";
  880.  
  881. case MembershipCreateStatus.ProviderError:
  882. 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.";
  883.  
  884. case MembershipCreateStatus.UserRejected:
  885. 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.";
  886.  
  887. default:
  888. return "Se ha producido un error desconocido. Inténtelo de nuevo más tarde. Si el problema persiste, contacte con su administrador de sistemas.";
  889. }
  890. }
  891. #endregion
  892.  
  893. #endregion
  894.  
  895. public void SendViewBagFilter(FilterUsersVM filter)
  896. {
  897. ViewBag.nombre = filter.filterText;
  898. }
  899.  
  900. public override bool AuthenticationRequired(string actionName, string controller)
  901. {
  902. return !"Login".Equals(actionName);
  903. }
  904.  
  905. }
  906.  
  907. // Cada Controlador tendrá una región y dentro de esa región
  908. // cada una de las acciones que contenga tendrá un método
  909. // de forma que determine qué usuarios tienen acceso
  910. public static class AuthorizationRules
  911. {
  912. #region Account
  913.  
  914. public static bool AccountUpgradePasswOracle(AuthorizationModel authMdl) { return true; }
  915. public static bool AccountAllUsers(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
  916.  
  917. public static bool AccountEdit(AuthorizationModel authMdl) { return true; }
  918. public static bool AccountEditUser(AuthorizationModel authMdl) { return AccountAllUsers(authMdl); }
  919.  
  920. public static bool AccountRegister(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
  921. public static bool AccountResetPassword(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
  922. public static bool AccountResetPasswordSuccess(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
  923.  
  924. #endregion
  925.  
  926. #region Comun
  927.  
  928. public static bool ComunIndex(AuthorizationModel authMdl) { return true; }
  929.  
  930. #endregion
  931.  
  932. #region Convocatoria
  933.  
  934. public static bool ConvocatoriaImportarInformacion(AuthorizationModel authMdl) { return authMdl.EsAdministrador; }
  935.  
  936. #endregion
  937.  
  938. }
  939. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement