/// <summary>
        /// Updates an Agent's name in it's corresponding user tables
        /// </summary>
        /// <param name="oldName"></param>
        /// <param name="newName"></param>
        public void UpdateAgentName(string oldName, string newName)
        {
            _personRepo.ForceIgnoreSecurity();
            Person person = _personRepo.Find(0, 1).Items?.Where(p => p.Name == oldName && p.IsAgent && p.IsDeleted == false)?.FirstOrDefault();

            if (person != null)
            {
                person.Name = newName;
                _personRepo.Update(person);

                _usersRepo.ForceIgnoreSecurity();
                var aspUser = _usersRepo.Find(0, 1).Items?.Where(u => u.PersonId == person.Id)?.FirstOrDefault();
                if (aspUser != null)
                {
                    var existingUser = _userManager.FindByIdAsync(aspUser.Id).Result;
                    existingUser.Name = newName;
                    var result = _userManager.UpdateAsync(existingUser).Result;
                }
                else
                {
                    throw new EntityDoesNotExistException("Could not find the corresponding asp user entity to update");
                }
                _usersRepo.ForceSecurity();
            }
            else
            {
                throw new EntityDoesNotExistException("Could not find the corresponding person entity to update");
            }
        }
        public async Task <IActionResult> UpdateOrganizationMember(UpdateTeamMemberViewModel request, string personId, string organizationId)
        {
            var currentUser = await _userManager.FindByEmailAsync(_accessor.HttpContext.User.Identity.Name);

            OrganizationMember currentOrgMember = _organzationMemberRepo.Find(null, o => o.PersonId == Guid.Parse(personId)).Items?.FirstOrDefault();

            if (!currentOrgMember.IsAdministrator ?? false || currentOrgMember.OrganizationId != Guid.Parse(organizationId))
            {
                throw new UnauthorizedOperationException("Only admins of this organization can update existing users", EntityOperationType.Update);
            }

            var             userToUpdate   = _aspNetUsersRepository.Find(null, u => u.PersonId == Guid.Parse(personId)).Items?.FirstOrDefault();
            var             personToUpdate = _personRepo.Find(null, p => p.Id == Guid.Parse(personId)).Items?.FirstOrDefault();
            ApplicationUser appUser        = await _userManager.FindByIdAsync(userToUpdate.Id).ConfigureAwait(false);

            //check password's validity if one was provided
            if (!string.IsNullOrEmpty(request.Password))
            {
                if (!IsPasswordValid(request.Password))
                {
                    throw new Exception(PasswordRequirementMessage(request.Password));
                }
            }

            //if email was provided check its availability
            if (!string.IsNullOrEmpty(request.Email))
            {
                //if email is not the same as user's current email
                if (!appUser.NormalizedEmail.Equals(request.Email.ToUpper()))
                {
                    var existingEmailUser = _aspNetUsersRepository.Find(null, u => u.Email == request.Email).Items?.FirstOrDefault();

                    if (existingEmailUser != null)
                    {
                        throw new Exception("A user already exists for the provided email address");
                    }

                    var personEmailToUpdate       = _personEmailRepository.Find(null, p => p.PersonId == Guid.Parse(personId)).Items?.FirstOrDefault();
                    var emailVerificationToUpdate = _emailVerificationRepository.Find(null, p => p.PersonId == Guid.Parse(personId)).Items?.FirstOrDefault();

                    //update application user's email
                    appUser.Email              = request.Email;
                    appUser.NormalizedEmail    = request.Email.ToUpper();
                    appUser.UserName           = request.Email;
                    appUser.NormalizedUserName = request.Email.ToUpper();

                    //update additional email tables
                    personEmailToUpdate.Address       = request.Email;
                    emailVerificationToUpdate.Address = request.Email;

                    _personEmailRepository.Update(personEmailToUpdate);
                    _emailVerificationRepository.Update(emailVerificationToUpdate);
                }
            }

            //update name if one was provided
            if (!string.IsNullOrEmpty(request.Name))
            {
                appUser.Name        = request.Name;
                personToUpdate.Name = request.Name;

                _personRepo.Update(personToUpdate);
            }

            //update password
            if (!string.IsNullOrEmpty(request.Password))
            {
                appUser.ForcedPasswordChange = false;
                var token = await _userManager.GeneratePasswordResetTokenAsync(appUser);

                IdentityResult result = await _userManager.ResetPasswordAsync(appUser, token, request.Password);

                if (!result.Succeeded)
                {
                    throw new Exception("Failed to set new password");
                }
            }

            //update application user
            if (!string.IsNullOrEmpty(request.Password) || !string.IsNullOrEmpty(request.Email))
            {
                _userManager.UpdateAsync(appUser);
            }

            return(new OkObjectResult(appUser));
        }
예제 #3
0
        public async Task <IActionResult> Register(SignUpViewModel signupModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            EmailVerification emailAddress = emailVerificationRepository.Find(null, p => p.Address.Equals(signupModel.Email, StringComparison.OrdinalIgnoreCase)).Items?.FirstOrDefault();

            if (emailAddress != null)
            {
                organizationMemberRepository.ForceIgnoreSecurity();
                var member = organizationMemberRepository.Find(null, m => m.PersonId == emailAddress.PersonId)?.Items?.FirstOrDefault();
                organizationMemberRepository.ForceSecurity();

                if (member != null)
                {
                    //Already a member of the organization
                    ModelState.AddModelError("Register", "Email address already exists");
                    return(BadRequest(ModelState));
                }
                // Make a request to join organization
                var oldOrganization = organizationManager.GetDefaultOrganization();
                if (oldOrganization != null)
                {
                    //Update user
                    if (!IsPasswordValid(signupModel.Password))
                    {
                        ModelState.AddModelError("Password", PasswordRequirementMessage(signupModel.Password));
                        return(BadRequest(ModelState));
                    }
                    var existingUser = await userManager.FindByEmailAsync(emailAddress.Address).ConfigureAwait(false);

                    existingUser.Name = signupModel.Name;
                    existingUser.ForcedPasswordChange = false;
                    existingUser.PasswordHash         = userManager.PasswordHasher.HashPassword(existingUser, signupModel.Password);

                    var result = await userManager.UpdateAsync(existingUser).ConfigureAwait(true);

                    if (!result.Succeeded)
                    {
                        return(GetErrorResult(result));
                    }

                    Person person = personRepository.Find(null, p => p.Id == emailAddress.PersonId)?.Items?.FirstOrDefault();
                    person.Name       = signupModel.Name;
                    person.Department = signupModel.Department;
                    personRepository.Update(person);

                    //Create a new access request
                    Model.Membership.AccessRequest accessRequest = new Model.Membership.AccessRequest()
                    {
                        OrganizationId    = oldOrganization.Id,
                        PersonId          = person.Id,
                        IsAccessRequested = true,
                        AccessRequestedOn = DateTime.UtcNow
                    };

                    accessRequestManager.AddAnonymousAccessRequest(accessRequest);
                    return(Ok("Access Request has been created for existing user"));
                }
            }

            var user = new ApplicationUser()
            {
                Name                 = signupModel.Name,
                UserName             = signupModel.Email,
                Email                = signupModel.Email,
                ForcedPasswordChange = false //Set this property to not show password reset secreen for new user
            };

            RandomPassword randomPass         = new RandomPassword();
            string         passwordString     = "";
            bool           isPasswordProvided = false;

            if (string.IsNullOrWhiteSpace(signupModel.Password))
            {
                passwordString     = randomPass.GenerateRandomPassword();
                isPasswordProvided = false;
            }
            else
            {
                passwordString     = signupModel.Password;
                isPasswordProvided = true;
            }

            var loginResult = await userManager.CreateAsync(user, passwordString).ConfigureAwait(false);

            bool IsEmailAllowed = emailSender.IsEmailAllowed();

            if (!loginResult.Succeeded)
            {
                return(GetErrorResult(loginResult));
            }
            else
            {
                //Add person email
                var emailIds    = new List <EmailVerification>();
                var personEmail = new EmailVerification()
                {
                    PersonId   = Guid.Empty,
                    Address    = signupModel.Email,
                    IsVerified = false
                };
                emailIds.Add(personEmail);

                Person newPerson = new Person()
                {
                    Company            = signupModel.Organization,
                    Department         = signupModel.Department,
                    Name               = signupModel.Name,
                    EmailVerifications = emailIds
                };
                var person = personRepository.Add(newPerson);

                var oldOrganization = organizationManager.GetDefaultOrganization();
                if (oldOrganization != null)
                {
                    //Add it to access requests
                    Model.Membership.AccessRequest accessRequest = new Model.Membership.AccessRequest()
                    {
                        OrganizationId    = oldOrganization.Id,
                        PersonId          = person.Id,
                        IsAccessRequested = true,
                        AccessRequestedOn = DateTime.UtcNow
                    };

                    accessRequestManager.AddAnonymousAccessRequest(accessRequest);
                }

                if (IsEmailAllowed)
                {
                    string code = await userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false);

                    EmailMessage emailMessage = new EmailMessage();
                    EmailAddress address      = new EmailAddress(user.Name, user.Email);
                    emailMessage.To.Add(address);
                    emailMessage.Body    = SendConfirmationEmail(code, user.Id, passwordString, "en");
                    emailMessage.Subject = "Confirm your account at " + Constants.PRODUCT;
                    await emailSender.SendEmailAsync(emailMessage).ConfigureAwait(false);
                }
                else
                {
                    ModelState.AddModelError("Email", "Email is disabled.  Verification email was not sent.");
                }

                //Update the user
                if (person != null)
                {
                    var registeredUser = userManager.FindByNameAsync(user.UserName).Result;
                    registeredUser.PersonId             = (Guid)person.Id;
                    registeredUser.ForcedPasswordChange = true;
                    await userManager.UpdateAsync(registeredUser).ConfigureAwait(false);
                }
            }
            if (!IsEmailAllowed)
            {
                return(Ok(ModelState));
            }
            else
            {
                return(Ok());
            }
        }
예제 #4
0
        public async Task <IActionResult> InviteUser(string organizationId, [FromBody] InviteUserViewModel value)
        {
            OrganizationMember teamMember;

            value.OrganizationId = new Guid(organizationId);
            var user = new ApplicationUser();

            //add person to organization only if you are admin or add it to access request table
            var requestingUser = repository.Find(null, a => a.PersonId == SecurityContext.PersonId && a.OrganizationId == Guid.Parse(organizationId))?.Items.FirstOrDefault();
            var isRequestingUserAdministrator = requestingUser.IsAdministrator.GetValueOrDefault(false);

            //if the requesting user is NOT an administrator then the user cannot skip email verification
            //only administrators can allow that; however, this can be skipped for now
            //if (value.SkipEmailVerification && !isRequestingUserAdministrator)
            //    value.SkipEmailVerification = false;

            try
            {
                bool IsEmailAllowed = _emailSender.IsEmailAllowed();

                var organizationMember = repository.Find(null, a => a.PersonId == SecurityContext.PersonId && a.OrganizationId == Guid.Parse(organizationId))?.Items.FirstOrDefault();
                if (organizationMember == null)
                {
                    throw new UnauthorizedAccessException();
                }

                //this is to check if the user is already in the system and where is part of the organization
                teamMember = _membershipManager.InviteUser(value, SecurityContext);
                if (teamMember == null)
                {
                    user.UserName = value.Email;
                    user.Email    = value.Email;
                    string passwordString = value.Password;

                    if (IsEmailAllowed)
                    {
                        if (string.IsNullOrEmpty(passwordString))
                        {
                            RandomPassword randomPass = new RandomPassword();
                            passwordString = randomPass.GenerateRandomPassword();
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(passwordString))
                        {
                            ModelState.AddModelError("Invite User", "Email is disabled.  Must provide a password.");
                            return(BadRequest(ModelState));
                        }
                    }

                    var loginResult = await _userManager.CreateAsync(user, passwordString).ConfigureAwait(false);

                    if (!loginResult.Succeeded)
                    {
                        return(GetErrorResult(loginResult));
                    }
                    else
                    {
                        //add person email
                        var emailIds    = new List <EmailVerification>();
                        var personEmail = new EmailVerification()
                        {
                            PersonId   = Guid.Empty,
                            Address    = value.Email,
                            IsVerified = false
                        };

                        if (value.SkipEmailVerification)
                        {
                            personEmail.IsVerified = true;
                        }
                        emailIds.Add(personEmail);

                        Person newPerson = new Person()
                        {
                            Company            = value.Company,
                            Department         = value.Department,
                            Name               = value.Name,
                            EmailVerifications = emailIds
                        };
                        var person = _personRepository.Add(newPerson);

                        if (!value.SkipEmailVerification)
                        {
                            if (IsEmailAllowed)
                            {
                                string code = await _userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false);

                                EmailMessage emailMessage = new EmailMessage();
                                emailMessage.Body    = SendConfirmationEmail(code, user.Id, passwordString, "en");
                                emailMessage.Subject = "Confirm your account at " + Constants.PRODUCT;
                                await _emailSender.SendEmailAsync(emailMessage, null, null, "Outgoing").ConfigureAwait(false);
                            }
                            else
                            {
                                value.SkipEmailVerification = true;
                                ModelState.AddModelError("Email", "Email is disabled.  Verification email was not sent.");
                            }
                        }

                        //update the user
                        if (person != null)
                        {
                            var registeredUser = _userManager.FindByNameAsync(user.UserName).Result;
                            registeredUser.PersonId             = person.Id.GetValueOrDefault();
                            registeredUser.ForcedPasswordChange = true;
                            await _userManager.UpdateAsync(registeredUser).ConfigureAwait(false);

                            //add person to organization only if you are admin or add it to access request table
                            if (isRequestingUserAdministrator)
                            {
                                OrganizationMember newOrgMember = new OrganizationMember()
                                {
                                    PersonId       = person.Id,
                                    OrganizationId = Guid.Parse(organizationId),
                                    IsAutoApprovedByEmailAddress = true,
                                    IsInvited = true
                                };
                                await base.PostEntity(newOrgMember).ConfigureAwait(false);
                            }
                            else
                            {
                                //add it to access requests
                                AccessRequest accessRequest = new AccessRequest()
                                {
                                    OrganizationId    = Guid.Parse(organizationId),
                                    PersonId          = person.Id,
                                    IsAccessRequested = true,
                                    AccessRequestedOn = DateTime.UtcNow
                                };

                                _accessRequestManager.AddAccessRequest(accessRequest);
                            }
                        }
                    }
                }
                if (IsEmailAllowed)
                {
                    return(Ok());
                }
                else
                {
                    return(Ok(ModelState));
                }
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }