Exemplo n.º 1
0
        private async Task <Tuple <Employee, string> > CreateOrdinaryEmployeeAndPassword(Company company, Random randomizer, Employee manager = null)
        {
            string   companyNormalizedName = GetCompanyNormalizedName(company.CompanyName);
            Employee candidate = null;
            string   title, firstName, lastName, email;

            do
            {
                int nameIndex = randomizer.Next(_Names.Length);
                title     = nameIndex < _FemaileNamesStartIndex ? _StringLocalizer["M"] : _StringLocalizer["Mme"];
                firstName = _Names[nameIndex];
                lastName  = _Surname[randomizer.Next(_Surname.Length)];
                email     = $"{firstName[0]}.{lastName.ToLower()}@{companyNormalizedName.ToLower()}.com";
                candidate = await _UnitOfWork.Employees.FindAsync(x => x.Email.Equals(email));
            } while (candidate != null);
            var daysFromCreation = (company.CompanyCreationDate - DateTime.Now).TotalDays;

            Employee result = new Employee()
            {
                UserName       = email,
                Email          = email,
                Title          = title,
                FirstName      = firstName,
                LastName       = lastName,
                Company        = company,
                Manager        = manager,
                EmploymentDate = DateTime.Now.AddDays(randomizer.NextDouble() * daysFromCreation),
                DateOfBirth    = DateTime.Now.AddDays(-1D * Convert.ToDouble(randomizer.Next(19 * 365, 65 * 365))),
                TaxRate        = randomizer.Next().ToString()
            };
            string password = _PasswordGenerator.GeneratePassword();

            return(Tuple.Create(result, password));
        }
        public async Task <IActionResult> CheckPassword([FromForm] AccountCheckPasswordRequest request)
        {
            if (request == null || string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
            {
                return(BadRequest());
            }

            var user = await _userManager.FindByNameAsync(request.UserName);

            // If the user does not exist, then return an empty result.
            if (user == null)
            {
                return(NoContent());
            }

            // If the user does exist and they have not been migrated to the Azure Active Directory identity store with the SQL-managed
            // password, then...
            if (user.MigrationStatus == (int)MigrationStatus.New || user.MigrationStatus == (int)MigrationStatus.NotMigrated || user.MigrationStatus == (int)MigrationStatus.MigratedWithoutPassword)
            {
                var checkPasswordResult = await _userManager.CheckPasswordAsync(user, request.Password);

                if (user.MigrationStatus == (int)MigrationStatus.NotMigrated)
                {
                    var userClaims = await _userManager.GetClaimsAsync(user);

                    var displayNameClaim = userClaims.First(c => c.Type == DisplayNameClaimType);
                    var playerTagClaim   = userClaims.FirstOrDefault(c => c.Type == PlayerTagClaimType);

                    // Create the user in the Azure Active Directory identity with either the SQL-managed password, if it is valid,
                    // or a generated password, if it is not valid.
                    await _graphService.CreateUserAsync(
                        request.UserName,
                        checkPasswordResult?request.Password : _passwordGenerator.GeneratePassword(),
                        displayNameClaim.Value,
                        "Activated",
                        playerTagClaim?.Value,
                        TermsOfServiceConsentedClaimValue);

                    user.MigrationStatus = checkPasswordResult ? (int)MigrationStatus.MigratedWithPassword : (int)MigrationStatus.MigratedWithoutPassword;
                    await _userManager.UpdateAsync(user);
                }
                else if (checkPasswordResult && (user.MigrationStatus == (int)MigrationStatus.New || user.MigrationStatus == (int)MigrationStatus.MigratedWithoutPassword))
                {
                    // Update the password for the user in the Azure Active Directory identity store with the SQL-managed password.
                    await _graphService.SetUserPasswordAsync(request.UserName, request.Password);

                    user.MigrationStatus = (int)MigrationStatus.MigratedWithPassword;
                    await _userManager.UpdateAsync(user);
                }
            }

            return(Ok(user));
        }
Exemplo n.º 3
0
        public async Task RegisterAdminAsync(ApplicationUser applicationUser)
        {
            await applicationUserRepository.AddAsync(applicationUser);

            await applicationUserRepository.SaveChangesAsync();

            string password = passwordGenerator.GeneratePassword();

            await AddUserPasswordAsync(applicationUser.User, password);
            await AddUserToRoleAsync(applicationUser.User, Roles.ADMIN);

            await emailService.SendEmailAsync(applicationUser.User.Email, password);
        }
        public async Task <IActionResult> Activate(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new InvalidOperationException();
            }

            var user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                throw new InvalidOperationException();
            }

            if (user.MigrationStatus == (int)MigrationStatus.NotMigrated)
            {
                throw new InvalidOperationException();
            }

            await _graphService.SetUserActivationStatusAsync(user.UserName, "Pending");

            var userClaims = await _userManager.GetClaimsAsync(user);

            var displayNameClaim = userClaims.First(c => c.Type == WingTipClaimTypes.DisplayNameClaimType);
            var nonce            = _passwordGenerator.GeneratePassword();
            var redeemUrl        = GenerateSignedRedeemUrl(user.UserName, nonce);

            _smtpService.SendActivationEmail(user.UserName, displayNameClaim.Value, redeemUrl);
            var existingNonceClaim = userClaims.FirstOrDefault(c => c.Type == WingTipClaimTypes.NonceClaimType);

            if (existingNonceClaim != null)
            {
                var removeClaimResult = await _userManager.RemoveClaimAsync(user, existingNonceClaim);

                if (!removeClaimResult.Succeeded)
                {
                    throw new InvalidOperationException(removeClaimResult.Errors.ToString());
                }
            }

            var newNonceClaim  = new Claim(WingTipClaimTypes.NonceClaimType, nonce);
            var addClaimResult = await _userManager.AddClaimAsync(user, newNonceClaim);

            if (!addClaimResult.Succeeded)
            {
                throw new InvalidOperationException(addClaimResult.Errors.ToString());
            }

            return(RedirectToAction("Index"));
        }
        public async Task <UniversityCreationResultDTO> CreateUniversityAsync(UniversityCreateRequestViewDTO createRequestDTO)
        {
            var university = new University
            {
                Name = createRequestDTO.UniversityName,
            };
            await universityRepository.AddAsync(university);

            await universityRepository.SaveChangesAsync();

            UniversityAdminRegistrationDTO adminRegisterRequest = new UniversityAdminRegistrationDTO
            {
                FirstName    = createRequestDTO.SubmitterFirstName,
                LastName     = createRequestDTO.SubmitterLastName,
                Email        = createRequestDTO.Email,
                Password     = passwordGenerator.GeneratePassword(),
                UniversityId = university.Id
            };
            await authService.RegisterUniversityAdminAsync(adminRegisterRequest);

            return(new UniversityCreationResultDTO
            {
                UniversityId = university.Id,
                UniversityName = university.Name,
                AdminEmail = adminRegisterRequest.Email,
                AdminPassword = adminRegisterRequest.Password
            });
        }
