コード例 #1
0
        private async Task ApplyToUser(OspUser applicationUser, UserDto userDto)
        {
            var roleIds = new List <string>();

            foreach (var roleDto in userDto.Roles)
            {
                if (roleDto == null)
                {
                    continue;
                }

                var role = await _roleManager.FindByIdAsync(roleDto.Id);

                if (role == null)
                {
                    throw new RoleNotFoundException($"Role '{roleDto.Name}' does not exist.");
                }

                roleIds.Add(role.Id.ToString());
            }


            if (!string.IsNullOrWhiteSpace(userDto.Name))
            {
                applicationUser.UserName = userDto.Name;
            }

            applicationUser.Roles.AddRange(roleIds);
            applicationUser.Email     = userDto.Email;
            applicationUser.FirstName = userDto.FirstName;
            applicationUser.LastName  = userDto.LastName;
        }
コード例 #2
0
        public async Task <IActionResult> Index(SetupViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (_userManager.Users.Any())
            {
                ModelState.AddModelError(String.Empty, Texts.Backend_Identity_Setup_Status_UsersAlreadyConfigured);
                return(View(model));
            }

            if (!_credentialGenerator.CheckPassword(model.NewPassword))
            {
                ModelState.AddModelError(String.Empty, Texts.Backend_Identity_Setup_Status_PasswordComplexity);
                return(View(model));
            }

            var adminRole = await _roleManager.FindByNameAsync(CommonConstants.AdministratorsRole);

            if (adminRole == null)
            {
                _logger.LogInformation("No Administrator-Role has been found.");

                ModelState.AddModelError(String.Empty, Texts.Backend_General_Error_Label);
                return(View(model));
            }

            var adminUser = await _userManager.FindByNameAsync(model.EMailAddress);

            if (adminUser == null)
            {
                adminUser = new OspUser {
                    UserName = model.EMailAddress, Email = model.EMailAddress
                };

                await _userManager.CreateAsync(adminUser, model.NewPassword);

                await _userManager.AddToRoleAsync(adminUser, adminRole.NormalizedName);
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #3
0
        private async Task <UserDto> CreateUserDto(OspUser applicationUser, UserManager <OspUser> userManager)
        {
            var userDto = new UserDto
            {
                UserId    = applicationUser.Id.ToString(),
                FirstName = applicationUser.FirstName,
                LastName  = applicationUser.LastName,
                Email     = applicationUser.Email ?? applicationUser.Claims.FirstOrDefault(x => x.ClaimType == JwtClaimTypes.Email)?.ClaimValue,
                Name      = applicationUser.UserName ?? applicationUser.Claims.FirstOrDefault(x => x.ClaimType == JwtClaimTypes.Name)?.ClaimValue
            };

            var roles = new List <RoleDto>();

            foreach (var role in await userManager.GetRolesAsync(applicationUser))
            {
                roles.Add(RolesController.CreateRoleDto(await _roleManager.FindByNameAsync(role)));
            }
            userDto.Roles = roles;

            return(userDto);
        }
コード例 #4
0
        public async Task <IActionResult> Post([Required][FromBody] UserDto userDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var applicationUser = new OspUser();

            try
            {
                await ApplyToUser(applicationUser, userDto);
            }
            catch (RoleNotFoundException e)
            {
                return(BadRequest(new OperationFailedError(e.Message)));
            }

            try
            {
                var result = await _userManager.CreateAsync(applicationUser);

                if (result.Succeeded)
                {
                    return(Ok());
                }

                return(BadRequest(new OperationFailedError("Creation of user failed",
                                                           result.Errors.Select(x => new FailedDetails {
                    Code = x.Code, Description = x.Description
                }))));
            }
            catch (Exception e)
            {
                return(BadRequest(new InternalServerError(e.Message)));
            }
        }
コード例 #5
0
        public async Task <IActionResult> AddAdminUser([FromBody] AdminUserDto adminUserDto)
        {
            if (_userManager.Users.Any())
            {
                return(NotFound("The request is not valid for this configuration."));
            }

            if (!_credentialGenerator.CheckPassword(adminUserDto.Password))
            {
                _logger.LogInformation("The password does not comply with the minimum requirements.");
                return(StatusCode(StatusCodes.Status406NotAcceptable));
            }

            var adminRole = await _roleManager.FindByNameAsync(CommonConstants.AdministratorsRole);

            if (adminRole == null)
            {
                _logger.LogInformation("No Administrator-Role has been found.");
                return(StatusCode(StatusCodes.Status406NotAcceptable));
            }

            var adminUser = await _userManager.FindByNameAsync(adminUserDto.EMail);

            if (adminUser == null)
            {
                adminUser = new OspUser {
                    UserName = adminUserDto.EMail, Email = adminUserDto.EMail
                };

                await _userManager.CreateAsync(adminUser, adminUserDto.Password);

                await _userManager.AddToRoleAsync(adminUser, adminRole.Id.ToString());
            }

            return(Ok());
        }
コード例 #6
0
        private async Task <OspUser> AutoProvisionUserAsync(string provider, string providerUserId,
                                                            ICollection <Claim> claims)
        {
            // create a list of claims that we want to transfer into our store
            var filtered = new List <Claim>();

            // user's display name
            var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
                       claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

            if (name != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Name, name));
            }
            else
            {
                var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
                            claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
                           claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                if (first != null && last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
                }
                else if (first != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first));
                }
                else if (last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, last));
                }
            }

            // email
            var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
                        claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;

            if (email != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Email, email));
            }

            var user = new OspUser()
            {
                UserName = Guid.NewGuid().ToString(),
            };
            var identityResult = await _userManager.CreateAsync(user);

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            if (filtered.Any())
            {
                identityResult = await _userManager.AddClaimsAsync(user, filtered);

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }
            }

            identityResult =
                await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            return(user);
        }