Advertisement
Venciity

Untitled

May 24th, 2015
778
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.05 KB | None | 0 0
  1. using System;
  2. using System.Globalization;
  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.Owin;
  10. using Microsoft.Owin.Security;
  11. using PompeiiSquare.Server.Models;
  12. using PompeiiSquare.Models;
  13.  
  14. namespace PompeiiSquare.Server.Controllers
  15. {
  16.     [Authorize]
  17.     public class AccountController : Controller
  18.     {
  19.         private ApplicationSignInManager _signInManager;
  20.         private ApplicationUserManager _userManager;
  21.  
  22.         public AccountController()
  23.         {
  24.         }
  25.  
  26.         public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
  27.         {
  28.             UserManager = userManager;
  29.             SignInManager = signInManager;
  30.         }
  31.  
  32.         public ApplicationSignInManager SignInManager
  33.         {
  34.             get
  35.             {
  36.                 return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
  37.             }
  38.             private set
  39.             {
  40.                 _signInManager = value;
  41.             }
  42.         }
  43.  
  44.         public ApplicationUserManager UserManager
  45.         {
  46.             get
  47.             {
  48.                 return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
  49.             }
  50.             private set
  51.             {
  52.                 _userManager = value;
  53.             }
  54.         }
  55.  
  56.         //
  57.         // GET: /Account/Login
  58.         [AllowAnonymous]
  59.         public ActionResult Login(string returnUrl)
  60.         {
  61.             ViewBag.ReturnUrl = returnUrl;
  62.             return View();
  63.         }
  64.  
  65.         //
  66.         // POST: /Account/Login
  67.         [HttpPost]
  68.         [AllowAnonymous]
  69.         [ValidateAntiForgeryToken]
  70.         public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  71.         {
  72.             if (!ModelState.IsValid)
  73.             {
  74.                 return View(model);
  75.             }
  76.  
  77.             // This doesn't count login failures towards account lockout
  78.             // To enable password failures to trigger account lockout, change to shouldLockout: true
  79.             var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
  80.             switch (result)
  81.             {
  82.                 case SignInStatus.Success:
  83.                     return RedirectToLocal(returnUrl);
  84.                 case SignInStatus.LockedOut:
  85.                     return View("Lockout");
  86.                 case SignInStatus.RequiresVerification:
  87.                     return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  88.                 case SignInStatus.Failure:
  89.                 default:
  90.                     ModelState.AddModelError("", "Invalid login attempt.");
  91.                     return View(model);
  92.             }
  93.         }
  94.  
  95.         //
  96.         // GET: /Account/VerifyCode
  97.         [AllowAnonymous]
  98.         public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
  99.         {
  100.             // Require that the user has already logged in via username/password or external login
  101.             if (!await SignInManager.HasBeenVerifiedAsync())
  102.             {
  103.                 return View("Error");
  104.             }
  105.             return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
  106.         }
  107.  
  108.         //
  109.         // POST: /Account/VerifyCode
  110.         [HttpPost]
  111.         [AllowAnonymous]
  112.         [ValidateAntiForgeryToken]
  113.         public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
  114.         {
  115.             if (!ModelState.IsValid)
  116.             {
  117.                 return View(model);
  118.             }
  119.  
  120.             // The following code protects for brute force attacks against the two factor codes.
  121.             // If a user enters incorrect codes for a specified amount of time then the user account
  122.             // will be locked out for a specified amount of time.
  123.             // You can configure the account lockout settings in IdentityConfig
  124.             var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent:  model.RememberMe, rememberBrowser: model.RememberBrowser);
  125.             switch (result)
  126.             {
  127.                 case SignInStatus.Success:
  128.                     return RedirectToLocal(model.ReturnUrl);
  129.                 case SignInStatus.LockedOut:
  130.                     return View("Lockout");
  131.                 case SignInStatus.Failure:
  132.                 default:
  133.                     ModelState.AddModelError("", "Invalid code.");
  134.                     return View(model);
  135.             }
  136.         }
  137.  
  138.         //
  139.         // GET: /Account/Register
  140.         [AllowAnonymous]
  141.         public ActionResult Register()
  142.         {
  143.             return View();
  144.         }
  145.  
  146.         //
  147.         // POST: /Account/Register
  148.         [HttpPost]
  149.         [AllowAnonymous]
  150.         [ValidateAntiForgeryToken]
  151.         public async Task<ActionResult> Register(RegisterViewModel model)
  152.         {
  153.             if (ModelState.IsValid)
  154.             {
  155.                 //var user = new User { UserName = model.Email, Email = model.Email };
  156.                 var photo = new Photo
  157.                 {
  158.                     CreatedAt = DateTime.Now,
  159.                     Path = model.ProfilePicture.Path
  160.                 };
  161.                 var user = new User
  162.                 {
  163.                     UserName = model.UserName,
  164.                     FirstName = model.FirstName,
  165.                     LastName = model.LastName,
  166.                     HomeCity = model.HomeCity,
  167.                     Gender = model.Gender,
  168.                     Email = model.Email,
  169.                     ProfilePicture = photo
  170.                 };
  171.                 var result = await UserManager.CreateAsync(user, model.Password);
  172.                 if (result.Succeeded)
  173.                 {
  174.                     photo.Author = user;
  175.                     await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
  176.                    
  177.                     // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  178.                     // Send an email with this link
  179.                     // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  180.                     // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  181.                     // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
  182.  
  183.                     return RedirectToAction("Index", "Home");
  184.                 }
  185.                 AddErrors(result);
  186.             }
  187.  
  188.             // If we got this far, something failed, redisplay form
  189.             return View(model);
  190.         }
  191.  
  192.         //
  193.         // GET: /Account/ConfirmEmail
  194.         [AllowAnonymous]
  195.         public async Task<ActionResult> ConfirmEmail(string userId, string code)
  196.         {
  197.             if (userId == null || code == null)
  198.             {
  199.                 return View("Error");
  200.             }
  201.             var result = await UserManager.ConfirmEmailAsync(userId, code);
  202.             return View(result.Succeeded ? "ConfirmEmail" : "Error");
  203.         }
  204.  
  205.         //
  206.         // GET: /Account/ForgotPassword
  207.         [AllowAnonymous]
  208.         public ActionResult ForgotPassword()
  209.         {
  210.             return View();
  211.         }
  212.  
  213.         //
  214.         // POST: /Account/ForgotPassword
  215.         [HttpPost]
  216.         [AllowAnonymous]
  217.         [ValidateAntiForgeryToken]
  218.         public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
  219.         {
  220.             if (ModelState.IsValid)
  221.             {
  222.                 var user = await UserManager.FindByNameAsync(model.Email);
  223.                 if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
  224.                 {
  225.                     // Don't reveal that the user does not exist or is not confirmed
  226.                     return View("ForgotPasswordConfirmation");
  227.                 }
  228.  
  229.                 // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  230.                 // Send an email with this link
  231.                 // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
  232.                 // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);      
  233.                 // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
  234.                 // return RedirectToAction("ForgotPasswordConfirmation", "Account");
  235.             }
  236.  
  237.             // If we got this far, something failed, redisplay form
  238.             return View(model);
  239.         }
  240.  
  241.         //
  242.         // GET: /Account/ForgotPasswordConfirmation
  243.         [AllowAnonymous]
  244.         public ActionResult ForgotPasswordConfirmation()
  245.         {
  246.             return View();
  247.         }
  248.  
  249.         //
  250.         // GET: /Account/ResetPassword
  251.         [AllowAnonymous]
  252.         public ActionResult ResetPassword(string code)
  253.         {
  254.             return code == null ? View("Error") : View();
  255.         }
  256.  
  257.         //
  258.         // POST: /Account/ResetPassword
  259.         [HttpPost]
  260.         [AllowAnonymous]
  261.         [ValidateAntiForgeryToken]
  262.         public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
  263.         {
  264.             if (!ModelState.IsValid)
  265.             {
  266.                 return View(model);
  267.             }
  268.             var user = await UserManager.FindByNameAsync(model.Email);
  269.             if (user == null)
  270.             {
  271.                 // Don't reveal that the user does not exist
  272.                 return RedirectToAction("ResetPasswordConfirmation", "Account");
  273.             }
  274.             var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
  275.             if (result.Succeeded)
  276.             {
  277.                 return RedirectToAction("ResetPasswordConfirmation", "Account");
  278.             }
  279.             AddErrors(result);
  280.             return View();
  281.         }
  282.  
  283.         //
  284.         // GET: /Account/ResetPasswordConfirmation
  285.         [AllowAnonymous]
  286.         public ActionResult ResetPasswordConfirmation()
  287.         {
  288.             return View();
  289.         }
  290.  
  291.         //
  292.         // POST: /Account/ExternalLogin
  293.         [HttpPost]
  294.         [AllowAnonymous]
  295.         [ValidateAntiForgeryToken]
  296.         public ActionResult ExternalLogin(string provider, string returnUrl)
  297.         {
  298.             // Request a redirect to the external login provider
  299.             return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
  300.         }
  301.  
  302.         //
  303.         // GET: /Account/SendCode
  304.         [AllowAnonymous]
  305.         public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
  306.         {
  307.             var userId = await SignInManager.GetVerifiedUserIdAsync();
  308.             if (userId == null)
  309.             {
  310.                 return View("Error");
  311.             }
  312.             var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
  313.             var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
  314.             return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
  315.         }
  316.  
  317.         //
  318.         // POST: /Account/SendCode
  319.         [HttpPost]
  320.         [AllowAnonymous]
  321.         [ValidateAntiForgeryToken]
  322.         public async Task<ActionResult> SendCode(SendCodeViewModel model)
  323.         {
  324.             if (!ModelState.IsValid)
  325.             {
  326.                 return View();
  327.             }
  328.  
  329.             // Generate the token and send it
  330.             if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
  331.             {
  332.                 return View("Error");
  333.             }
  334.             return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
  335.         }
  336.  
  337.         //
  338.         // GET: /Account/ExternalLoginCallback
  339.         [AllowAnonymous]
  340.         public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
  341.         {
  342.             var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
  343.             if (loginInfo == null)
  344.             {
  345.                 return RedirectToAction("Login");
  346.             }
  347.  
  348.             // Sign in the user with this external login provider if the user already has a login
  349.             var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
  350.             switch (result)
  351.             {
  352.                 case SignInStatus.Success:
  353.                     return RedirectToLocal(returnUrl);
  354.                 case SignInStatus.LockedOut:
  355.                     return View("Lockout");
  356.                 case SignInStatus.RequiresVerification:
  357.                     return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
  358.                 case SignInStatus.Failure:
  359.                 default:
  360.                     // If the user does not have an account, then prompt the user to create an account
  361.                     ViewBag.ReturnUrl = returnUrl;
  362.                     ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
  363.                     return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
  364.             }
  365.         }
  366.  
  367.         //
  368.         // POST: /Account/ExternalLoginConfirmation
  369.         [HttpPost]
  370.         [AllowAnonymous]
  371.         [ValidateAntiForgeryToken]
  372.         public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
  373.         {
  374.             if (User.Identity.IsAuthenticated)
  375.             {
  376.                 return RedirectToAction("Index", "Manage");
  377.             }
  378.  
  379.             if (ModelState.IsValid)
  380.             {
  381.                 // Get the information about the user from the external login provider
  382.                 var info = await AuthenticationManager.GetExternalLoginInfoAsync();
  383.                 if (info == null)
  384.                 {
  385.                     return View("ExternalLoginFailure");
  386.                 }
  387.                 var user = new User { UserName = model.Email, Email = model.Email };
  388.                 var result = await UserManager.CreateAsync(user);
  389.                 if (result.Succeeded)
  390.                 {
  391.                     result = await UserManager.AddLoginAsync(user.Id, info.Login);
  392.                     if (result.Succeeded)
  393.                     {
  394.                         await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  395.                         return RedirectToLocal(returnUrl);
  396.                     }
  397.                 }
  398.                 AddErrors(result);
  399.             }
  400.  
  401.             ViewBag.ReturnUrl = returnUrl;
  402.             return View(model);
  403.         }
  404.  
  405.         //
  406.         // POST: /Account/LogOff
  407.         [HttpPost]
  408.         [ValidateAntiForgeryToken]
  409.         public ActionResult LogOff()
  410.         {
  411.             AuthenticationManager.SignOut();
  412.             return RedirectToAction("Index", "Home");
  413.         }
  414.  
  415.         //
  416.         // GET: /Account/ExternalLoginFailure
  417.         [AllowAnonymous]
  418.         public ActionResult ExternalLoginFailure()
  419.         {
  420.             return View();
  421.         }
  422.  
  423.         protected override void Dispose(bool disposing)
  424.         {
  425.             if (disposing)
  426.             {
  427.                 if (_userManager != null)
  428.                 {
  429.                     _userManager.Dispose();
  430.                     _userManager = null;
  431.                 }
  432.  
  433.                 if (_signInManager != null)
  434.                 {
  435.                     _signInManager.Dispose();
  436.                     _signInManager = null;
  437.                 }
  438.             }
  439.  
  440.             base.Dispose(disposing);
  441.         }
  442.  
  443.         #region Helpers
  444.         // Used for XSRF protection when adding external logins
  445.         private const string XsrfKey = "XsrfId";
  446.  
  447.         private IAuthenticationManager AuthenticationManager
  448.         {
  449.             get
  450.             {
  451.                 return HttpContext.GetOwinContext().Authentication;
  452.             }
  453.         }
  454.  
  455.         private void AddErrors(IdentityResult result)
  456.         {
  457.             foreach (var error in result.Errors)
  458.             {
  459.                 ModelState.AddModelError("", error);
  460.             }
  461.         }
  462.  
  463.         private ActionResult RedirectToLocal(string returnUrl)
  464.         {
  465.             if (Url.IsLocalUrl(returnUrl))
  466.             {
  467.                 return Redirect(returnUrl);
  468.             }
  469.             return RedirectToAction("Index", "Home");
  470.         }
  471.  
  472.         internal class ChallengeResult : HttpUnauthorizedResult
  473.         {
  474.             public ChallengeResult(string provider, string redirectUri)
  475.                 : this(provider, redirectUri, null)
  476.             {
  477.             }
  478.  
  479.             public ChallengeResult(string provider, string redirectUri, string userId)
  480.             {
  481.                 LoginProvider = provider;
  482.                 RedirectUri = redirectUri;
  483.                 UserId = userId;
  484.             }
  485.  
  486.             public string LoginProvider { get; set; }
  487.             public string RedirectUri { get; set; }
  488.             public string UserId { get; set; }
  489.  
  490.             public override void ExecuteResult(ControllerContext context)
  491.             {
  492.                 var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
  493.                 if (UserId != null)
  494.                 {
  495.                     properties.Dictionary[XsrfKey] = UserId;
  496.                 }
  497.                 context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  498.             }
  499.         }
  500.         #endregion
  501.     }
  502. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement