/// <summary>
 /// Initializes a new instance of the <c>RegisterUserResponseViewModel</c> class.
 /// </summary>
 /// <param name="user">The user that is registered.</param>
 public RegisterUserResponseViewModel(AbacuzaAppUser user)
 {
     Id          = user.Id;
     UserName    = user.UserName;
     DisplayName = user.DisplayName;
     Email       = user.Email;
 }
Example #2
0
        public async Task <IActionResult> RegisterUser([FromBody] RegisterUserRequestViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var appUser = new AbacuzaAppUser
            {
                UserName    = model.UserName,
                DisplayName = model.DisplayName,
                Email       = model.Email
            };

            var result = await _userManager.CreateAsync(appUser, model.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            await _userManager.AddClaimAsync(appUser, new Claim(ClaimTypes.NameIdentifier, appUser.UserName));

            await _userManager.AddClaimAsync(appUser, new Claim(ClaimTypes.Name, appUser.DisplayName));

            await _userManager.AddClaimAsync(appUser, new Claim(ClaimTypes.Email, appUser.Email));

            if (model.RoleNames?.Count > 0)
            {
                var validRoleNames = new List <string>();
                foreach (var roleName in model.RoleNames)
                {
                    var trimmedRoleName = roleName.Trim();
                    if (await _roleManager.RoleExistsAsync(trimmedRoleName))
                    {
                        validRoleNames.Add(trimmedRoleName);
                        await _userManager.AddToRoleAsync(appUser, trimmedRoleName);
                    }
                }

                await _userManager.AddClaimAsync(appUser, new Claim(ClaimTypes.Role, string.Join(',', validRoleNames)));
            }

            return(Ok(new RegisterUserResponseViewModel(appUser)));
        }