Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class AccountController : Controller
- {
- private ApplicationSignInManager _signInManager;
- private ApplicationUserManager _userManager;
- public AccountController()
- {
- }
- public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
- {
- UserManager = userManager;
- SignInManager = signInManager;
- }
- public ApplicationSignInManager SignInManager
- {
- get
- {
- return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
- }
- private set
- {
- _signInManager = value;
- }
- }
- public ApplicationUserManager UserManager
- {
- get
- {
- return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
- }
- private set
- {
- _userManager = value;
- }
- }
- //
- // GET: /Account/Login
- [AllowAnonymous]
- public ActionResult Login(string returnUrl)
- {
- //Create the Admin account using setting in Web.Config(if needed)
- //CreateAdminIfNeeded();
- //ViewBag.ReturnUrl = returnUrl;
- return View();
- //return RedirectToAction("Index", "UserLanding");
- }
- //
- // POST: /Account/Login
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- CreateAdminIfNeeded();
- // This doesn't count login failures towards account lockout
- // To enable password failures to trigger account lockout, change to shouldLockout: true
- var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
- switch (result)
- {
- case SignInStatus.Success:
- return RedirectToLocal(returnUrl);
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.RequiresVerification:
- return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
- case SignInStatus.Failure:
- ModelState.AddModelError("", "Invalid login attempt.");
- return View(model);
- default:
- ModelState.AddModelError("", "Invalid login attempt.");
- return View(model);
- }
- }
- //
- // GET: /Account/VerifyCode
- [AllowAnonymous]
- public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
- {
- // Require that the user has already logged in via username/password or external login
- if (!await SignInManager.HasBeenVerifiedAsync())
- {
- return View("Error");
- }
- return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
- }
- //
- // POST: /Account/VerifyCode
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- // The following code protects for brute force attacks against the two factor codes.
- // If a user enters incorrect codes for a specified amount of time then the user account
- // will be locked out for a specified amount of time.
- // You can configure the account lockout settings in IdentityConfig
- var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
- switch (result)
- {
- case SignInStatus.Success:
- return RedirectToLocal(model.ReturnUrl);
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.Failure:
- default:
- ModelState.AddModelError("", "Invalid code.");
- return View(model);
- }
- }
- //
- // GET: /Account/Register
- [AllowAnonymous]
- public ActionResult Register()
- {
- return View();
- }
- //
- // POST: /Account/Register
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Register(RegisterViewModel model)
- {
- if (ModelState.IsValid)
- {
- var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
- var result = await UserManager.CreateAsync(user, model.Password);
- if (result.Succeeded)
- {
- await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
- // Send an email with this link
- // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
- // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
- // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href="" + callbackUrl + "">here</a>");
- return RedirectToAction("Index", "Home");
- }
- AddErrors(result);
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- //
- // GET: /Account/ConfirmEmail
- [AllowAnonymous]
- public async Task<ActionResult> ConfirmEmail(string userId, string code)
- {
- if (userId == null || code == null)
- {
- return View("Error");
- }
- var result = await UserManager.ConfirmEmailAsync(userId, code);
- return View(result.Succeeded ? "ConfirmEmail" : "Error");
- }
- //
- // GET: /Account/ForgotPassword
- [AllowAnonymous]
- public ActionResult ForgotPassword()
- {
- return View();
- }
- //
- // POST: /Account/ForgotPassword
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
- {
- if (ModelState.IsValid)
- {
- var user = await UserManager.FindByNameAsync(model.Email);
- if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
- {
- // Don't reveal that the user does not exist or is not confirmed
- return View("ForgotPasswordConfirmation");
- }
- // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
- // Send an email with this link
- // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
- // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
- // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href="" + callbackUrl + "">here</a>");
- // return RedirectToAction("ForgotPasswordConfirmation", "Account");
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- //
- // GET: /Account/ForgotPasswordConfirmation
- [AllowAnonymous]
- public ActionResult ForgotPasswordConfirmation()
- {
- return View();
- }
- //
- // GET: /Account/ResetPassword
- [AllowAnonymous]
- public ActionResult ResetPassword(string code)
- {
- return code == null ? View("Error") : View();
- }
- //
- // POST: /Account/ResetPassword
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- var user = await UserManager.FindByNameAsync(model.Email);
- if (user == null)
- {
- // Don't reveal that the user does not exist
- return RedirectToAction("ResetPasswordConfirmation", "Account");
- }
- var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
- if (result.Succeeded)
- {
- return RedirectToAction("ResetPasswordConfirmation", "Account");
- }
- AddErrors(result);
- return View();
- }
- //
- // GET: /Account/ResetPasswordConfirmation
- [AllowAnonymous]
- public ActionResult ResetPasswordConfirmation()
- {
- return View();
- }
- //
- // POST: /Account/ExternalLogin
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult ExternalLogin(string provider, string returnUrl)
- {
- // Request a redirect to the external login provider
- return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
- }
- //
- // GET: /Account/SendCode
- [AllowAnonymous]
- public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
- {
- var userId = await SignInManager.GetVerifiedUserIdAsync();
- if (userId == null)
- {
- return View("Error");
- }
- var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
- var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
- return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
- }
- //
- // POST: /Account/SendCode
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> SendCode(SendCodeViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View();
- }
- // Generate the token and send it
- if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
- {
- return View("Error");
- }
- return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
- }
- //
- // GET: /Account/ExternalLoginCallback
- [AllowAnonymous]
- public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
- {
- var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
- if (loginInfo == null)
- {
- return RedirectToAction("Login");
- }
- // Sign in the user with this external login provider if the user already has a login
- var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
- switch (result)
- {
- case SignInStatus.Success:
- return RedirectToLocal(returnUrl);
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.RequiresVerification:
- return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
- case SignInStatus.Failure:
- default:
- // If the user does not have an account, then prompt the user to create an account
- ViewBag.ReturnUrl = returnUrl;
- ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
- return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
- }
- }
- //
- // POST: /Account/ExternalLoginConfirmation
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
- {
- if (User.Identity.IsAuthenticated)
- {
- return RedirectToAction("Index", "Manage");
- }
- if (ModelState.IsValid)
- {
- // Get the information about the user from the external login provider
- var info = await AuthenticationManager.GetExternalLoginInfoAsync();
- if (info == null)
- {
- return View("ExternalLoginFailure");
- }
- var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
- var result = await UserManager.CreateAsync(user);
- if (result.Succeeded)
- {
- result = await UserManager.AddLoginAsync(user.Id, info.Login);
- if (result.Succeeded)
- {
- await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- return RedirectToLocal(returnUrl);
- }
- }
- AddErrors(result);
- }
- ViewBag.ReturnUrl = returnUrl;
- return View(model);
- }
- //
- // POST: /Account/LogOff
- //[HttpPost]
- //[ValidateAntiForgeryToken]
- public ActionResult LogOff()
- {
- AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
- //System.Web.HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
- Session.Abandon();
- Session.Clear();
- return RedirectToAction("Index", "Login");
- }
- //
- // GET: /Account/ExternalLoginFailure
- [AllowAnonymous]
- public ActionResult ExternalLoginFailure()
- {
- return View();
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (_userManager != null)
- {
- _userManager.Dispose();
- _userManager = null;
- }
- if (_signInManager != null)
- {
- _signInManager.Dispose();
- _signInManager = null;
- }
- }
- base.Dispose(disposing);
- }
- #region Helpers
- // Used for XSRF protection when adding external logins
- private const string XsrfKey = "XsrfId";
- private IAuthenticationManager AuthenticationManager
- {
- get
- {
- return HttpContext.GetOwinContext().Authentication;
- }
- }
- private void AddErrors(IdentityResult result)
- {
- foreach (var error in result.Errors)
- {
- ModelState.AddModelError("", error);
- }
- }
- private ActionResult RedirectToLocal(string returnUrl)
- {
- if (Url.IsLocalUrl(returnUrl))
- {
- return Redirect(returnUrl);
- }
- if (User.IsInRole("Administrator"))
- {
- // return RedirectToAction("Index", "AdminLanding");
- return RedirectToAction("Index", "Admin");
- }
- if (User.IsInRole("User"))
- {
- return RedirectToAction("Index", "Dashboard");
- }
- else
- return RedirectToAction("Login", "Account");
- }
- internal class ChallengeResult : HttpUnauthorizedResult
- {
- public ChallengeResult(string provider, string redirectUri)
- : this(provider, redirectUri, null)
- {
- }
- public ChallengeResult(string provider, string redirectUri, string userId)
- {
- LoginProvider = provider;
- RedirectUri = redirectUri;
- UserId = userId;
- }
- public string LoginProvider { get; set; }
- public string RedirectUri { get; set; }
- public string UserId { get; set; }
- public override void ExecuteResult(ControllerContext context)
- {
- var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
- if (UserId != null)
- {
- properties.Dictionary[XsrfKey] = UserId;
- }
- context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
- }
- }
- #endregion
- // Utility
- // Add RoleManager
- #region public ApplicationRoleManager RoleManager
- private ApplicationRoleManager _roleManager;
- public ApplicationRoleManager RoleManager
- {
- get
- {
- return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>();
- }
- private set
- {
- _roleManager = value;
- }
- }
- #endregion
- // Add CreateAdminIfNeeded
- #region private void CreateAdminIfNeeded()
- private void CreateAdminIfNeeded()
- {
- // Get Admin Account
- string AdminUserName = ConfigurationManager.AppSettings["AdminUserName"];
- string AdminPassword = ConfigurationManager.AppSettings["AdminPassword"];
- // See if Admin exists
- var objAdminUser = UserManager.FindByEmail(AdminUserName);
- if (objAdminUser == null)
- {
- //See if the Admin role exists
- if (!RoleManager.RoleExists("Administrator"))
- {
- // Create the Admin Role (if needed)
- IdentityRole objAdminRole = new IdentityRole("Administrator");
- RoleManager.Create(objAdminRole);
- }
- // Create Admin user
- var objNewAdminUser = new ApplicationUser { UserName = AdminUserName, Email = AdminUserName };
- var AdminUserCreateResult = UserManager.Create(objNewAdminUser, AdminPassword);
- // Put user in Admin role
- UserManager.AddToRole(objNewAdminUser.Id, "Administrator");
- }
- }
- #endregion
- }
- public partial class Startup
- {
- // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
- public void ConfigureAuth(IAppBuilder app)
- {
- // Configure the db context, user manager and signin manager to use a single instance per request
- app.CreatePerOwinContext(ApplicationDbContext.Create);
- app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
- app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
- // Add Role Manager
- app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
- // Enable the application to use a cookie to store information for the signed in user
- // and to use a cookie to temporarily store information about a user logging in with a third party login provider
- // Configure the sign in cookie
- app.UseCookieAuthentication(new CookieAuthenticationOptions
- {
- AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
- LoginPath = new PathString("/Login"),
- Provider = new CookieAuthenticationProvider
- {
- // Enables the application to validate the security stamp when the user logs in.
- // This is a security feature which is used when you change a password or add an external login to your account.
- OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
- validateInterval: TimeSpan.FromMinutes(30),
- regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
- }
- });
- app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
- // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
- app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
- // Enables the application to remember the second login verification factor such as phone or email.
- // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
- // This is similar to the RememberMe option when you log in.
- app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
- // Uncomment the following lines to enable logging in with third party login providers
- //app.UseMicrosoftAccountAuthentication(
- // clientId: "",
- // clientSecret: "");
- //app.UseTwitterAuthentication(
- // consumerKey: "",
- // consumerSecret: "");
- //app.UseFacebookAuthentication(
- // appId: "",
- // appSecret: "");
- //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
- //{
- // ClientId = "",
- // ClientSecret = ""
- //});
- }
- }
- }
- public class EmailService : IIdentityMessageService
- {
- public Task SendAsync(IdentityMessage message)
- {
- // Plug in your email service here to send an email.
- return Task.FromResult(0);
- }
- }
- public class SmsService : IIdentityMessageService
- {
- public Task SendAsync(IdentityMessage message)
- {
- // Plug in your SMS service here to send a text message.
- return Task.FromResult(0);
- }
- }
- // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
- public class ApplicationUserManager : UserManager<ApplicationUser>
- {
- public ApplicationUserManager(IUserStore<ApplicationUser> store)
- : base(store)
- {
- }
- public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
- {
- var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
- // Configure validation logic for usernames
- manager.UserValidator = new UserValidator<ApplicationUser>(manager)
- {
- AllowOnlyAlphanumericUserNames = false,
- RequireUniqueEmail = true
- };
- // Configure validation logic for passwords
- manager.PasswordValidator = new PasswordValidator
- {
- RequiredLength = 6,
- RequireNonLetterOrDigit = true,
- RequireDigit = true,
- RequireLowercase = true,
- RequireUppercase = true,
- };
- // Configure user lockout defaults
- manager.UserLockoutEnabledByDefault = true;
- manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
- manager.MaxFailedAccessAttemptsBeforeLockout = 5;
- // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
- // You can write your own provider and plug it in here.
- manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
- {
- MessageFormat = "Your security code is {0}"
- });
- manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
- {
- Subject = "Security Code",
- BodyFormat = "Your security code is {0}"
- });
- manager.EmailService = new EmailService();
- manager.SmsService = new SmsService();
- var dataProtectionProvider = options.DataProtectionProvider;
- if (dataProtectionProvider != null)
- {
- manager.UserTokenProvider =
- new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
- }
- return manager;
- }
- }
- // Configure the application sign-in manager which is used in this application.
- public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
- {
- public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
- : base(userManager, authenticationManager)
- {
- }
- public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
- {
- return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
- }
- public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
- {
- return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
- }
- }
- // Add ApplicationRoleManager to allow the management of Roles
- public class ApplicationRoleManager : RoleManager<IdentityRole>
- {
- public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
- : base(store)
- {
- }
- public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
- {
- var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
- return new ApplicationRoleManager(roleStore);
- }
- }
Add Comment
Please, Sign In to add comment