Exemplo n.º 1
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));
        }
Exemplo n.º 2
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());
            }
        }