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));
        }
Example #2
0
        public async Task <IActionResult> CreateToken([FromBody] LoginModel loginModel)
        {
            logger.LogInformation(string.Format("Login user : {0}", loginModel.UserName));
            if (ModelState.IsValid)
            {
                ApplicationUser user = null;
                //Sign in user id
                string signInUser = loginModel.UserName;
                if (RegexUtilities.IsValidEmail(signInUser))
                {
                    //First check if emailId exists
                    user = await userManager.FindByEmailAsync(signInUser).ConfigureAwait(true);
                }
                else //Not emailId, then find by username.
                {
                    user = await userManager.FindByNameAsync(signInUser).ConfigureAwait(true);
                }

                if (user == null)
                {
                    return(Unauthorized());
                }
                signInUser = user?.UserName;

                var loginResult = await signInManager.PasswordSignInAsync(signInUser, loginModel.Password, isPersistent : false, lockoutOnFailure : false).ConfigureAwait(true);

                if (!loginResult.Succeeded)
                {
                    return(Unauthorized());
                }

                Person person = personRepository.Find(null, p => p.Id == user.PersonId)?.Items.FirstOrDefault();
                string authenticationToken = GetToken(user);
                VerifyUserEmailAsync(user);

                var agentId = (Guid?)null;
                if (person.IsAgent)
                {
                    agentId = agentRepository.Find(null, p => p.Name == user.Name)?.Items?.FirstOrDefault()?.Id;
                }

                string startsWith = "";
                int    skip       = 0;
                int    take       = 100;
                var    personOrgs = membershipManager.Search(user.PersonId, startsWith, skip, take);
                // Issue #2791 We will disable the need for User Consent for this release.
                bool isUserConsentRequired = false; // VerifyUserAgreementConsentStatus(user.PersonId);
                var  pendingAcessOrgs      = membershipManager.PendingOrganizationAccess(user.PersonId);
                var  newRefreshToken       = GenerateRefreshToken();
                var  authenticatedUser     = new
                {
                    personId     = user.PersonId,
                    email        = user.Email,
                    userName     = user.UserName,
                    token        = authenticationToken,
                    refreshToken = newRefreshToken,
                    user.ForcedPasswordChange,
                    isUserConsentRequired,
                    IsJoinOrgRequestPending = (pendingAcessOrgs?.Items?.Count > 0) ? true : false,
                    myOrganizations         = personOrgs?.Items,
                    agent = agentId
                };
                //Save refresh token
                await userManager.SetAuthenticationTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, "refresh", newRefreshToken).ConfigureAwait(false);

                try
                {
                    AuditLog auditLog = new AuditLog();
                    auditLog.ChangedFromJson = null;
                    auditLog.ChangedToJson   = JsonConvert.SerializeObject(authenticatedUser);
                    auditLog.CreatedBy       = user.Email;
                    auditLog.CreatedOn       = DateTime.UtcNow;
                    auditLog.Id             = Guid.NewGuid();
                    auditLog.IsDeleted      = false;
                    auditLog.MethodName     = "Login";
                    auditLog.ServiceName    = this.ToString();
                    auditLog.Timestamp      = new byte[1];
                    auditLog.ParametersJson = "";
                    auditLog.ExceptionJson  = "";

                    auditLogRepository.Add(auditLog); //Log entry
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Audit Log", ex.Message);
                    return(BadRequest());
                }
                return(Ok(authenticatedUser));
            }
            return(BadRequest(ModelState));
        }