Example #1
0
        public async Task <IActionResult> Post([FromRoute] int departmentId, [FromBody] string userId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByIdAsync(userId);

            var department = _departmentRepository.Get(departmentId);

            if (user == null)
            {
                return(NotFound("User is not found"));
            }

            if (department == null)
            {
                return(NotFound("Department is not found"));
            }

            var depUser = new DepartmentApplicationUser
            {
                ApplicationUserId = user.Id,
                DepartmentId      = department.DepartmentId,
                IsMaintainer      = false
            };

            await _departmentApplicationUserRepository.Add(depUser);

            return(CreatedAtAction("Get", new { id = department.DepartmentId }, department));
        }
Example #2
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            const string employeeNumberRegex = @"^[a-zA-Z0-9]*$";
            var          regex = new Regex(employeeNumberRegex);

            if (!regex.IsMatch(Input.EmployeeNumber))
            {
                ModelState.AddModelError("EmployeeNumber", "Employee-number is not valid");
            }
            else
            {
                var user = _context.Users.FirstOrDefault(u => u.EmployeeNumber == Input.EmployeeNumber);
                if (user != null)
                {
                    ModelState.AddModelError("EmployeeNumber", "Employee-number already exists");
                }
            }

            if (ModelState.IsValid)
            {
                var currentUser = await _userManager.FindByNameAsync(User.Identity.Name);

                var user = new ApplicationUser {
                    UserName       = Input.Email,
                    Email          = Input.Email,
                    EmployeeNumber = Input.EmployeeNumber,
                    FirstName      = Input.FirstName,
                    LastName       = Input.LastName,
                    BirthDate      = Input.BirthDate,
                    PhoneNumber    = Input.PhoneNumber,
                    CreationDate   = DateTime.Now,
                    CurrentLoggedInDepartmentId = currentUser.CurrentLoggedInDepartmentId,
                    LockoutEnabled           = true,
                    LockoutEnd               = null,
                    IsOrganizationMaintainer = false
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    user = await _userManager.FindByIdAsync(user.Id);

                    await _departmentApplicationUserRepository.Add(new DepartmentApplicationUser
                    {
                        ApplicationUserId = user.Id,
                        DepartmentId      = currentUser.CurrentLoggedInDepartmentId,
                        IsMaintainer      = false
                    });

                    result = await _userManager.UpdateAsync(user);

                    if (!result.Succeeded)
                    {
                        _logger.LogInformation("Unable to add user to department. Check error logs for any errors!");
                        result = await _userManager.DeleteAsync(user);

                        if (!result.Succeeded)
                        {
                            _logger.LogInformation("Unable to remove user. Manual intervention required.");
                        }
                    }
                    _logger.LogInformation("A new user-account with password created.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "User");

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(Page());
        }