From: Rafał Długołęcki Date: Fri, 12 Feb 2016 04:13:26 +0000 (+0100) Subject: Custom logging X-Git-Url: https://git.dlugolecki.net.pl/?a=commitdiff_plain;ds=sidebyside;h=ebce2754ea0c114789c3f5ff6494ba390f2492ab;p=wsti_pai.git Custom logging --- diff --git a/Projects/App_Start/IdentityConfig.cs b/Projects/App_Start/IdentityConfig.cs index fbbdf74..ac244c6 100644 --- a/Projects/App_Start/IdentityConfig.cs +++ b/Projects/App_Start/IdentityConfig.cs @@ -11,99 +11,8 @@ using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security; using Projects.Models; +using System.Web.Security; namespace Projects { - 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 - { - public ApplicationUserManager(IUserStore store) - : base(store) - { - } - - public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) - { - var manager = new ApplicationUserManager(new UserStore(context.Get())); - // Configure validation logic for usernames - manager.UserValidator = new UserValidator(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 - { - MessageFormat = "Your security code is {0}" - }); - manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider - { - 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(dataProtectionProvider.Create("ASP.NET Identity")); - } - return manager; - } - } - - // Configure the application sign-in manager which is used in this application. - public class ApplicationSignInManager : SignInManager - { - public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) - : base(userManager, authenticationManager) - { - } - - public override Task CreateUserIdentityAsync(ApplicationUser user) - { - return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager); - } - - public static ApplicationSignInManager Create(IdentityFactoryOptions options, IOwinContext context) - { - return new ApplicationSignInManager(context.GetUserManager(), context.Authentication); - } - } } diff --git a/Projects/App_Start/Startup.Auth.cs b/Projects/App_Start/Startup.Auth.cs index 94dc828..d584b89 100644 --- a/Projects/App_Start/Startup.Auth.cs +++ b/Projects/App_Start/Startup.Auth.cs @@ -11,58 +11,5 @@ namespace Projects { 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.Create); - app.CreatePerOwinContext(ApplicationSignInManager.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("/Account/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( - 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 = "" - //}); - } } } \ No newline at end of file diff --git a/Projects/Controllers/AccountController.cs b/Projects/Controllers/AccountController.cs deleted file mode 100644 index 3c9683d..0000000 --- a/Projects/Controllers/AccountController.cs +++ /dev/null @@ -1,485 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using System.Web; -using System.Web.Mvc; -using Microsoft.AspNet.Identity; -using Microsoft.AspNet.Identity.Owin; -using Microsoft.Owin.Security; -using Projects.Models; - -namespace Projects.Controllers -{ - [Authorize] - 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(); - } - private set - { - _signInManager = value; - } - } - - public ApplicationUserManager UserManager - { - get - { - return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); - } - private set - { - _userManager = value; - } - } - - // - // GET: /Account/Login - [AllowAnonymous] - public ActionResult Login(string returnUrl) - { - ViewBag.ReturnUrl = returnUrl; - return View(); - } - - // - // POST: /Account/Login - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task Login(LoginViewModel model, string returnUrl) - { - if (!ModelState.IsValid) - { - return View(model); - } - - // 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: - default: - ModelState.AddModelError("", "Invalid login attempt."); - return View(model); - } - } - - // - // GET: /Account/VerifyCode - [AllowAnonymous] - public async Task 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 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 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 here"); - - 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 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 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 here"); - // 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 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 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 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 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 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); - return RedirectToAction("Index", "Home"); - } - - // - // 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); - } - return RedirectToAction("Index", "Home"); - } - - 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 - } -} \ No newline at end of file diff --git a/Projects/Controllers/LoginController.cs b/Projects/Controllers/LoginController.cs new file mode 100644 index 0000000..7ab9547 --- /dev/null +++ b/Projects/Controllers/LoginController.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using Projects.Models; +using System.Web.Security; + +namespace Projects.Controllers +{ + public class LoginController : Controller + { + // GET: Login + public ActionResult Login() + { + return View(); + } + + [HttpPost] + public ActionResult Login(User model, string returnUrl) + { + if (ModelState.IsValid) + { + using (ProjectsDBEntities entities = new ProjectsDBEntities()) + { + string username = model.login; + string password = model.password; + + bool userValid = entities.Users.Any(user => user.login == username && user.password == password); + + if (userValid) + { + + FormsAuthentication.SetAuthCookie(username, false); + if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") + && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) + { + return Redirect(returnUrl); + } + else + { + return RedirectToAction("Index", "Home"); + } + } + else + { + ModelState.AddModelError("", "The user name or password provided is incorrect."); + } + } + } + + // If we got this far, something failed, redisplay form + return View(model); + } + + public ActionResult Logout() + { + FormsAuthentication.SignOut(); + + return RedirectToAction("Index", "Home"); + } + } +} \ No newline at end of file diff --git a/Projects/Controllers/ManageController.cs b/Projects/Controllers/ManageController.cs deleted file mode 100644 index bfdcf30..0000000 --- a/Projects/Controllers/ManageController.cs +++ /dev/null @@ -1,387 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using System.Web; -using System.Web.Mvc; -using Microsoft.AspNet.Identity; -using Microsoft.AspNet.Identity.Owin; -using Microsoft.Owin.Security; -using Projects.Models; - -namespace Projects.Controllers -{ - [Authorize] - public class ManageController : Controller - { - private ApplicationSignInManager _signInManager; - private ApplicationUserManager _userManager; - - public ManageController() - { - } - - public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) - { - UserManager = userManager; - SignInManager = signInManager; - } - - public ApplicationSignInManager SignInManager - { - get - { - return _signInManager ?? HttpContext.GetOwinContext().Get(); - } - private set - { - _signInManager = value; - } - } - - public ApplicationUserManager UserManager - { - get - { - return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); - } - private set - { - _userManager = value; - } - } - - // - // GET: /Manage/Index - public async Task Index(ManageMessageId? message) - { - ViewBag.StatusMessage = - message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." - : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." - : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." - : message == ManageMessageId.Error ? "An error has occurred." - : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." - : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." - : ""; - - var userId = User.Identity.GetUserId(); - var model = new IndexViewModel - { - HasPassword = HasPassword(), - PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), - TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), - Logins = await UserManager.GetLoginsAsync(userId), - BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) - }; - return View(model); - } - - // - // POST: /Manage/RemoveLogin - [HttpPost] - [ValidateAntiForgeryToken] - public async Task RemoveLogin(string loginProvider, string providerKey) - { - ManageMessageId? message; - var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - message = ManageMessageId.RemoveLoginSuccess; - } - else - { - message = ManageMessageId.Error; - } - return RedirectToAction("ManageLogins", new { Message = message }); - } - - // - // GET: /Manage/AddPhoneNumber - public ActionResult AddPhoneNumber() - { - return View(); - } - - // - // POST: /Manage/AddPhoneNumber - [HttpPost] - [ValidateAntiForgeryToken] - public async Task AddPhoneNumber(AddPhoneNumberViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - // Generate the token and send it - var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number); - if (UserManager.SmsService != null) - { - var message = new IdentityMessage - { - Destination = model.Number, - Body = "Your security code is: " + code - }; - await UserManager.SmsService.SendAsync(message); - } - return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); - } - - // - // POST: /Manage/EnableTwoFactorAuthentication - [HttpPost] - [ValidateAntiForgeryToken] - public async Task EnableTwoFactorAuthentication() - { - await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true); - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", "Manage"); - } - - // - // POST: /Manage/DisableTwoFactorAuthentication - [HttpPost] - [ValidateAntiForgeryToken] - public async Task DisableTwoFactorAuthentication() - { - await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false); - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", "Manage"); - } - - // - // GET: /Manage/VerifyPhoneNumber - public async Task VerifyPhoneNumber(string phoneNumber) - { - var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber); - // Send an SMS through the SMS provider to verify the phone number - return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); - } - - // - // POST: /Manage/VerifyPhoneNumber - [HttpPost] - [ValidateAntiForgeryToken] - public async Task VerifyPhoneNumber(VerifyPhoneNumberViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); - } - // If we got this far, something failed, redisplay form - ModelState.AddModelError("", "Failed to verify phone"); - return View(model); - } - - // - // GET: /Manage/RemovePhoneNumber - public async Task RemovePhoneNumber() - { - var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null); - if (!result.Succeeded) - { - return RedirectToAction("Index", new { Message = ManageMessageId.Error }); - } - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess }); - } - - // - // GET: /Manage/ChangePassword - public ActionResult ChangePassword() - { - return View(); - } - - // - // POST: /Manage/ChangePassword - [HttpPost] - [ValidateAntiForgeryToken] - public async Task ChangePassword(ChangePasswordViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); - } - AddErrors(result); - return View(model); - } - - // - // GET: /Manage/SetPassword - public ActionResult SetPassword() - { - return View(); - } - - // - // POST: /Manage/SetPassword - [HttpPost] - [ValidateAntiForgeryToken] - public async Task SetPassword(SetPasswordViewModel model) - { - if (ModelState.IsValid) - { - var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); - } - AddErrors(result); - } - - // If we got this far, something failed, redisplay form - return View(model); - } - - // - // GET: /Manage/ManageLogins - public async Task ManageLogins(ManageMessageId? message) - { - ViewBag.StatusMessage = - message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." - : message == ManageMessageId.Error ? "An error has occurred." - : ""; - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user == null) - { - return View("Error"); - } - var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()); - var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); - ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; - return View(new ManageLoginsViewModel - { - CurrentLogins = userLogins, - OtherLogins = otherLogins - }); - } - - // - // POST: /Manage/LinkLogin - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult LinkLogin(string provider) - { - // Request a redirect to the external login provider to link a login for the current user - return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); - } - - // - // GET: /Manage/LinkLoginCallback - public async Task LinkLoginCallback() - { - var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); - if (loginInfo == null) - { - return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); - } - var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); - return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); - } - - protected override void Dispose(bool disposing) - { - if (disposing && _userManager != null) - { - _userManager.Dispose(); - _userManager = 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 bool HasPassword() - { - var user = UserManager.FindById(User.Identity.GetUserId()); - if (user != null) - { - return user.PasswordHash != null; - } - return false; - } - - private bool HasPhoneNumber() - { - var user = UserManager.FindById(User.Identity.GetUserId()); - if (user != null) - { - return user.PhoneNumber != null; - } - return false; - } - - public enum ManageMessageId - { - AddPhoneSuccess, - ChangePasswordSuccess, - SetTwoFactorSuccess, - SetPasswordSuccess, - RemoveLoginSuccess, - RemovePhoneSuccess, - Error - } - -#endregion - } -} \ No newline at end of file diff --git a/Projects/Controllers/ProjectTasksController.cs b/Projects/Controllers/ProjectTasksController.cs index 81cb093..e28a4e5 100644 --- a/Projects/Controllers/ProjectTasksController.cs +++ b/Projects/Controllers/ProjectTasksController.cs @@ -37,6 +37,7 @@ namespace Projects.Controllers } // GET: ProjectTasks/Create + [Authorize] public ActionResult Create() { ViewBag.project_id = new SelectList(db.Projects, "id", "name"); @@ -48,6 +49,7 @@ namespace Projects.Controllers // POST: ProjectTasks/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. + [Authorize] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "id,project_id,name,description,created_at,updated_at,task_status_id,user_id")] ProjectTask projectTask) @@ -68,6 +70,7 @@ namespace Projects.Controllers } // GET: ProjectTasks/Edit/5 + [Authorize] public ActionResult Edit(int? id) { if (id == null) @@ -88,6 +91,7 @@ namespace Projects.Controllers // POST: ProjectTasks/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. + [Authorize] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "id,project_id,name,description,task_status_id,user_id,created_at")] ProjectTask projectTask) @@ -106,6 +110,7 @@ namespace Projects.Controllers } // GET: ProjectTasks/Delete/5 + [Authorize(Roles = "admin")] public ActionResult Delete(int? id) { if (id == null) @@ -121,6 +126,7 @@ namespace Projects.Controllers } // POST: ProjectTasks/Delete/5 + [Authorize(Roles = "admin")] [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) diff --git a/Projects/Controllers/ProjectsController.cs b/Projects/Controllers/ProjectsController.cs index b6f57e6..ab93cc8 100644 --- a/Projects/Controllers/ProjectsController.cs +++ b/Projects/Controllers/ProjectsController.cs @@ -36,6 +36,7 @@ namespace Projects.Models } // GET: Projects/Create + [Authorize(Roles = "admin")] public ActionResult Create() { ViewBag.user_id = new SelectList(db.Users, "id", "login"); @@ -45,6 +46,7 @@ namespace Projects.Models // POST: Projects/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. + [Authorize(Roles = "admin")] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "id,user_id,name,description")] Project project) @@ -63,6 +65,7 @@ namespace Projects.Models } // GET: Projects/Edit/5 + [Authorize(Roles = "admin")] public ActionResult Edit(int? id) { if (id == null) @@ -81,6 +84,7 @@ namespace Projects.Models // POST: Projects/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. + [Authorize(Roles = "admin")] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "id,user_id,name,description,created_at")] Project project) @@ -97,6 +101,7 @@ namespace Projects.Models } // GET: Projects/Delete/5 + [Authorize(Roles = "admin")] public ActionResult Delete(int? id) { if (id == null) @@ -112,6 +117,7 @@ namespace Projects.Models } // POST: Projects/Delete/5 + [Authorize(Roles = "admin")] [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) diff --git a/Projects/Global.asax.cs b/Projects/Global.asax.cs index c0cafe1..61f3d92 100644 --- a/Projects/Global.asax.cs +++ b/Projects/Global.asax.cs @@ -1,10 +1,12 @@ -using System; +using Projects.Models; +using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; +using System.Web.Security; namespace Projects { @@ -17,5 +19,38 @@ namespace Projects RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } + + protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) + { + if (FormsAuthentication.CookiesSupported == true) + { + if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) + { + try + { + //let us take out the username now + string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; + string roles = string.Empty; + + using (ProjectsDBEntities entities = new ProjectsDBEntities()) + { + User user = entities.Users.SingleOrDefault(u => u.login == username); + + roles = user.UserRole.role.Trim(); + } + //let us extract the roles from our own custom cookie + + + //Let us set the Pricipal with our user specific details + HttpContext.Current.User = new System.Security.Principal.GenericPrincipal( + new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';')); + } + catch (Exception) + { + //somehting went wrong + } + } + } + } } } diff --git a/Projects/Projects.csproj b/Projects/Projects.csproj index 9efa3cf..cc369fb 100644 --- a/Projects/Projects.csproj +++ b/Projects/Projects.csproj @@ -197,11 +197,10 @@ - - + Global.asax @@ -334,6 +333,7 @@ + diff --git a/Projects/Startup.cs b/Projects/Startup.cs index 4d55fac..6b6568d 100644 --- a/Projects/Startup.cs +++ b/Projects/Startup.cs @@ -8,7 +8,6 @@ namespace Projects { public void Configuration(IAppBuilder app) { - ConfigureAuth(app); } } } diff --git a/Projects/Views/Shared/_LoginPartial.cshtml b/Projects/Views/Shared/_LoginPartial.cshtml index f996508..9612c5e 100644 --- a/Projects/Views/Shared/_LoginPartial.cshtml +++ b/Projects/Views/Shared/_LoginPartial.cshtml @@ -1,22 +1,13 @@ @using Microsoft.AspNet.Identity @if (Request.IsAuthenticated) { - using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) - { - @Html.AntiForgeryToken() - - } } else { } diff --git a/Projects/Web.config b/Projects/Web.config index 7c97ace..06973af 100644 --- a/Projects/Web.config +++ b/Projects/Web.config @@ -18,7 +18,9 @@ - + + + @@ -27,7 +29,7 @@ - +