Advertisement
Guest User

Untitled

a guest
Jun 29th, 2016
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.20 KB | None | 0 0
  1. namespace MeuProjeto.Controllers
  2. {
  3. public class LoginController : Controller
  4. {
  5. private MeuProjetoContext _db = new MeuProjetoContext();
  6. //
  7. // GET: /Login/
  8.  
  9. public ActionResult Index()
  10. {
  11. return View();
  12. }
  13.  
  14. [HttpPost]
  15. public ActionResult Index(UserLogin userLogin)
  16. {
  17. if (ModelState.IsValid && WebSecurity.Login(userLogin.Username, userLogin.Password, persistCookie: true))
  18. {
  19. return RedirectToAction("Index", "Home", new { area = "" });
  20. }
  21.  
  22. // Se chegou aqui, re-exibir form. Modelo inválido.
  23. ModelState.AddModelError("", "Usuário ou senha incorretos.");
  24. return View(userLogin);
  25. }
  26.  
  27. public ActionResult RecuperarSenha()
  28. {
  29. ViewBag.ErrorMessage = "";
  30. return View();
  31. }
  32.  
  33. [HttpPost]
  34. public ActionResult RecuperarSenha(string email)
  35. {
  36. string errorMsg = string.Empty;
  37.  
  38. if (!string.IsNullOrEmpty(email))
  39. {
  40. List<Usuario> users = _db.Usuarios.Where(usr => usr.Email == email).ToList();
  41.  
  42. if (users.Count == 0)
  43. {
  44. errorMsg = "E-Mail não encontrado";
  45. }
  46. else
  47. {
  48. Usuario user = users[0];
  49.  
  50. string url = string.Format("{0}/{1}/{2}", Request.Url.GetLeftPart(UriPartial.Authority), "Login/ResetPassword", user.UsuarioId);
  51.  
  52. string bodyMail = "Olá " + user.Nome + @"rn";
  53. bodyMail += "Para redefinir a sua senha clique <a href="" + url + "">aqui</a><br>";
  54.  
  55. EmailMessage msg = new EmailMessage();
  56. msg.To = user.Email;
  57. msg.Subject = "Redefinir senha";
  58. msg.Body = bodyMail;
  59. msg.Send();
  60. errorMsg = "E-Mail enviado com sucesso";
  61. }
  62. }
  63. else
  64. {
  65. errorMsg = "E-Mail não pode estar em branco";
  66. }
  67.  
  68. ViewBag.ErrorMessage = errorMsg;
  69. return View();
  70. }
  71.  
  72. public ActionResult Logout()
  73. {
  74. WebSecurity.Logout();
  75. return RedirectToAction("Index", "Login", new { area = "" });
  76. }
  77.  
  78. protected override void Dispose(bool disposing)
  79. {
  80. _db.Dispose();
  81. base.Dispose(disposing);
  82. }
  83. }
  84. }
  85.  
  86. <system.web>
  87. <roleManager enabled="true" defaultProvider="CustomRoleProvider">
  88. <providers>
  89. <clear />
  90. <add name="CustomRoleProvider" type="MeuProjeto.Site.Infrastructure.CustomRoleProvider" connectionStringName="DefaultConnection" applicationName="/" />
  91. </providers>
  92. </roleManager>
  93. <membership defaultProvider="CustomMembershipProvider">
  94. <providers>
  95. <clear />
  96. <add name="CustomMembershipProvider" type="MeuProjeto.Site.Infrastructure.CustomMembershipProvider" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
  97. </providers>
  98. </membership>
  99. <sessionState mode="InProc" customProvider="DefaultSessionProvider">
  100. <providers>
  101. <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
  102. </providers>
  103. </sessionState>
  104. <customErrors mode="Off" />
  105. </system.web>
  106.  
  107. using MeuProjeto.Core.Models;
  108. using System;
  109. using System.Collections.Generic;
  110. using System.Linq;
  111. using System.Security.Cryptography;
  112. using System.Web;
  113. using System.Web.Configuration;
  114. using System.Web.Security;
  115. using WebMatrix.WebData;
  116.  
  117. namespace MeuProjeto.Infrastructure
  118. {
  119. public class CustomMembershipProvider : ExtendedMembershipProvider
  120. {
  121. #region Class Variables
  122.  
  123. private int newPasswordLength = 8;
  124. private string connectionString;
  125. private string applicationName;
  126. private bool enablePasswordReset;
  127. private bool enablePasswordRetrieval;
  128. private bool requiresQuestionAndAnswer;
  129. private bool requiresUniqueEmail;
  130. private int maxInvalidPasswordAttempts;
  131. private int passwordAttemptWindow;
  132. private MembershipPasswordFormat passwordFormat;
  133. private int minRequiredNonAlphanumericCharacters;
  134. private int minRequiredPasswordLength;
  135. private string passwordStrengthRegularExpression;
  136. private MachineKeySection machineKey; //Used when determining encryption key values.
  137.  
  138. #endregion
  139.  
  140. static public byte[] RandomSalt
  141. {
  142. get
  143. {
  144. byte[] salt = new byte[48];
  145. using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
  146. rngCsp.GetBytes(salt);
  147. return salt;
  148. }
  149. }
  150.  
  151. private byte[] GeneratePasswordHash(byte[] salt, string password)
  152. {
  153. Byte[] bytes;
  154. using (SHA256 hasher = SHA256.Create())
  155. {
  156. System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  157. bytes = encoding.GetBytes(password);
  158.  
  159. hasher.TransformBlock(salt, 0, salt.Length, salt, 0);
  160. hasher.TransformFinalBlock(bytes, 0, bytes.Length);
  161.  
  162. bytes = hasher.Hash;
  163. }
  164.  
  165. return bytes;
  166. }
  167.  
  168. private String GeneratePassword(string newpassword)
  169. {
  170. byte[] salt = RandomSalt;
  171. byte[] passHash = GeneratePasswordHash(salt, newpassword);
  172.  
  173. // concatenates the salt and hash in one vector
  174. byte[] finalData = new byte[salt.Length + passHash.Length];
  175. Array.Copy(salt, finalData, salt.Length);
  176. Array.Copy(passHash, 0, finalData, salt.Length, passHash.Length);
  177.  
  178. return System.Convert.ToBase64String(finalData);
  179. }
  180.  
  181. private bool ByteArraysEqual(byte[] b1, byte[] b2)
  182. {
  183. if (b1 == b2) return true;
  184. if (b1 == null || b2 == null) return false;
  185. if (b1.Length != b2.Length) return false;
  186. for (int i = 0; i < b1.Length; i++)
  187. {
  188. if (b1[i] != b2[i]) return false;
  189. }
  190. return true;
  191. }
  192.  
  193. public override bool ConfirmAccount(string accountConfirmationToken)
  194. {
  195. throw new NotImplementedException();
  196. }
  197.  
  198. public override bool ConfirmAccount(string userName, string accountConfirmationToken)
  199. {
  200. throw new NotImplementedException();
  201. }
  202.  
  203. public override string CreateAccount(string userName, string password, bool requireConfirmationToken)
  204. {
  205. throw new NotImplementedException();
  206. }
  207.  
  208. public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary<string, object> values)
  209. {
  210. ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(userName, password, true);
  211.  
  212. OnValidatingPassword(args);
  213.  
  214. if (args.Cancel)
  215. {
  216. // return MembershipCreateStatus.InvalidPassword;
  217. throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword);
  218. }
  219.  
  220. var CustomMembershipUser = GetUser(userName);
  221.  
  222. if (CustomMembershipUser == null)
  223. {
  224. // try
  225. // {
  226. using (var context = new MeuProjetoContext())
  227. {
  228. var hashedPassword = GeneratePassword(password);
  229.  
  230. var user = new Usuario {
  231. UsuarioId = Guid.NewGuid(),
  232. Email = userName,
  233. Nome = values["Name"].ToString(),
  234. Senha = hashedPassword,
  235. Ativo = true
  236. };
  237.  
  238. context.Usuarios.Add(user);
  239. context.SaveChanges();
  240.  
  241. var membership = new MeuProjeto.Core.Models.Membership();
  242.  
  243. membership.MembershipId = Guid.NewGuid();
  244. membership.Usuario = user;
  245. membership.Password = hashedPassword;
  246. context.Memberships.Add(membership);
  247. context.SaveChanges();
  248.  
  249. return MembershipCreateStatus.Success.ToString();
  250. }
  251. }
  252. else
  253. {
  254. // return MembershipCreateStatus.DuplicateUserName;
  255. throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName);
  256. }
  257. }
  258.  
  259. public override MembershipUser GetUser(string username, bool userIsOnline = true)
  260. {
  261. CustomMembershipUser CustomMembershipUser = null;
  262. using (var context = new MeuProjetoContext())
  263. {
  264. try
  265. {
  266. var user = context.Usuarios.Where(u => u.Email == username).SingleOrDefault();
  267.  
  268. if (user != null)
  269. {
  270. CustomMembershipUser = new CustomMembershipUser(
  271. this.Name,
  272. user.Email,
  273. user.UsuarioId,
  274. user.Email,
  275. "",
  276. "",
  277. true,
  278. false,
  279. user.CreatedOn,
  280. DateTime.Now,
  281. DateTime.Now,
  282. default(DateTime),
  283. default(DateTime),
  284. user.Email);
  285. }
  286. }
  287. catch { }
  288. }
  289.  
  290. return CustomMembershipUser;
  291. }
  292.  
  293. public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
  294. {
  295. throw new NotImplementedException();
  296. }
  297.  
  298. public override string GetUserNameByEmail(string email)
  299. {
  300. throw new NotImplementedException();
  301. }
  302.  
  303. public override int MaxInvalidPasswordAttempts
  304. {
  305. get { throw new NotImplementedException(); }
  306. }
  307.  
  308. public override int MinRequiredNonAlphanumericCharacters
  309. {
  310. get { throw new NotImplementedException(); }
  311. }
  312.  
  313. public override int MinRequiredPasswordLength
  314. {
  315. get { throw new NotImplementedException(); }
  316. }
  317.  
  318. public override int PasswordAttemptWindow
  319. {
  320. get { throw new NotImplementedException(); }
  321. }
  322.  
  323. public override System.Web.Security.MembershipPasswordFormat PasswordFormat
  324. {
  325. get { throw new NotImplementedException(); }
  326. }
  327.  
  328. public override string PasswordStrengthRegularExpression
  329. {
  330. get { throw new NotImplementedException(); }
  331. }
  332.  
  333. public override bool RequiresQuestionAndAnswer
  334. {
  335. get { throw new NotImplementedException(); }
  336. }
  337.  
  338. public override bool RequiresUniqueEmail
  339. {
  340. get { throw new NotImplementedException(); }
  341. }
  342.  
  343. public override string ResetPassword(string username, string answer)
  344. {
  345. throw new NotImplementedException();
  346. }
  347.  
  348. public override bool UnlockUser(string userName)
  349. {
  350. throw new NotImplementedException();
  351. }
  352.  
  353. public override void UpdateUser(System.Web.Security.MembershipUser user)
  354. {
  355. throw new NotImplementedException();
  356. }
  357.  
  358. public override bool ValidateUser(string username, string password)
  359. {
  360. using (var context = new MeuProjetoContext())
  361. {
  362. if (context == null) throw new InvalidOperationException();
  363.  
  364. var user = (from u in context.Usuarios
  365. where u.Email == username && u.Ativo == true
  366. select u).FirstOrDefault();
  367.  
  368. if (user != null)
  369. {
  370. byte[] pwdHash = GeneratePasswordHash(user.Salt, password);
  371. if (ByteArraysEqual(pwdHash, user.Hash))
  372. {
  373. bool isAdm = true;
  374.  
  375. System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1,
  376. user.UsuarioId.ToString() + "#" + username,
  377. DateTime.Now,
  378. DateTime.Now.AddMinutes(15),
  379. false,
  380. isAdm ? "#" + user.Nome : user.Nome,
  381. System.Web.Security.FormsAuthentication.FormsCookiePath);
  382.  
  383. #if DEBUG
  384. System.Diagnostics.Debugger.Log(0, "SEC", "User " + username + " logged in at " + ticket.IssueDate.ToString());
  385. #endif
  386.  
  387. // Encrypt the ticket.
  388. string encTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);
  389.  
  390. HttpContext.Current.Response.Cookies.Add(new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encTicket));
  391. return true;
  392. }
  393. }
  394.  
  395. return false;
  396. }
  397. }
  398. }
  399. }
  400.  
  401. using System;
  402. using System.Collections.Generic;
  403. using System.Linq;
  404. using System.Web;
  405. using System.Web.Security;
  406.  
  407. namespace MeuProjeto.Infrastructure
  408. {
  409. public class CustomMembershipUser : MembershipUser
  410. {
  411. public string Name { get; set; }
  412.  
  413. public CustomMembershipUser(
  414. string providername,
  415. string username,
  416. object providerUserKey,
  417. string email,
  418. string passwordQuestion,
  419. string comment,
  420. bool isApproved,
  421. bool isLockedOut,
  422. DateTime creationDate,
  423. DateTime lastLoginDate,
  424. DateTime lastActivityDate,
  425. DateTime lastPasswordChangedDate,
  426. DateTime lastLockedOutDate,
  427. // int companyFK,
  428. string name) :
  429.  
  430. base(providername,
  431. username,
  432. providerUserKey,
  433. email,
  434. passwordQuestion,
  435. comment,
  436. isApproved,
  437. isLockedOut,
  438. creationDate,
  439. lastLoginDate,
  440. lastPasswordChangedDate,
  441. lastActivityDate,
  442. lastLockedOutDate)
  443. {
  444. // CompanyFK = companyFK;
  445. Name = name;
  446. }
  447. }
  448. }
  449.  
  450. using MeuProjeto.Core.Models;
  451. using System;
  452. using System.Collections.Generic;
  453. using System.Linq;
  454. using System.Web;
  455. using System.Web.Security;
  456.  
  457. namespace MeuProjeto.Infrastructure
  458. {
  459. public class CustomRoleProvider : RoleProvider
  460. {
  461. public override void AddUsersToRoles(string[] usernames, string[] roleNames)
  462. {
  463. try
  464. {
  465. using (var context = new MeuProjetoContext())
  466. {
  467. foreach (string username in usernames)
  468. {
  469. // find each user in users table
  470. var user = context.Usuarios.Where(u => u.Email == username).FirstOrDefault();
  471.  
  472. if (user != null)
  473. {
  474. // find all roles that are contained in the roleNames
  475. var AllDbRoles = context.Roles.ToList();
  476.  
  477. List<Role> UserRoles = new List<Role>();
  478.  
  479. foreach (var roleName in roleNames)
  480. {
  481. var role = context.Roles.SingleOrDefault(r => r.Name == roleName);
  482.  
  483. if (role == default(Role))
  484. {
  485. throw new Exception("Role does not exist.");
  486. }
  487.  
  488. UserRoles.Add(role);
  489. }
  490.  
  491.  
  492. if (UserRoles.Count > 0)
  493. {
  494. foreach (var role in UserRoles)
  495. {
  496. if (!context.UserRoles.Where(ur => ur.UsuarioId == user.UsuarioId && ur.RoleId == role.RoleId).Any())
  497. {
  498. var userRole = new UserRole();
  499. userRole.UserRoleId = Guid.NewGuid();
  500. userRole.Usuario = user;
  501. userRole.Role = role;
  502. context.UserRoles.Add(userRole);
  503. context.SaveChanges();
  504. }
  505. }
  506. }
  507. }
  508. }
  509. }
  510. }
  511. catch (Exception e)
  512. {
  513. throw e;
  514. }
  515. }
  516.  
  517. public override void CreateRole(string roleName)
  518. {
  519. try
  520. {
  521. if (!RoleExists(roleName))
  522. {
  523. using (var context = new MeuProjetoContext())
  524. {
  525. Role role = new Role();
  526. role.RoleId = Guid.NewGuid();
  527. role.Name = roleName;
  528. context.Roles.Add(role);
  529. context.SaveChanges();
  530. }
  531. }
  532. }
  533. catch (Exception e)
  534. {
  535. throw e;
  536. }
  537. }
  538.  
  539. public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
  540. {
  541. using (var context = new MeuProjetoContext())
  542. {
  543. try
  544. {
  545. Role role = context.Roles.Where(r => r.Name == roleName).SingleOrDefault();
  546.  
  547. if (role != null)
  548. {
  549. context.Roles.Remove(role);
  550. context.SaveChanges();
  551. return true;
  552. }
  553. }
  554. catch
  555. {
  556. return false;
  557. }
  558. }
  559.  
  560. return false;
  561. }
  562.  
  563. public override string[] FindUsersInRole(string roleName, string usernameToMatch)
  564. {
  565. List<string> users = new List<string>();
  566.  
  567. using (var context = new MeuProjetoContext())
  568. {
  569. try
  570. {
  571. var usersInRole = context.UserRoles.Where(ur => ur.Role.Name == roleName && ur.Usuario.Email == usernameToMatch).ToList();
  572.  
  573. if (usersInRole != null)
  574. {
  575. foreach (var userInRole in usersInRole)
  576. {
  577. users.Add(userInRole.Usuario.Email);
  578. }
  579. }
  580. }
  581. catch { }
  582. }
  583.  
  584. return users.ToArray();
  585. }
  586.  
  587. public override string[] GetAllRoles()
  588. {
  589. List<string> roles = new List<string>();
  590.  
  591. using (var context = new MeuProjetoContext())
  592. {
  593. try
  594. {
  595. var dbRoles = context.Roles.ToList();
  596.  
  597. foreach (var role in dbRoles)
  598. {
  599. roles.Add(role.Name);
  600. }
  601. }
  602. catch { }
  603. }
  604.  
  605. return roles.ToArray();
  606. }
  607.  
  608. public override string[] GetRolesForUser(string username)
  609. {
  610. List<string> roles = new List<string>();
  611.  
  612. using (var context = new MeuProjetoContext())
  613. {
  614. try
  615. {
  616. var dbRoles = context.UserRoles.Where(r => r.Usuario.Email == username).ToList();
  617.  
  618. foreach (var role in dbRoles)
  619. {
  620. roles.Add(role.Role.Name);
  621. }
  622. }
  623. catch { }
  624. }
  625.  
  626. return roles.ToArray();
  627. }
  628.  
  629. public override string[] GetUsersInRole(string roleName)
  630. {
  631. List<string> users = new List<string>();
  632.  
  633. using (var context = new MeuProjetoContext())
  634. {
  635. try
  636. {
  637. var usersInRole = context.UserRoles.Where(ur => ur.Role.Name == roleName).ToList();
  638.  
  639. if (usersInRole != null)
  640. {
  641. foreach (var userInRole in usersInRole)
  642. {
  643. users.Add(userInRole.Usuario.Email);
  644. }
  645. }
  646. }
  647. catch { }
  648. }
  649.  
  650. return users.ToArray();
  651. }
  652.  
  653. public override bool IsUserInRole(string username, string roleName)
  654. {
  655. using (var context = new MeuProjetoContext())
  656. {
  657. try
  658. {
  659. var usersInRole = context.UserRoles.SingleOrDefault(ur => ur.Usuario.Email == username && ur.Role.Name == roleName);
  660.  
  661. if (usersInRole != default(UserRole))
  662. {
  663. return true;
  664. }
  665. }
  666. catch (Exception ex)
  667. {
  668. throw ex;
  669. }
  670. }
  671.  
  672. return false;
  673. }
  674.  
  675. public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
  676. {
  677. try
  678. {
  679. using (var context = new MeuProjetoContext())
  680. {
  681. foreach (string username in usernames)
  682. {
  683. // find each user in users table
  684. var user = context.Usuarios.Where(u => u.Email == username).SingleOrDefault();
  685.  
  686. if (user != null)
  687. {
  688. // find all roles that are contained in the roleNames
  689. var AllDbRoles = context.Roles.ToList();
  690.  
  691. List<Role> RemoveRoles = new List<Role>();
  692.  
  693. foreach (var role in AllDbRoles)
  694. {
  695. foreach (string roleName in roleNames)
  696. {
  697. if (role.Name == roleName)
  698. {
  699. RemoveRoles.Add(role);
  700. continue;
  701. }
  702. }
  703. }
  704.  
  705. if (RemoveRoles.Count > 0)
  706. {
  707. foreach (var role in RemoveRoles)
  708. {
  709. UserRole userRole = context.UserRoles
  710. .Where(ur => ur.UsuarioId == user.UsuarioId && ur.RoleId == role.RoleId)
  711. .SingleOrDefault();
  712.  
  713. if (userRole != null)
  714. {
  715. context.UserRoles.Remove(userRole);
  716. context.SaveChanges();
  717. }
  718. }
  719. }
  720. }
  721. }
  722. }
  723. }
  724.  
  725. catch { }
  726. }
  727.  
  728. public override bool RoleExists(string roleName)
  729. {
  730. using (var context = new MeuProjetoContext())
  731. {
  732. // check if role exits
  733. return context.Roles.Any(r => r.Name == roleName);
  734. }
  735. }
  736. }
  737. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement