Exemplo n.º 1
0
        public IActionResult ChangePassword(ChangePasswordViewModel view)
        {
            ApplicationUserRepository     userRepo = null;
            ApplicationAuditLogRepository logRepo  = null;
            ApplicationUser user = null;

            try
            {
                if (ModelState.IsValid)
                {
                    if (view.OldPassword != view.NewPassword)
                    {
                        userRepo = new ApplicationUserRepository(settings, logger, dbc);
                        logRepo  = new ApplicationAuditLogRepository(settings, logger, dbc);

                        // Find user in database and validate there password
                        user = (userRepo.FindAll()).FirstOrDefault(u => u.NormalizedUserName == view.UserName.ToUpper());
                        if (PasswordHash.ValidateHashedPassword(user.PasswordHash, view.OldPassword))
                        {
                            user.PasswordHash = PasswordHash.HashPassword(view.NewPassword);
                            userRepo.Update(user);
                            logRepo.Add(new ApplicationAuditLog()
                            {
                                CategoryId = 1, Description = $"Changed password for User ({HttpContext.User.Identity.Name})."
                            });

                            return(RedirectToAction("PasswordChangeSuccess", "Account"));
                        }
                        else
                        {
                            // Old Password wrong
                            logRepo.Add(new ApplicationAuditLog()
                            {
                                CategoryId = 1, Description = $"Old password didn't match for User ({HttpContext.User.Identity.Name}) while changing password."
                            });
                            ModelState.AddModelError("OldPassword", "Password doesn't match our records.");
                            return(View("ChangePassword", view));
                        }
                    }
                    else
                    {
                        // Passwords matched
                        ModelState.AddModelError("NewPassword", "New Password is the same as the Old Password.");
                        return(View("ChangePassword", view));
                    }
                }
                else
                {
                    return(View("ChangePassword", view));
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"Exception: {ex.Message}");
                throw (Exception)Activator.CreateInstance(ex.GetType(), ex.Message + ex.StackTrace);
            }
        }
Exemplo n.º 2
0
        public IActionResult ResetPassword()
        {
            ResetPasswordViewModel    view = new ResetPasswordViewModel();
            ApplicationUserRepository applicationUserRepository;

            applicationUserRepository = new ApplicationUserRepository(settings, logger, dbc);
            view.Users = applicationUserRepository.FindAll().Where(u => u.NormalizedUserName != "ADMIN" && u.NormalizedUserName != "ADMINISTRATOR").ToList();

            return(View("ResetPassword", view));
        }
Exemplo n.º 3
0
        public IActionResult ResetPassword(ResetPasswordViewModel view)
        {
            ApplicationUserRepository     userRepo = null;
            ApplicationAuditLogRepository logRepo  = null;
            ApplicationUser user = null;

            try
            {
                if (ModelState.IsValid)
                {
                    if (view.Password == view.ConfirmPassword)
                    {
                        if (view.UserName.ToUpper() != "ADMIN" && view.UserName.ToUpper() != "ADMINISTRATOR")
                        {
                            userRepo = new ApplicationUserRepository(settings, logger, dbc);
                            logRepo  = new ApplicationAuditLogRepository(settings, logger, dbc);
                            // Find user in database and validate there password
                            user = (userRepo.FindAll()).FirstOrDefault(u => u.NormalizedUserName == view.UserName.ToUpper());
                            user.PasswordHash = PasswordHash.HashPassword(view.Password);
                            userRepo.Update(user);
                            logRepo.Add(new ApplicationAuditLog()
                            {
                                CategoryId = 1, Description = $"Reset password for User ({HttpContext.User.Identity.Name})."
                            });
                            return(RedirectToAction("PasswordResetSuccess", "Account"));
                        }
                        else
                        {
                            // Can't reset Admin password
                            ModelState.AddModelError("UserName", "You can't reset the Admin users password!");
                            return(View("ResetPassword", view));
                        }
                    }
                    else
                    {
                        // Passwords don't match
                        ModelState.AddModelError("ConfirmPassword", "Confirm Password doesn't match New Password.");
                        return(View("ResetPassword", view));
                    }
                }
                else
                {
                    return(View("ResetPassword", view));
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"Exception: {ex.Message}");
                throw (Exception)Activator.CreateInstance(ex.GetType(), ex.Message + ex.StackTrace);
            }
        }
