Exemple #1
0
        /// <summary>
        /// Creates a restriction on accounts with the specified e-mail address indication that the user is not allowed to log in while their account is being reset.
        /// </summary>
        /// <param name="accounts">A list of user accounts associated with the e-mail address</param>
        /// <param name="emailAddress">The e-mail address entered from the Reset page</param>
        /// <param name="haveUsername">If the username has also been forgotten or a normal reset where the user knows their username</param>
        /// <returns></returns>
        private string CreateRestriction(IEnumerable <UserEntity> accounts, string emailAddress, bool haveUsername)
        {
            var restrictionKey = EpicMembershipProvider.CreateSalt(16);

            var accountRestriction = new AccountRestrictionEntity
            {
                AccountRestrictionType = haveUsername ? AccountRestrictionType.PasswordReset : AccountRestrictionType.LostUsername,
                RestrictionKey         = restrictionKey,
                EmailAddress           = emailAddress,
                IPAddress = Request.ServerVariables["REMOTE_ADDR"]
            };

            foreach (var account in accounts)
            {
                // If account is already restricted, don't create a new restriction.
                // It could be restricted because it's a new account or due to a prior
                // password reset.
                if (account.UserAccountRestrictions.Count == 0)
                {
                    var restriction = accountRestriction.UserAccountRestrictions.AddNew();
                    restriction.UserId = account.UserId;
                }
            }

            accountRestriction.Save(true);

            return(restrictionKey);
        }
Exemple #2
0
        private static void Initialize()
        {
            var mockUserController = Mock <UserController>();
            var request1           = mockUserController.Mock(x => x.ControllerContext.HttpContext.Request);

            request1.SetupGet(x => x.HttpMethod).Returns("POST");
            mockUserController.HttpContext.User = new RolePrincipal(new GenericIdentity(TestData.OrgAdminUsername));
            mockUserController.ControllerContext.RouteData.Values.Add("model",
                                                                      new AddUserModel
            {
                FirstName      = FIRST_NAME,
                LastName       = LAST_NAME,
                EmailAddress   = TestData.ServiceAdminSupportEmail,
                Role           = TestData.OrgAdminRoleId,
                OrganizationId = TestData.EndUserOrgId,
                Pin            = PIN
            });
            mockUserController.ControllerContext.RouteData.Values.Add("organizationId", TestData.EndUserOrgId);
            mockUserController.Invoke("Add");
            Assert.AreEqual(200, mockUserController.Response.StatusCode);

            var testUser = new LinqMetaData().User.First(u => u.FirstName == FIRST_NAME && u.LastName == LAST_NAME && u.EmailAddress == TestData.ServiceAdminSupportEmail);

            testRestriction = testUser.UserAccountRestrictions[0].AccountRestriction;
        }
        public ActionResult Add(int organizationId, AddUserModel model)
        {
            var organization = new OrganizationEntity(organizationId);

            if (organization.IsNew)
            {
                throw new HttpException(404, SharedRes.Error.NotFound_Organization);
            }

            var restrictionKey = EpicMembershipProvider.CreateSalt(16);

            if (ModelState.IsValid)
            {
                if (!Permissions.UserHasPermission("Edit", organization))
                {
                    throw new HttpException(401, SharedRes.Error.Unauthorized_OrganizationEdit);
                }

                // Validate submitted role.
                if (!model.Role.HasValue || !(OrganizationUtils.GetAllowedRoles(organizationId).Any(r => r.RoleId == model.Role)))
                {
                    throw new HttpException(417, ControllerRes.Account.Invalid_RoleSpecified);
                }

                // Locations are only valid for non-admin users.
                bool isAdmin = RoleUtils.IsRoleForAdmin(model.Role.Value);
                if (!isAdmin)
                {
                    // Validate submitted locations are locations of the organization.
                    if (model.Locations.Except(new LinqMetaData().Location.Where(l => l.OrganizationId == organizationId).Select(l => l.LocationId).ToList()).Any())
                    {
                        throw new HttpException(404, SharedRes.Error.NotFound_Location);
                    }
                }

                Transaction transaction = new Transaction(IsolationLevel.ReadCommitted, "user add");

                try
                {
                    UserEntity user = new UserEntity
                    {
                        OrganizationId = organizationId,
                        FirstName      = model.FirstName,
                        LastName       = model.LastName,
                        EmailAddress   = model.EmailAddress,
                        Username       = string.Empty,
                        Password       = string.Empty
                    };
                    transaction.Add(user);

                    // If role is non-admin, set up locations.
                    if (!isAdmin)
                    {
                        foreach (var loc in model.Locations)
                        {
                            var assignedLocation = user.UserAssignedLocations.AddNew();
                            assignedLocation.LocationId = loc;
                        }
                    }

                    var userRole = user.Roles.AddNew();
                    userRole.RoleId = model.Role.Value;

                    var accountRestriction = new AccountRestrictionEntity
                    {
                        AccountRestrictionType = AccountRestrictionType.NewUser,
                        RestrictionKey         = restrictionKey,
                        EmailAddress           = model.EmailAddress,
                        Parameters             = string.IsNullOrWhiteSpace(model.Pin) ? string.Empty : model.Pin,
                        CreatedBy = Membership.GetUser().GetUserId().Id,
                        IPAddress = Request.ServerVariables["REMOTE_ADDR"]
                    };
                    transaction.Add(accountRestriction);
                    accountRestriction.Save();

                    var userRestriction = user.UserAccountRestrictions.AddNew();
                    userRestriction.AccountRestrictionId = accountRestriction.AccountRestrictionId;

                    // Save recursively ... so assigned locations, role and restriction are saved, too.
                    user.Save(true);

                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw new HttpException(500, SharedRes.Error.Error_DatabaseUnknown);
                }
                finally
                {
                    transaction.Dispose();
                }

                // Send email for registration validation.
                SendRegistrationEmail(model, restrictionKey);

                // Add user complete. Modal dialog will close, so no response except "success".
                return(new EmptyResult());
            }

            Response.StatusCode             = 417;
            Response.TrySkipIisCustomErrors = true;

            return(PartialView(model));
        }