private async Task CreateUserAsync(ImportUserDto input)
        {
            var tenantId = CurrentUnitOfWork.GetTenantId();

            if (tenantId.HasValue)
            {
                await _userPolicy.CheckMaxUserCountAsync(tenantId.Value);
            }

            var user = _objectMapper.Map <User>(input); //Passwords is not mapped (see mapping configuration)

            user.Password = input.Password;
            user.TenantId = tenantId;

            if (!input.Password.IsNullOrEmpty())
            {
                await UserManager.InitializeOptionsAsync(tenantId);

                foreach (var validator in _passwordValidators)
                {
                    (await validator.ValidateAsync(UserManager, user, input.Password)).CheckErrors();
                }

                user.Password = _passwordHasher.HashPassword(user, input.Password);
            }

            user.Roles = new List <UserRole>();
            var roleList = _roleManager.Roles.ToList();

            foreach (var roleName in input.AssignedRoleNames)
            {
                var correspondingRoleName = GetRoleNameFromDisplayName(roleName, roleList);
                var role = await _roleManager.GetRoleByNameAsync(correspondingRoleName);

                user.Roles.Add(new UserRole(tenantId, user.Id, role.Id));
            }

            (await UserManager.CreateAsync(user)).CheckErrors();
        }
Пример #2
0
        public IHttpActionResult ImportUsers(dynamic xmlData)
        {
            var    importResult   = new ImportResultDto();
            var    importUsesrDto = new List <ImportUserDto>();
            var    savedCount     = 0;
            var    skippedCount   = 0;
            var    totalCount     = 0;
            var    failedCount    = 0;
            string xmlDataString  = xmlData.xmlData;

            xmlDataString = Regex.Replace(xmlDataString, @"[^\u0020-\u007F]", String.Empty);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xmlDataString);
            var nodes = doc.ChildNodes;

            foreach (var node in nodes)
            {
                var userNode = node as XmlNode;
                if (userNode.Name == "Users")
                {
                    foreach (var innerNode in userNode.ChildNodes)
                    {
                        var importUserDto    = new ImportUserDto();
                        var contentUserNodes = (innerNode as XmlNode).ChildNodes;
                        var firstName        = contentUserNodes.Item(0).InnerText;
                        var lastName         = contentUserNodes.Item(1).InnerText;
                        var userName         = contentUserNodes.Item(2).InnerText;
                        var email            = contentUserNodes.Item(3).InnerText;
                        importUserDto.FirstName = firstName;
                        importUserDto.LastName  = lastName;
                        importUserDto.UserLogin = userName;
                        importUserDto.Email     = email;
                        try
                        {
                            if (userService.IsEmailExist(email))
                            {
                                skippedCount++;
                                totalCount++;
                                importUserDto.Status = "Skipped";
                            }
                            else
                            {
                                if (ModelState.IsValid == false)
                                {
                                    return(BadRequest(ModelState));
                                }

                                var newUser = userService.Create(userName, email, firstName,
                                                                 "", lastName);

                                #region Send one time code for initial change password
                                var userCode = userCodeRepo.Create(new UserCode()
                                {
                                    UserK = newUser.Id
                                });
                                string code = userCode.Code;

                                var      adminSecurity = adminSecurityService.GetAdministrationSecurity();
                                EmailDto emaildto      = new EmailDto()
                                {
                                    EmailBody      = String.Format("Hi {0} {1}. You have been added as a new user to siteTRAX Evolution. <br/><br/> Your Onetime code is: <b>{2}</b> <br/> This Onetime code is valid until: <b>{3}</b> at which time it will expire and a new one code will be required to be requested. <br/><br/> To enter your onetime code. Click on \"Forget my password\" then click on \"I have a onetime code\" <br/><br/>If you did not request this password reset, please ignore this message. <br/> Do not reply to this email message as the mail box is un-monitored.", newUser.FirstName, newUser.LastName, userCode.Code, userCode.ExpirationDateUtc.ToLocalTime().ToString("dd-MMMM-yyyy hh:mm tt")),
                                    EmailSubject   = "New User - siteTRAX Evolution",
                                    EmailSender    = "*****@*****.**",
                                    EmailRecipient = newUser.Email
                                };

                                CustomEmail.SendPasswordEmail(adminSecurity.MailerServer, adminSecurity.MailerServerPort.Value, adminSecurity.MailerUsername, adminSecurity.MailerPassword, adminSecurity.PasswordResetEmail, newUser.Email, emaildto.EmailSubject, emaildto.EmailBody);
                                #endregion
                                savedCount++;
                                importUserDto.Status = "Added";
                            }
                        }
                        catch (Exception)
                        {
                            failedCount++;
                            importUserDto.Status = "Failed";
                        }

                        importUsesrDto.Add(importUserDto);
                    }

                    importResult.ImportUsersDto = importUsesrDto;
                    importResult.Added          = savedCount;
                    importResult.Skipped        = skippedCount;
                    importResult.Total          = totalCount;
                    importResult.Failed         = failedCount;
                }
            }


            return(Ok(importResult));
        }
Пример #3
0
        private async Task CreateUserAsync(ImportUserDto input)
        {
            var tenantId = CurrentUnitOfWork.GetTenantId();

            if (tenantId.HasValue)
            {
                await _userPolicy.CheckMaxUserCountAsync(tenantId.Value);
            }

            var user = _objectMapper.Map <User>(input);    //Passwords is not mapped (see mapping configuration)

            //shift
            var shift = await _shiftRepository.FirstOrDefaultAsync(x => x.NameAr == input.ShiftName ||
                                                                   x.NameEn == input.ShiftName ||
                                                                   x.Code == input.ShiftName);

            if (shift != null)
            {
                user.ShiftId = shift.Id;
            }

            //unit
            var unit = await _organizationUnitRepository.FirstOrDefaultAsync(x => x.DisplayName == input.Department);

            if (unit != null)
            {
                user.OrganizationUnitId = (int)unit.Id;
            }

            user.Password = input.Password;
            user.TenantId = tenantId;

            if (!input.Password.IsNullOrEmpty())
            {
                await UserManager.InitializeOptionsAsync(tenantId);

                foreach (var validator in _passwordValidators)
                {
                    (await validator.ValidateAsync(UserManager, user, input.Password)).CheckErrors();
                }

                user.Password = _passwordHasher.HashPassword(user, input.Password);
            }

            user.Roles = new List <UserRole>();
            var roleList = _roleManager.Roles.ToList();

            foreach (var roleName in input.AssignedRoleNames)
            {
                var correspondingRoleName = GetRoleNameFromDisplayName(roleName, roleList);
                var role = await _roleManager.GetRoleByNameAsync(correspondingRoleName);

                user.Roles.Add(new UserRole(tenantId, user.Id, role.Id));
            }

            var currentUser = await _userRepository.FirstOrDefaultAsync(x => x.CivilId == input.CivilId);

            if (currentUser != null)
            {
                currentUser.ShiftId            = user.ShiftId;
                currentUser.OrganizationUnitId = user.OrganizationUnitId;
                currentUser.FingerCode         = user.FingerCode;
                currentUser.Password           = user.Password;

                await UserManager.UpdateAsync(currentUser);
            }

            else
            {
                (await UserManager.CreateAsync(user)).CheckErrors();
            }
        }