Exemplo n.º 4
0
        public IActionResult Index()
        {
            ApplicationUserRepository userRepo;
            IPager <ApplicationUser>  pager = null;

            try
            {
                userRepo = new ApplicationUserRepository(settings, logger, dbc);

                pager = userRepo.FindAll(new Pager <ApplicationUser>()
                {
                    PageNbr = 0, PageSize = 20
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
            }

            return(View(pager));
        }
Exemplo n.º 5
0
        public async Task <ActionResult> Register(RegisterViewModel register, string ReturnUrl = null)
        {
            ApplicationUserRepository      userRepo;
            ApplicationUserClaimRepository userClaimRepo;
            ApplicationUser user;
            //ApplicationUserClaim userClaim;
            //AuthenticationProperties props = null;
            const string issuer = "Local Authority";
            int          id     = 0;

            if (ModelState.IsValid)
            {
                try
                {
                    userRepo      = new ApplicationUserRepository(settings, logger, dbc);
                    userClaimRepo = new ApplicationUserClaimRepository(settings, logger, dbc);
                    user          = userRepo.FindAll().FirstOrDefault(u => u.NormalizedUserName == register.UserName.ToUpper());

                    if (user == null)
                    {
                        user = new ApplicationUser()
                        {
                            UserName           = register.UserName,
                            NormalizedUserName = register.UserName.ToUpper(),
                            Email                = register.Email,
                            NormalizedEmail      = register.Email.ToUpper(),
                            EmailConfirmed       = true,
                            PhoneNumber          = String.Empty,
                            PhoneNumberConfirmed = false,
                            TwoFactorEnabled     = false,
                            DOB        = DateTime.Now,
                            Department = String.Empty,
                            Active     = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now,
                            Claims     = new List <ApplicationUserClaim>()
                        };

                        // NOTE: This should be wrapped in a Unit of Work
                        // Add User to the database
                        user.PasswordHash = PasswordHash.HashPassword(register.Password);
                        id = (int)userRepo.Add(user);
                        logger.LogInformation($"Created new user account: {register.UserName}");

                        // Add default User Claims
                        user.Claims.Add(new ApplicationUserClaim()
                        {
                            UserId    = id,
                            ClaimType = ClaimTypes.Name, ClaimValue = user.UserName, ClaimIssuer = issuer,
                            Active    = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now
                        });
                        user.Claims.Add(new ApplicationUserClaim()
                        {
                            UserId    = id,
                            ClaimType = ClaimTypes.NameIdentifier, ClaimValue = id.ToString(), ClaimIssuer = issuer,
                            Active    = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now
                        });
                        user.Claims.Add(new ApplicationUserClaim()
                        {
                            UserId    = id,
                            ClaimType = ClaimTypes.Role, ClaimValue = "Basic", ClaimIssuer = issuer,
                            Active    = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now
                        });
                        user.Claims.Add(new ApplicationUserClaim()
                        {
                            UserId    = id,
                            ClaimType = ClaimTypes.DateOfBirth, ClaimValue = user.DOB.ToString("yyyy-MM-dd hh:mm:ss"), ClaimIssuer = issuer,
                            Active    = true, ModifiedDt = DateTime.Now, CreateDt = DateTime.Now
                        });

                        // Add User Claims to the database
                        foreach (ApplicationUserClaim c in user.Claims)
                        {
                            userClaimRepo.Add(c);
                        }

                        logger.LogInformation($"Assigned default claims to new user account: {register.UserName}");

                        // Sign in the user
                        await identityManager.SignInAsync(user);

                        logger.LogInformation($"Logged in user: {user.UserName} at IP address: {HttpContext.Connection.RemoteIpAddress}");

                        if (ReturnUrl == null)
                        {
                            return(LocalRedirect("/Home/LoginSuccess"));
                        }
                        else
                        {
                            return(LocalRedirect($"{ReturnUrl}"));
                        }
                    }
                    else
                    {
                        logger.LogError($"User is already registered: {register.UserName}");
                        return(LocalRedirect("/Account/UserAlreadyRegistered"));
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError($"Exception registering user({register.UserName}): {ex.Message}");
                    return(RedirectToAction("Error"));
                }
            }

            return(RedirectToAction("Error"));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Login(LoginViewModel login, string ReturnUrl = null)
        {
            ApplicationUserRepository      userRepo      = null;
            ApplicationUserClaimRepository userClaimRepo = null;
            ApplicationAuditLogRepository  logRepo       = null;
            ApplicationUser user = null;

            try
            {
                if (ModelState.IsValid)
                {
                    userRepo      = new ApplicationUserRepository(settings, logger, dbc);
                    userClaimRepo = new ApplicationUserClaimRepository(settings, logger, dbc);
                    logRepo       = new ApplicationAuditLogRepository(settings, logger, dbc);

                    // Find user in database and validate there password
                    user = (userRepo.FindAll()).FirstOrDefault(u => u.NormalizedUserName == login.UserName.ToUpper());
                    if (user != null)
                    {
                        //valid = PasswordHash.ValidateHashedPassword(user.PasswordHash, login.Password);

                        // Add user claims from the database
                        user.Claims = new List <ApplicationUserClaim>();
                        foreach (ApplicationUserClaim c in userClaimRepo.FindAll().Where(c => c.UserId == user.Id))
                        {
                            user.Claims.Add(c);
                        }

                        // Sign in the user, if there password is correct
                        if (await identityManager.SignInWithPasswordAsync(user, login.Password))
                        {
                            logRepo.Add(new ApplicationAuditLog()
                            {
                                CategoryId = 1, Description = $"User ({user.UserName}) logged into application at IP address: {HttpContext.Connection.RemoteIpAddress}.", UserName = user.UserName
                            });
                            logger.LogInformation($"Logged in user: {login.UserName} at IP address: {HttpContext.Connection.RemoteIpAddress}");
                            if (ReturnUrl == null)
                            {
                                return(LocalRedirect("/Home/LoginSuccess"));
                            }
                            else
                            {
                                return(LocalRedirect($"{ReturnUrl}"));
                            }
                        }
                        else
                        {
                            logger.LogError($"Invalid user name / password combination: {login.UserName} at IP address {HttpContext.Connection.RemoteIpAddress}");
                            logRepo.Add(new ApplicationAuditLog()
                            {
                                CategoryId = 1, Description = $"Invalid user name / password combination for User ({user.UserName}) at IP address {HttpContext.Connection.RemoteIpAddress}.", UserName = user.UserName
                            });
                            return(LocalRedirect("/Home/InvalidCredentials"));
                        }
                    }
                    else
                    {
                        logger.LogError($"Invalid user name / password combination: {login.UserName} at IP address: {HttpContext.Connection.RemoteIpAddress}");
                        return(LocalRedirect("/Home/InvalidCredentials"));
                    }
                }
                else
                {
                    logger.LogError("Invalid ModelState: AccountController.Login()");
                    return(View($"LoginRegister?action=login?ReturnUrl={ReturnUrl}"));
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"Exception: {ex.Message}");
            }

            return(RedirectToAction("Error"));
        }