Exemplo n.º 6
0
        public async Task <string> CreateUser(UserViewModel userViewModel)
        {
            var user = new ApplicationUser
            {
                UserName  = userViewModel.Email,
                Email     = userViewModel.Email,
                FirstName = userViewModel.FirstName,
                LastName  = userViewModel.LastName
            };
            var password = _passwordGenerator.GeneratePassword();

            var result = await _userManager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

                var callbackUrl = $"Identity/Account/ConfirmEmail?userId={user.Id}&code={code}&returnUrl=~/";

                await _emailSender.SendEmailAsync(user.Email, "Confirm your email",
                                                  $"Please confirm your account by " +
                                                  $"<a href='{_navigationManager.BaseUri + HtmlEncoder.Default.Encode(callbackUrl.ToString())}'>clicking here</a>." +
                                                  $"Your automatically generated password: {password}");

                if (!_userManager.Options.SignIn.RequireConfirmedAccount)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);
                }
            }

            return(user.Id);
        }
Exemplo n.º 7
0
        public async Task <ActionResult <PasswordResponse> > ResetPassword(ResetPasswordRequest model)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user == null)
            {
                return(NotFound());
            }

            var password = _passwordGenerator.GeneratePassword();
            var result   = await ChangePassword(user, password);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(error.Code, error.Description);
                }

                return(BadRequest(ModelState));
            }

            var response = new PasswordResponse
            {
                Id       = user.Id,
                UserName = user.UserName,
                Password = password
            };

            return(response);
        }
        public async Task GeneratePassword()
        {
            if (appController.Busy)
            {
                return;
            }
            else
            {
                appController.EnableBusyState();
            }

            var vm = viewModelsController.GetViewModel <CreateViewModel>();

            if (string.IsNullOrEmpty(vm.Login) ||
                string.IsNullOrEmpty(vm.Name))
            {
                appController.DisableBusyState();
                return;
            }

            try
            {
                vm.Password = await Task.Run(() => passwordGenerator.GeneratePassword(vm.UserLower, vm.UseUpper, vm.UseNumber, vm.UseSpecial, vm.UsePolish, vm.PasswordLenght));
            }
            catch (Exception)
            {
                vm.Password = "******";
            }
            finally
            {
                appController.DisableBusyState();
            }
        }
        public JsonResult GeneratePassword(GeneratePasswordViewModel model)
        {
            string password = _passwordGenerator.GeneratePassword(model.PasswordLength, model.MinUpperCaseCharLength,
                                                                  model.MinLowerCaseCharLength, model.MinSpecialCharLength, model.MinNumericCharLength);

            return(Json(password));
        }
Exemplo n.º 10
0
        public ActionResult GeneratePassword(PasswordGeneration passwordGeneration)
        {
            var generatedPassword = new GeneratedPassword
            {
                Value = passwordGenerator.GeneratePassword(passwordGeneration.DomainName,
                                                           passwordGeneration.MasterPassword, passwordGeneration.PasswordLength,
                                                           passwordGeneration.HashFunction, passwordGeneration.CharacterSpace)
            };

            return(Json(generatedPassword));
        }
        public async Task OnGetAsync(int id)
        {
            TenantId      = _sessionTenantAccessor.TenantId;
            ApiResourceId = id;


            Input = new SecretModel
            {
                Value            = _passwordGenerator.GeneratePassword(),
                SecretExpiration = "Never"
            };
        }
        // [Authorize(AuthenticationSchemes = "frontend")]
        public IActionResult Create()
        {
            List <IdentityRole> list = new List <IdentityRole>();

            list         = roleManager.Roles.ToList();
            ViewBag.list = list;
            string generatedPassword   = passwordGenerator.GeneratePassword(15);
            CreateAdminViewModel model = new CreateAdminViewModel();

            model.Password = generatedPassword;
            return(View(model));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Resets the user's password and email's them a new password
        /// </summary>
        /// <param name="email">email address</param>
        public void ForgotPassword(string email)
        {
            var user = GetUserByEmail(email);

            if (user == null || user.Deleted || !user.Active)
            {
                return;
            }

            var password = _passwordGenerator.GeneratePassword(10);

            SetUserPassword(user, user.PasswordFormat, password);
        }
Exemplo n.º 14
0
        private void CreateNewEditorAccount(Request request)
        {
            if (WebSecurity.UserExists(request.Email))
            {
                throw new Exception("Username taken");
            }

            var user        = Mapper.Map <Request, User>(request);
            var userProfile = Mapper.Map <Request, UserProfile>(request);

            user.UserName      = userProfile.Email;
            userProfile.Status = 0;
            _registrationService.CreateUser(user, userProfile, _passwordGenerator.GeneratePassword(), RoleNames.Editor);
        }
Exemplo n.º 15
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                string password = passwordGenerator.GeneratePassword(signInManager);
                var    user     = new ApplicationUser {
                    UserName = Input.User.Email, Email = Input.User.Email, DisplayName = Input.User.Name, OrganizationID = Input.User.OrganizationID, EmailConfirmed = true
                };
                var result = await userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    logger.LogInformation("User created a new account with password.");
                    var addToRoles = await userManager.AddToRolesAsync(user, Input.Roles.Where(r => r.IsAssigned).Select(r => r.Name).ToArray());


                    var code = await userManager.GeneratePasswordResetTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ResetPassword",
                        pageHandler: null,
                        values: new { code },
                        protocol: Request.Scheme);

                    await emailSender.SendEmailAsync(Input.User.Email, "You have been registered for Onebeat",
                                                     $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    //await signInManager.SignInAsync(user, isPersistent: false);
                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            else
            {
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 16
0
        private async Task CreateAccountsForContacts(Contact[] contactsForSave)
        {
            foreach (var contact in contactsForSave)
            {
                foreach (var account in contact.SecurityAccounts)
                {
                    account.MemberId = contact.Id;

                    if (string.IsNullOrEmpty(account.Password))
                    {
                        var generatedPassword = _passwordGenerator.GeneratePassword();
                        await _userManager.CreateAsync(account, generatedPassword);
                    }
                    else
                    {
                        await _userManager.CreateAsync(account, account.Password);
                    }
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Resets a user password using the generated token.
        /// </summary>
        /// <param name="token">Token provided by the system</param>
        /// <returns>The new password generated.</returns>
        public string ResetPassword(string token)
        {
            string unencoded = _tokenizer.ValidateToken(token);

            string[] parameters = unencoded.Split(',');

            int    siteAddressId = Convert.ToInt32(parameters[0]);
            string userName      = parameters[1];

            User u = FindUser(siteAddressId, userName);

            if (u != null)
            {
                string password = _passwordGenerator.GeneratePassword(PasswordGenerationLength);
                u.ChangePassword(password);
                _userRepository.SaveOrUpdate(u);
                return(password);
            }

            throw new InvalidCredentialsException();
        }
Exemplo n.º 18
0
        public bool Create(User user)
        {
            if (!_repository.IsEmailAvailable(user.Email))
            {
                return(false);
            }

            do
            {
                user.Id = Guid.NewGuid();
            } while (!_repository.IsGuidAvailable(user.Id));

            user.Secret    = _transformer.Encrypt(user.Secret, out string key, out string iv);
            user.SecretIv  = iv;
            user.SecretKey = key;

            user.Password = _hasher.Hash(_generator.GeneratePassword(), out string salt);
            user.Salt     = salt;

            return(_repository.Create(user));
        }
Exemplo n.º 19
0
        public Site RegisterUser(int siteId,
                                 string memberName,
                                 string firstName,
                                 string lastName,
                                 string emailAddress,
                                 string userName,
                                 string password)
        {
            User u = FindUser(userName);

            if (u != null)
            {
                throw new UserAlreadyExistException();
            }

            Site c = _siteRepository.Get(siteId);

            var m = new User();

            m.UserName  = memberName;
            m.FirstName = firstName;
            m.LastName  = lastName;
            if (!string.IsNullOrEmpty(password))
            {
                m.SetPassword(password);
            }
            else
            {
                m.SetPassword(_passwordGenerator.GeneratePassword(10));
            }
            m.Email    = emailAddress.Trim().ToLower();
            m.UserName = userName.Trim().ToLower();
            c.AddUser(m);

            SendConfirmationToken(m);

            _siteRepository.SaveOrUpdate(c);

            return(c);
        }
 public string Get(string username)
 {
     return(_passwordGenerator.GeneratePassword(username));
 }
Exemplo n.º 21
0
 public bool ResetPasswordToGenerated(string userLogin, string email, string fullName)
 => ResetPassword(userLogin, _passwordGenerator.GeneratePassword(_passwordLength), email, fullName);
Exemplo n.º 22
0
 private static void GetPassword(IPasswordGenerator generator, List<Password> passwords)
 {
     string password = generator.GeneratePassword();
     Console.WriteLine(password);
     passwords.Add(new Password(password));
 }
        public async Task <IActionResult> AddTeacher(AddTeacherViewModel model)
        {
            if (ModelState.IsValid)
            {
                IdentityUser user = new IdentityUser
                {
                    UserName    = passwordGenerator.GenerateUsernameFromEmail(model.EmailAddress),
                    Email       = model.EmailAddress,
                    PhoneNumber = model.PhoneNumber
                };
                IdentityResult result = await userManager.CreateAsync(user, passwordGenerator.GeneratePassword(15));

                if (result.Succeeded)
                {
                    Teacher teacher = new Teacher
                    {
                        Firstname        = model.Firstname,
                        Middlename       = model.Middlename,
                        Lastname         = model.Lastname,
                        Gender           = model.Gender,
                        DateOfBirth      = model.DateOfBirth.ToString(),
                        PhoneNumber      = model.PhoneNumber,
                        EmailAddress     = model.EmailAddress,
                        Religion         = model.Religion,
                        ProfilePhotoPath = processFileUpload.UploadImage(model.Photo, "uploads"),
                        IdentityUserId   = user.Id,
                        DepartmentId     = model.DepartmentId
                    };
                    _teacherRepository.InsertAndSaveTeacherData(teacher);
                    TeacherContactInformation contactInformation = new TeacherContactInformation
                    {
                        Address1 = model.Address1,
                        Address2 = model.Address2,
                        AlternateEmailAddress = model.AlternateEmailAddress,
                        ZipCode             = model.ZipCode,
                        HomePhone           = model.HomePhone,
                        MobilePhone         = model.MobilePhone,
                        NextOfKinFirstname  = model.NextOfKinFirstname,
                        NextOfKinLastname   = model.NextOfKinLastname,
                        RelationToNextOfKin = model.RelationToNextOfKin,
                        PhoneOfNextOfKin    = model.PhoneOfNextOfKin,
                        EmailOfNextOfKin    = model.EmailOfNextOfKin,
                        TeacherId           = teacher.Id,
                        CountryId           = model.CountryId
                    };
                    _teacherRepository.InsertContactData(contactInformation);
                    TeacherHighestDegree highestDegree = new TeacherHighestDegree
                    {
                        NameOfInstitution = model.NameOfInstitution,
                        YearEnrolled      = model.YearEnrolled.ToString(),
                        YearOfGraduation  = model.YearOfGraduation.ToString(),
                        DegreeAttained    = model.DegreeAttained,
                        CGPA = model.CGPA,
                        TeacherContactInfoId = contactInformation.Id
                    };
                    _teacherRepository.InsertAndSaveHighestDegree(highestDegree);
                    TeacherOtherDegree otherDegree = new TeacherOtherDegree
                    {
                        NameOfInstitution = model.OtherNameOfInstitution,
                        YearOfEnrollement = model.YearOfEnrollement.ToString(),
                        YearOfGraduation  = model.OtherYearOfGraduation.ToString(),
                        DegreeAttained    = model.OtherDegreeAttained,
                        CGPA = model.OtherCGPA,
                        TeacherHighestDegreeId = highestDegree.Id
                    };
                    _teacherRepository.InsertAndSaveOtherDegree(otherDegree);
                    return(RedirectToAction("allteachers"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            ListOfCountries(model);
            ListAllDepartments(model);
            return(View(model));
        }
Exemplo n.º 24
0
 public string RegisterUser(string email)
 {
     return(_passwordGenerator.GeneratePassword(10));
 }
Exemplo n.º 25
0
 public ResultMessage ResetPasswordToGenerated(Employee employee, int passwordLength)
 => ResetPassword(employee, passwordGenerator.GeneratePassword(passwordLength));
Exemplo n.º 26
0
 public bool ResetPasswordToGenerated(Employee employee)
 => ResetPassword(employee, passwordGenerator.GeneratePassword(passwordLength));
Exemplo n.º 27
0
        public async Task <IActionResult> AddStudent(AddStudentViewModel model)
        {
            if (ModelState.IsValid)
            {
                IdentityUser user = new IdentityUser
                {
                    UserName    = passwordGenerator.GenerateUsernameFromEmail(model.EmailAddress),
                    Email       = model.EmailAddress,
                    PhoneNumber = model.PhoneNumber
                };
                IdentityResult result = await userManager.CreateAsync(user, passwordGenerator.GeneratePassword(15));

                string  uniqueName = processFileUpload.UploadImage(model.Image, "uploads");
                Student student    = new Student
                {
                    Firstname             = model.Firstname,
                    Middlename            = model.Middlename,
                    Lastname              = model.Lastname,
                    Gender                = model.Gender,
                    DateOfBirth           = model.DateOfBirth.ToLongDateString(),
                    PhoneNumber           = model.PhoneNumber,
                    AlternateEmailAddress = model.AlternateEmailAddress,
                    EmailAddress          = model.EmailAddress,
                    Religion              = model.Religion,
                    MaritalStatus         = model.MaritalStatus,
                    ResidentialAddress    = model.ResidentialAddress,
                    ContactAddress        = model.ContactAddress,
                    AlternatePhoneNumber  = model.AlternatePhoneNumber,
                    IdentityUserId        = user.Id,
                    DepartmentId          = model.DepartmentId,
                    CourseYearId          = SetStudentCurrentYear(model.PreviousLevel.Value.ToString()),
                    ProfilePhotoPath      = uniqueName,
                    MatriculationNumber   = SetMatriculationNumber(model.FacultyId, model.DepartmentId)
                };
                studentRepository.InsertStudent(student);
                studentRepository.Save();
                StudentAccademicInformation accademicInformation = new StudentAccademicInformation
                {
                    NameOfInstitution = model.NameOfInstitution,
                    YearEnrolled      = model.YearEnrolled.ToLongDateString(),
                    YearOfGraduation  = model.YearOfGraduation.ToLongDateString(),
                    PreviousLevel     = model.PreviousLevel,
                    StudentId         = student.Id
                };
                studentRepository.InsertStudentAccademicInformation(accademicInformation);
                studentRepository.Save();
                StudentNextOfKinInformation nextOfKinInformation = new StudentNextOfKinInformation
                {
                    NextOfKinFirstname  = model.NextOfKinFirstname,
                    NextOfKinLastname   = model.NextOfKinLastname,
                    RelationToNextOfKin = model.RelationToNextOfKin,
                    PhoneOfNextOfKin    = model.PhoneOfNextOfKin,
                    EmailOfNextOfKin    = model.EmailOfNextOfKin,
                    StudentId           = student.Id
                };
                studentRepository.InsertStudentNextOfKin(nextOfKinInformation);
                studentRepository.Save();
                StudentSponsor studentSponsor = new StudentSponsor
                {
                    SponsorFirstname      = model.SponsorFirstname,
                    SponsorMiddlename     = model.SponsorMiddlename,
                    SponsorLastname       = model.SponsorLastname,
                    SponsorEmailAddress   = model.SponsorEmailAddress,
                    SponsorPhoneNumber    = model.SponsorPhoneNumber,
                    SponsorContactAddress = model.SponsorContactAddress,
                    SponsorProffession    = model.SponsorProffession,
                    SponsorWorkAddress    = model.SponsorWorkAddress,
                    StudentId             = student.Id
                };
                SetStudentCourses(student.Id, student.DepartmentId, student.CourseYearId);
                studentRepository.InsertStudentSponsor(studentSponsor);
                studentRepository.Save();

                return(Redirect("allstudents"));
            }
            ListAllFaculties(model);
            ListAllDepartments(model);
            return(View(model));
        }
Exemplo n.º 28
0
        public async Task <IActionResult> CreateEmployee(EmployeeCreationVM employeeCreationVM)
        {
            string referer            = employeeCreationVM.ReturnUrl;
            var    currentPermissions = await GetEditionPermission(null);

            var currentUserData = await GetCurrentUserData();

            //Validating access
            if (!ValidateCreationAccess(currentUserData.Item3))
            {
                return(Forbid());
            }
            //Validating duplicates
            await ValidateDuplicateMail(employeeCreationVM.Email);
            await ValidateDuplicateUserName(employeeCreationVM.UserName);

            //Validating contract
            ValidateContractAcceptence(employeeCreationVM.AcceptContract);
            //Validating is company and manager correctly assigned
            await ValidateEmployeeCreationVMState(employeeCreationVM);

            UserRoles employeeRoles = await ValidateAssignedRoles(UserManagerExtensions.ToUserRoles(employeeCreationVM.Roles), null);

            if (ModelState.ErrorCount > 0)
            {
                employeeCreationVM.RolesList = await GetListAllowedRoles(employeeRoles);
            }
            if (ModelState.ErrorCount == 0)
            {
                Employee employee = new Employee();
                employeeCreationVM.Id = employee.Id;
                employee = (Employee)_Mapper.Map(employeeCreationVM, typeof(EmployeeCreationVM), typeof(Employee));
                string password = _PasswordGenerator.GeneratePassword();
                employee.LockoutEnabled = false;
                employee.EmailConfirmed = true;
                bool result = await _UnitOfWork.Employees.RegisterEmployeeAsync(_UserManager, employee, password);

                if (!result)
                {
                    ModelState.AddModelError("", _DataLocalizer["Unabled to save employee into repository"]);
                }
                else
                {
                    await SendMailWithCredentials(employee, password);
                }
            }
            //Validating user roles
            if (ModelState.ErrorCount == 0)
            {
                var employeeIdentityUser = await _UserManager.FindByEmailAsync(employeeCreationVM.Email);

                var newRoles = UserManagerExtensions.FromUserRoles(employeeRoles).ToList();
                foreach (var role in newRoles)
                {
                    var identityResult = await _UserManager.AddToRoleAsync(employeeIdentityUser, role);

                    if (!identityResult.Succeeded)
                    {
                        ModelState.AddModelError("", _DataLocalizer["Unable to add this user to role {0}", role]);
                    }
                }
                ;
            }

            if (ModelState.ErrorCount > 0)
            {
                employeeCreationVM = await SetEmployeeCompanyAndManagerState(employeeCreationVM, currentPermissions);

                employeeCreationVM.RolesListEnabled = currentPermissions.AllowEditAccess;
                employeeCreationVM.RolesList        = await GetListAllowedRoles(currentUserData.Item3, self : currentPermissions.IsSelfEdition);

                ViewData["Referer"] = referer;
                ViewBag.Action      = nameof(CreateEmployee);
                return(View(RegisterEmployeeView, employeeCreationVM));
            }
            else
            {
                if (!String.IsNullOrEmpty(referer))
                {
                    return(Redirect(referer));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
        }
 private void AutoGeneratePassword_Click(object sender, RoutedEventArgs e)
 {
     CreateUserModel.SetAutoGenerateneratedPassword(passwordGenerator.GeneratePassword());
 }
        public async Task <UserModel> RegisterUser(TokenModel token, string userName)
        {
            var user = await userRepository.Register(new RegisterModel { Username = userName, Password = passwordGenerator.GeneratePassword(20, 30) });

            if (user != null)
            {
                context.UserTokens.Add(new Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken <string>
                {
                    LoginProvider = socialAPI.ProviderName,
                    Name          = socialAPI.ProviderName,
                    UserId        = user.Id,
                    Value         = token.User_Id
                });

                if (await context.SaveChangesAsync() <= 0)
                {
                    return(null);
                }
            }

            return(user);
        }
Exemplo n.º 31
0
 public bool ResetPasswordToGenerated(string userLogin, string email)
 => ResetPassword(userLogin, passwordGenerator.GeneratePassword(passwordLength), email);