Advertisement
Guest User

Untitled

a guest
Jun 30th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.01 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using Microsoft.AspNet.Identity;
  9. using Microsoft.AspNet.Identity.EntityFramework;
  10. using Microsoft.AspNet.Identity.Owin;
  11. using Microsoft.Owin.Security;
  12. using Owin;
  13. using MVC_Postfun.Models;
  14.  
  15. namespace MVC_Postfun.Controllers
  16. {
  17. [Authorize]
  18. public class AccountController : Controller
  19. {
  20. private ApplicationUserManager _userManager;
  21.  
  22. public AccountController()
  23. {
  24. }
  25.  
  26. public AccountController(ApplicationUserManager userManager)
  27. {
  28. UserManager = userManager;
  29. }
  30.  
  31. public ApplicationUserManager UserManager {
  32. get
  33. {
  34. return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
  35. }
  36. private set
  37. {
  38. _userManager = value;
  39. }
  40. }
  41.  
  42. //
  43. // GET: /Account/Login
  44. [AllowAnonymous]
  45. public ActionResult Login(string returnUrl)
  46. {
  47. ViewBag.ReturnUrl = returnUrl;
  48. return View();
  49. }
  50.  
  51. //
  52. // POST: /Account/Login
  53. [HttpPost]
  54. [AllowAnonymous]
  55. [ValidateAntiForgeryToken]
  56. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  57. {
  58. if (ModelState.IsValid)
  59. {
  60. var user = await UserManager.FindAsync(model.Email, model.Password);
  61. if (user != null)
  62. {
  63. await SignInAsync(user, model.RememberMe);
  64. return RedirectToLocal(returnUrl);
  65. }
  66. else
  67. {
  68. ModelState.AddModelError("", "Invalid username or password.");
  69. }
  70. }
  71.  
  72. // If we got this far, something failed, redisplay form
  73. return View(model);
  74. }
  75.  
  76. //
  77. // GET: /Account/Register
  78. [AllowAnonymous]
  79. public ActionResult Register()
  80. {
  81. return View();
  82. }
  83.  
  84. //
  85. // POST: /Account/Register
  86. [HttpPost]
  87. [AllowAnonymous]
  88. [ValidateAntiForgeryToken]
  89. public async Task<ActionResult> Register(RegisterViewModel model)
  90. {
  91. if (ModelState.IsValid)
  92. {
  93. var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
  94. IdentityResult result = await UserManager.CreateAsync(user, model.Password);
  95. if (result.Succeeded)
  96. {
  97. await SignInAsync(user, isPersistent: false);
  98.  
  99. // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  100. // Send an email with this link
  101. // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  102. // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  103. // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
  104.  
  105. return RedirectToAction("Index", "Post");
  106. }
  107. else
  108. {
  109. AddErrors(result);
  110. }
  111. }
  112.  
  113. // If we got this far, something failed, redisplay form
  114. return View(model);
  115. }
  116.  
  117. //
  118. // GET: /Account/ConfirmEmail
  119. [AllowAnonymous]
  120. public async Task<ActionResult> ConfirmEmail(string userId, string code)
  121. {
  122. if (userId == null || code == null)
  123. {
  124. return View("Error");
  125. }
  126.  
  127. IdentityResult result = await UserManager.ConfirmEmailAsync(userId, code);
  128. if (result.Succeeded)
  129. {
  130. return View("ConfirmEmail");
  131. }
  132. else
  133. {
  134. AddErrors(result);
  135. return View();
  136. }
  137. }
  138.  
  139. //
  140. // GET: /Account/ForgotPassword
  141. [AllowAnonymous]
  142. public ActionResult ForgotPassword()
  143. {
  144. return View();
  145. }
  146.  
  147. //
  148. // POST: /Account/ForgotPassword
  149. [HttpPost]
  150. [AllowAnonymous]
  151. [ValidateAntiForgeryToken]
  152. public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
  153. {
  154. if (ModelState.IsValid)
  155. {
  156. var user = await UserManager.FindByNameAsync(model.Email);
  157. if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
  158. {
  159. ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
  160. return View();
  161. }
  162.  
  163. // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  164. // Send an email with this link
  165. // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
  166. // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  167. // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
  168. // return RedirectToAction("ForgotPasswordConfirmation", "Account");
  169. }
  170.  
  171. // If we got this far, something failed, redisplay form
  172. return View(model);
  173. }
  174.  
  175. //
  176. // GET: /Account/ForgotPasswordConfirmation
  177. [AllowAnonymous]
  178. public ActionResult ForgotPasswordConfirmation()
  179. {
  180. return View();
  181. }
  182.  
  183. //
  184. // GET: /Account/ResetPassword
  185. [AllowAnonymous]
  186. public ActionResult ResetPassword(string code)
  187. {
  188. if (code == null)
  189. {
  190. return View("Error");
  191. }
  192. return View();
  193. }
  194.  
  195. //
  196. // POST: /Account/ResetPassword
  197. [HttpPost]
  198. [AllowAnonymous]
  199. [ValidateAntiForgeryToken]
  200. public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
  201. {
  202. if (ModelState.IsValid)
  203. {
  204. var user = await UserManager.FindByNameAsync(model.Email);
  205. if (user == null)
  206. {
  207. ModelState.AddModelError("", "No user found.");
  208. return View();
  209. }
  210. IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
  211. if (result.Succeeded)
  212. {
  213. return RedirectToAction("ResetPasswordConfirmation", "Account");
  214. }
  215. else
  216. {
  217. AddErrors(result);
  218. return View();
  219. }
  220. }
  221.  
  222. // If we got this far, something failed, redisplay form
  223. return View(model);
  224. }
  225.  
  226. //
  227. // GET: /Account/ResetPasswordConfirmation
  228. [AllowAnonymous]
  229. public ActionResult ResetPasswordConfirmation()
  230. {
  231. return View();
  232. }
  233.  
  234. //
  235. // POST: /Account/Disassociate
  236. [HttpPost]
  237. [ValidateAntiForgeryToken]
  238. public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
  239. {
  240. ManageMessageId? message = null;
  241. IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
  242. if (result.Succeeded)
  243. {
  244. var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
  245. await SignInAsync(user, isPersistent: false);
  246. message = ManageMessageId.RemoveLoginSuccess;
  247. }
  248. else
  249. {
  250. message = ManageMessageId.Error;
  251. }
  252. return RedirectToAction("Manage", new { Message = message });
  253. }
  254.  
  255. //
  256. // GET: /Account/Manage
  257. public ActionResult Manage(ManageMessageId? message)
  258. {
  259. ViewBag.StatusMessage =
  260. message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
  261. : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
  262. : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
  263. : message == ManageMessageId.Error ? "An error has occurred."
  264. : "";
  265. ViewBag.HasLocalPassword = HasPassword();
  266. ViewBag.ReturnUrl = Url.Action("Manage");
  267. return View();
  268. }
  269.  
  270. //
  271. // POST: /Account/Manage
  272. [HttpPost]
  273. [ValidateAntiForgeryToken]
  274. public async Task<ActionResult> Manage(ManageUserViewModel model)
  275. {
  276. bool hasPassword = HasPassword();
  277. ViewBag.HasLocalPassword = hasPassword;
  278. ViewBag.ReturnUrl = Url.Action("Manage");
  279. if (hasPassword)
  280. {
  281. if (ModelState.IsValid)
  282. {
  283. IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
  284. if (result.Succeeded)
  285. {
  286. var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
  287. await SignInAsync(user, isPersistent: false);
  288. return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
  289. }
  290. else
  291. {
  292. AddErrors(result);
  293. }
  294. }
  295. }
  296. else
  297. {
  298. // User does not have a password so remove any validation errors caused by a missing OldPassword field
  299. ModelState state = ModelState["OldPassword"];
  300. if (state != null)
  301. {
  302. state.Errors.Clear();
  303. }
  304.  
  305. if (ModelState.IsValid)
  306. {
  307. IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
  308. if (result.Succeeded)
  309. {
  310. return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
  311. }
  312. else
  313. {
  314. AddErrors(result);
  315. }
  316. }
  317. }
  318.  
  319. // If we got this far, something failed, redisplay form
  320. return View(model);
  321. }
  322.  
  323. //
  324. // POST: /Account/ExternalLogin
  325. [HttpPost]
  326. [AllowAnonymous]
  327. [ValidateAntiForgeryToken]
  328. public ActionResult ExternalLogin(string provider, string returnUrl)
  329. {
  330. // Request a redirect to the external login provider
  331. return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
  332. }
  333.  
  334. //
  335. // GET: /Account/ExternalLoginCallback
  336. [AllowAnonymous]
  337. public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
  338. {
  339. var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
  340. if (loginInfo == null)
  341. {
  342. return RedirectToAction("Login");
  343. }
  344.  
  345. // Sign in the user with this external login provider if the user already has a login
  346. var user = await UserManager.FindAsync(loginInfo.Login);
  347. if (user != null)
  348. {
  349. await SignInAsync(user, isPersistent: false);
  350. return RedirectToLocal(returnUrl);
  351. }
  352. else
  353. {
  354. // If the user does not have an account, then prompt the user to create an account
  355. ViewBag.ReturnUrl = returnUrl;
  356. ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
  357. return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
  358. }
  359. }
  360.  
  361. //
  362. // POST: /Account/LinkLogin
  363. [HttpPost]
  364. [ValidateAntiForgeryToken]
  365. public ActionResult LinkLogin(string provider)
  366. {
  367. // Request a redirect to the external login provider to link a login for the current user
  368. return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
  369. }
  370.  
  371. //
  372. // GET: /Account/LinkLoginCallback
  373. public async Task<ActionResult> LinkLoginCallback()
  374. {
  375. var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
  376. if (loginInfo == null)
  377. {
  378. return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
  379. }
  380. IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
  381. if (result.Succeeded)
  382. {
  383. return RedirectToAction("Manage");
  384. }
  385. return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
  386. }
  387.  
  388. //
  389. // POST: /Account/ExternalLoginConfirmation
  390. [HttpPost]
  391. [AllowAnonymous]
  392. [ValidateAntiForgeryToken]
  393. public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
  394. {
  395. if (User.Identity.IsAuthenticated)
  396. {
  397. return RedirectToAction("Manage");
  398. }
  399.  
  400. if (ModelState.IsValid)
  401. {
  402. // Get the information about the user from the external login provider
  403. var info = await AuthenticationManager.GetExternalLoginInfoAsync();
  404. if (info == null)
  405. {
  406. return View("ExternalLoginFailure");
  407. }
  408. var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
  409. IdentityResult result = await UserManager.CreateAsync(user);
  410. if (result.Succeeded)
  411. {
  412. result = await UserManager.AddLoginAsync(user.Id, info.Login);
  413. if (result.Succeeded)
  414. {
  415. await SignInAsync(user, isPersistent: false);
  416.  
  417. // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  418. // Send an email with this link
  419. // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  420. // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  421. // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link");
  422.  
  423. return RedirectToLocal(returnUrl);
  424. }
  425. }
  426. AddErrors(result);
  427. }
  428.  
  429. ViewBag.ReturnUrl = returnUrl;
  430. return View(model);
  431. }
  432.  
  433. //
  434. // POST: /Account/LogOff
  435. [HttpPost]
  436. [ValidateAntiForgeryToken]
  437. public ActionResult LogOff()
  438. {
  439. AuthenticationManager.SignOut();
  440. return RedirectToAction("Index", "Home");
  441. }
  442.  
  443. //
  444. // GET: /Account/ExternalLoginFailure
  445. [AllowAnonymous]
  446. public ActionResult ExternalLoginFailure()
  447. {
  448. return View();
  449. }
  450.  
  451. [ChildActionOnly]
  452. public ActionResult RemoveAccountList()
  453. {
  454. var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
  455. ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
  456. return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
  457. }
  458.  
  459. protected override void Dispose(bool disposing)
  460. {
  461. if (disposing && UserManager != null)
  462. {
  463. UserManager.Dispose();
  464. UserManager = null;
  465. }
  466. base.Dispose(disposing);
  467. }
  468.  
  469. #region Helpers
  470. // Used for XSRF protection when adding external logins
  471. private const string XsrfKey = "XsrfId";
  472.  
  473. private IAuthenticationManager AuthenticationManager
  474. {
  475. get
  476. {
  477. return HttpContext.GetOwinContext().Authentication;
  478. }
  479. }
  480.  
  481. private async Task SignInAsync(ApplicationUser user, bool isPersistent)
  482. {
  483. AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  484. AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
  485. }
  486.  
  487. private void AddErrors(IdentityResult result)
  488. {
  489. foreach (var error in result.Errors)
  490. {
  491. ModelState.AddModelError("", error);
  492. }
  493. }
  494.  
  495. private bool HasPassword()
  496. {
  497. var user = UserManager.FindById(User.Identity.GetUserId());
  498. if (user != null)
  499. {
  500. return user.PasswordHash != null;
  501. }
  502. return false;
  503. }
  504.  
  505. private void SendEmail(string email, string callbackUrl, string subject, string message)
  506. {
  507. // For information on sending mail, please visit http://go.microsoft.com/fwlink/?LinkID=320771
  508. }
  509.  
  510. public enum ManageMessageId
  511. {
  512. ChangePasswordSuccess,
  513. SetPasswordSuccess,
  514. RemoveLoginSuccess,
  515. Error
  516. }
  517.  
  518. private ActionResult RedirectToLocal(string returnUrl)
  519. {
  520. if (Url.IsLocalUrl(returnUrl))
  521. {
  522. return Redirect(returnUrl);
  523. }
  524. else
  525. {
  526. return RedirectToAction("Index", "Home");
  527. }
  528. }
  529.  
  530. private class ChallengeResult : HttpUnauthorizedResult
  531. {
  532. public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
  533. {
  534. }
  535.  
  536. public ChallengeResult(string provider, string redirectUri, string userId)
  537. {
  538. LoginProvider = provider;
  539. RedirectUri = redirectUri;
  540. UserId = userId;
  541. }
  542.  
  543. public string LoginProvider { get; set; }
  544. public string RedirectUri { get; set; }
  545. public string UserId { get; set; }
  546.  
  547. public override void ExecuteResult(ControllerContext context)
  548. {
  549. var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
  550. if (UserId != null)
  551. {
  552. properties.Dictionary[XsrfKey] = UserId;
  553. }
  554. context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  555. }
  556. }
  557. #endregion
  558. }
  559. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement