Advertisement
lignite0

AccountController C# ASP.NET

Feb 1st, 2017
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.06 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.Owin.Security;
  11. using WebApplication1.Models;
  12.  
  13. namespace WebApplication1.Controllers
  14. {
  15.     [Authorize]
  16.     public class AccountController : Controller
  17.     {
  18.         public AccountController()
  19.             : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
  20.         {
  21.         }
  22.  
  23.         public AccountController(UserManager<ApplicationUser> userManager)
  24.         {
  25.             UserManager = userManager;
  26.         }
  27.  
  28.         public UserManager<ApplicationUser> UserManager { get; private set; }
  29.  
  30.         //
  31.         // GET: /Account/Login
  32.         [AllowAnonymous]
  33.         public ActionResult Login(string returnUrl)
  34.         {
  35.             ViewBag.ReturnUrl = returnUrl;
  36.             return View();
  37.         }
  38.  
  39.         //
  40.         // POST: /Account/Login
  41.         [HttpPost]
  42.         [AllowAnonymous]
  43.         [ValidateAntiForgeryToken]
  44.         public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  45.         {
  46.             if (ModelState.IsValid)
  47.             {
  48.                 var user = await UserManager.FindAsync(model.UserName, model.Password);
  49.                 if (user != null)
  50.                 {
  51.                     await SignInAsync(user, model.RememberMe);
  52.                     return RedirectToLocal(returnUrl);
  53.                 }
  54.                 else
  55.                 {
  56.                     ModelState.AddModelError("", "Invalid username or password.");
  57.                 }
  58.             }
  59.  
  60.             // If we got this far, something failed, redisplay form
  61.             return View(model);
  62.         }
  63.  
  64.         //
  65.         // GET: /Account/Register
  66.         [AllowAnonymous]
  67.         public ActionResult Register()
  68.         {
  69.             return View();
  70.         }
  71.  
  72.         //
  73.         // POST: /Account/Register
  74.         [HttpPost]
  75.         [AllowAnonymous]
  76.         [ValidateAntiForgeryToken]
  77.         public async Task<ActionResult> Register(RegisterViewModel model)
  78.         {
  79.             if (ModelState.IsValid)
  80.             {
  81.                 var user = new ApplicationUser() { UserName = model.UserName };
  82.                 var result = await UserManager.CreateAsync(user, model.Password);
  83.                 if (result.Succeeded)
  84.                 {
  85.                     await SignInAsync(user, isPersistent: false);
  86.                     return RedirectToAction("Index", "Home");
  87.                 }
  88.                 else
  89.                 {
  90.                     AddErrors(result);
  91.                 }
  92.             }
  93.  
  94.             // If we got this far, something failed, redisplay form
  95.             return View(model);
  96.         }
  97.  
  98.         //
  99.         // POST: /Account/Disassociate
  100.         [HttpPost]
  101.         [ValidateAntiForgeryToken]
  102.         public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
  103.         {
  104.             ManageMessageId? message = null;
  105.             IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
  106.             if (result.Succeeded)
  107.             {
  108.                 message = ManageMessageId.RemoveLoginSuccess;
  109.             }
  110.             else
  111.             {
  112.                 message = ManageMessageId.Error;
  113.             }
  114.             return RedirectToAction("Manage", new { Message = message });
  115.         }
  116.  
  117.         //
  118.         // GET: /Account/Manage
  119.         public ActionResult Manage(ManageMessageId? message)
  120.         {
  121.             ViewBag.StatusMessage =
  122.                 message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
  123.                 : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
  124.                 : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
  125.                 : message == ManageMessageId.Error ? "An error has occurred."
  126.                 : "";
  127.             ViewBag.HasLocalPassword = HasPassword();
  128.             ViewBag.ReturnUrl = Url.Action("Manage");
  129.             return View();
  130.         }
  131.  
  132.         //
  133.         // POST: /Account/Manage
  134.         [HttpPost]
  135.         [ValidateAntiForgeryToken]
  136.         public async Task<ActionResult> Manage(ManageUserViewModel model)
  137.         {
  138.             bool hasPassword = HasPassword();
  139.             ViewBag.HasLocalPassword = hasPassword;
  140.             ViewBag.ReturnUrl = Url.Action("Manage");
  141.             if (hasPassword)
  142.             {
  143.                 if (ModelState.IsValid)
  144.                 {
  145.                     IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
  146.                     if (result.Succeeded)
  147.                     {
  148.                         return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
  149.                     }
  150.                     else
  151.                     {
  152.                         AddErrors(result);
  153.                     }
  154.                 }
  155.             }
  156.             else
  157.             {
  158.                 // User does not have a password so remove any validation errors caused by a missing OldPassword field
  159.                 ModelState state = ModelState["OldPassword"];
  160.                 if (state != null)
  161.                 {
  162.                     state.Errors.Clear();
  163.                 }
  164.  
  165.                 if (ModelState.IsValid)
  166.                 {
  167.                     IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
  168.                     if (result.Succeeded)
  169.                     {
  170.                         return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
  171.                     }
  172.                     else
  173.                     {
  174.                         AddErrors(result);
  175.                     }
  176.                 }
  177.             }
  178.  
  179.             // If we got this far, something failed, redisplay form
  180.             return View(model);
  181.         }
  182.  
  183.         //
  184.         // POST: /Account/ExternalLogin
  185.         [HttpPost]
  186.         [AllowAnonymous]
  187.         [ValidateAntiForgeryToken]
  188.         public ActionResult ExternalLogin(string provider, string returnUrl)
  189.         {
  190.             // Request a redirect to the external login provider
  191.             return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
  192.         }
  193.  
  194.         //
  195.         // GET: /Account/ExternalLoginCallback
  196.         [AllowAnonymous]
  197.         public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
  198.         {
  199.             var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
  200.             if (loginInfo == null)
  201.             {
  202.                 return RedirectToAction("Login");
  203.             }
  204.  
  205.             // Sign in the user with this external login provider if the user already has a login
  206.             var user = await UserManager.FindAsync(loginInfo.Login);
  207.             if (user != null)
  208.             {
  209.                 await SignInAsync(user, isPersistent: false);
  210.                 return RedirectToLocal(returnUrl);
  211.             }
  212.             else
  213.             {
  214.                 // If the user does not have an account, then prompt the user to create an account
  215.                 ViewBag.ReturnUrl = returnUrl;
  216.                 ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
  217.                 return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = loginInfo.DefaultUserName });
  218.             }
  219.         }
  220.  
  221.         //
  222.         // POST: /Account/LinkLogin
  223.         [HttpPost]
  224.         [ValidateAntiForgeryToken]
  225.         public ActionResult LinkLogin(string provider)
  226.         {
  227.             // Request a redirect to the external login provider to link a login for the current user
  228.             return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
  229.         }
  230.  
  231.         //
  232.         // GET: /Account/LinkLoginCallback
  233.         public async Task<ActionResult> LinkLoginCallback()
  234.         {
  235.             var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
  236.             if (loginInfo == null)
  237.             {
  238.                 return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
  239.             }
  240.             var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
  241.             if (result.Succeeded)
  242.             {
  243.                 return RedirectToAction("Manage");
  244.             }
  245.             return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
  246.         }
  247.  
  248.         //
  249.         // POST: /Account/ExternalLoginConfirmation
  250.         [HttpPost]
  251.         [AllowAnonymous]
  252.         [ValidateAntiForgeryToken]
  253.         public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
  254.         {
  255.             if (User.Identity.IsAuthenticated)
  256.             {
  257.                 return RedirectToAction("Manage");
  258.             }
  259.  
  260.             if (ModelState.IsValid)
  261.             {
  262.                 // Get the information about the user from the external login provider
  263.                 var info = await AuthenticationManager.GetExternalLoginInfoAsync();
  264.                 if (info == null)
  265.                 {
  266.                     return View("ExternalLoginFailure");
  267.                 }
  268.                 var user = new ApplicationUser() { UserName = model.UserName };
  269.                 var result = await UserManager.CreateAsync(user);
  270.                 if (result.Succeeded)
  271.                 {
  272.                     result = await UserManager.AddLoginAsync(user.Id, info.Login);
  273.                     if (result.Succeeded)
  274.                     {
  275.                         await SignInAsync(user, isPersistent: false);
  276.                         return RedirectToLocal(returnUrl);
  277.                     }
  278.                 }
  279.                 AddErrors(result);
  280.             }
  281.  
  282.             ViewBag.ReturnUrl = returnUrl;
  283.             return View(model);
  284.         }
  285.  
  286.         //
  287.         // POST: /Account/LogOff
  288.         [HttpPost]
  289.         [ValidateAntiForgeryToken]
  290.         public ActionResult LogOff()
  291.         {
  292.             AuthenticationManager.SignOut();
  293.             return RedirectToAction("Index", "Home");
  294.         }
  295.  
  296.         //
  297.         // GET: /Account/ExternalLoginFailure
  298.         [AllowAnonymous]
  299.         public ActionResult ExternalLoginFailure()
  300.         {
  301.             return View();
  302.         }
  303.  
  304.         [ChildActionOnly]
  305.         public ActionResult RemoveAccountList()
  306.         {
  307.             var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
  308.             ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
  309.             return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
  310.         }
  311.  
  312.         protected override void Dispose(bool disposing)
  313.         {
  314.             if (disposing && UserManager != null)
  315.             {
  316.                 UserManager.Dispose();
  317.                 UserManager = null;
  318.             }
  319.             base.Dispose(disposing);
  320.         }
  321.  
  322.         #region Helpers
  323.         // Used for XSRF protection when adding external logins
  324.         private const string XsrfKey = "XsrfId";
  325.  
  326.         private IAuthenticationManager AuthenticationManager
  327.         {
  328.             get
  329.             {
  330.                 return HttpContext.GetOwinContext().Authentication;
  331.             }
  332.         }
  333.  
  334.         private async Task SignInAsync(ApplicationUser user, bool isPersistent)
  335.         {
  336.             AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  337.             var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
  338.             AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
  339.         }
  340.  
  341.         private void AddErrors(IdentityResult result)
  342.         {
  343.             foreach (var error in result.Errors)
  344.             {
  345.                 ModelState.AddModelError("", error);
  346.             }
  347.         }
  348.  
  349.         private bool HasPassword()
  350.         {
  351.             var user = UserManager.FindById(User.Identity.GetUserId());
  352.             if (user != null)
  353.             {
  354.                 return user.PasswordHash != null;
  355.             }
  356.             return false;
  357.         }
  358.  
  359.         public enum ManageMessageId
  360.         {
  361.             ChangePasswordSuccess,
  362.             SetPasswordSuccess,
  363.             RemoveLoginSuccess,
  364.             Error
  365.         }
  366.  
  367.         private ActionResult RedirectToLocal(string returnUrl)
  368.         {
  369.             if (Url.IsLocalUrl(returnUrl))
  370.             {
  371.                 return Redirect(returnUrl);
  372.             }
  373.             else
  374.             {
  375.                 return RedirectToAction("Index", "Home");
  376.             }
  377.         }
  378.  
  379.         private class ChallengeResult : HttpUnauthorizedResult
  380.         {
  381.             public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
  382.             {
  383.             }
  384.  
  385.             public ChallengeResult(string provider, string redirectUri, string userId)
  386.             {
  387.                 LoginProvider = provider;
  388.                 RedirectUri = redirectUri;
  389.                 UserId = userId;
  390.             }
  391.  
  392.             public string LoginProvider { get; set; }
  393.             public string RedirectUri { get; set; }
  394.             public string UserId { get; set; }
  395.  
  396.             public override void ExecuteResult(ControllerContext context)
  397.             {
  398.                 var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
  399.                 if (UserId != null)
  400.                 {
  401.                     properties.Dictionary[XsrfKey] = UserId;
  402.                 }
  403.                 context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  404.             }
  405.         }
  406.         #endregion
  407.     }
  408. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement