Пример #1
0
        public void UpdateUserClaims(int memberId)
        {
            var memberById = Uow.MemberRepository.GetQueryWithIncludes().FirstOrDefault(m => m.Id == memberId);

            #region v1.

            //try
            //{
            //    memberById.User.Claims.Clear();
            //    Uow.MemberRepository.Update(memberById);
            //    Uow.Save();

            //    // Assigns claims.
            //    var claims = ClaimsCreator.GetUserClaims(memberById.User.UserName, memberById.FullName, memberById.User.Email, memberById.User.IsAdmin ? AdminRole : UserRole, memberId);

            //    _userManager.AddClaimsAsync(memberById.User, claims).GetAwaiter().GetResult();

            //    ClearCacheMembers();
            //}

            //catch (Exception) { }

            #endregion

            #region v2.

            //memberByName.User.Claims.Clear();
            //memberByName.User.Claims.Add(new IdentityUserClaim<string> { ClaimType = JwtClaimTypes.Email, ClaimValue = memberByName.User.Email, });
            //var updatememberByNameClaims = _userManager.UpdateAsync(memberByName.User).GetAwaiter().GetResult();
            //if (!updatememberByNameClaims.Succeeded)
            //{
            //    BLHelpers.CheckMembersErrors(updatememberByNameClaims.Errors.Select(e => new IdentityErrorView
            //    {
            //        Code = e.Code,
            //        Description = e.Description
            //    }));
            //}

            #endregion

            var memberByNameClaims    = _userManager.GetClaimsAsync(memberById.User).GetAwaiter().GetResult();
            var removeClaimsForMember = _userManager.RemoveClaimsAsync(memberById.User, memberByNameClaims).GetAwaiter().GetResult();
            if (!removeClaimsForMember.Succeeded)
            {
                CheckIdentityResultErrors(removeClaimsForMember);
            }

            var claimsForMemberNew = ClaimsCreator.CreateUserClaims(memberById.User.UserName, memberById.FullName, memberById.User.Email, memberById.User.IsAdmin ? ApplicationRoleAdmin : ApplicationRoleUser, memberById.Id);
            var addClaimsForMember = _userManager.AddClaimsAsync(memberById.User, claimsForMemberNew).GetAwaiter().GetResult();
            if (!addClaimsForMember.Succeeded)
            {
                CheckIdentityResultErrors(addClaimsForMember);
            }
        }
Пример #2
0
        private async Task <Member> CreateNewUserCommon(MemberView memberView, ApplicationUser applicationUserNew, string roleUser)
        {
            //var userByName = Uow.UserRepository.LinkedCacheGetByName(memberView.UserName);
            //if (userByName != null)
            //{
            //    throw new CoralTimeAlreadyExistsException($"User with userName {memberView.UserName} already exist");
            //}

            #region Check ApplicationUser, Roles, Claims, Member

            // Check ApplicationUser
            var isExistApplicationUser = await _userManager.FindByNameAsync(memberView.UserName);

            if (isExistApplicationUser != null)
            {
                throw new CoralTimeAlreadyExistsException($"User with userName {memberView.UserName} already exist");
            }

            // Check ApplicationUser Roles
            var isExistRolesForMember = await _userManager.GetRolesAsync(applicationUserNew).ToAsyncEnumerable().Any(x => x.Contains(roleUser));

            if (isExistRolesForMember)
            {
                throw new CoralTimeAlreadyExistsException($"User with userName {memberView.UserName} already exist '{roleUser}' role");
            }

            // Check Member
            var isExistMember = Uow.MemberRepository.GetQueryByUserName(applicationUserNew.UserName);
            if (isExistMember != null)
            {
                throw new CoralTimeAlreadyExistsException($"Member with userName {memberView.UserName} already exist");
            }

            #endregion

            // Insert ApplicationUser
            var userCreationResult = await _userManager.CreateAsync(applicationUserNew, memberView.Password);

            if (!userCreationResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreationResult);
            }

            var applicationUser = await _userManager.FindByNameAsync(applicationUserNew.UserName);

            // Insert ApplicationUser Roles
            var userCreateRoleResult = await _userManager.AddToRoleAsync(applicationUser, roleUser);

            if (!userCreateRoleResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreateRoleResult);
            }

            #region Set UserId to new Member. Save to Db. Get Member from Db with related entity User by UserId.

            // 1. Convert MemberView to Member.
            var newMember = Mapper.Map <MemberView, Member>(memberView);

            // 2. Assign UserId to Member (After Save, when you try to get entity from Db, before assign UserId to entity then it has Related Entity User).
            newMember.UserId = applicationUser.Id;

            // 3. Save in Db.
            Uow.MemberRepository.Insert(newMember);
            Uow.Save();

            // 4. Clear cache for Members.
            Uow.MemberRepository.LinkedCacheClear();

            // 5. Get From Db -> Cache New Member. (Get entity With new created related entity - User)
            var memberByName = Uow.MemberRepository.LinkedCacheGetByName(memberView.UserName);

            #endregion

            // Identity #3. Create claims. Add Claims for user in AspNetUserClaims.
            var claimsUser       = ClaimsCreator.CreateUserClaims(applicationUser.UserName, memberView.FullName, memberView.Email, roleUser, memberByName.Id);
            var claimsUserResult = await _userManager.AddClaimsAsync(applicationUser, claimsUser);

            if (!claimsUserResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreateRoleResult);
            }

            return(memberByName);
        }
Пример #3
0
        public async Task <MemberView> CreateNewUser(MemberView memberView, string baseUrl)
        {
            if (!EmailChecker.IsValidEmail(memberView.Email))
            {
                throw new CoralTimeDangerException("Invalid email");
            }

            var applicationUserNew = new ApplicationUser
            {
                UserName  = memberView.UserName,
                Email     = memberView.Email,
                IsManager = false,
                IsActive  = true,
                IsAdmin   = memberView.IsAdmin
            };

            var roleUser = memberView.IsAdmin ? ApplicationRoleAdmin : ApplicationRoleUser;

            #region Check ApplicationUser, Roles, Member

            // Check ApplicationUser
            var isExistApplicationUser = await _userManager.FindByNameAsync(memberView.UserName);

            if (isExistApplicationUser != null)
            {
                throw new CoralTimeAlreadyExistsException($"User with userName {memberView.UserName} already exist");
            }

            // Check ApplicationUser Roles
            var isExistRolesForMember = await _userManager.GetRolesAsync(applicationUserNew).ToAsyncEnumerable().Any(x => x.Contains(roleUser));

            if (isExistRolesForMember)
            {
                throw new CoralTimeAlreadyExistsException($"User with userName {memberView.UserName} already exist '{roleUser}' role");
            }

            // Check Member
            var isExistMember = Uow.MemberRepository.GetQueryByUserName(applicationUserNew.UserName);
            if (isExistMember != null)
            {
                throw new CoralTimeAlreadyExistsException($"Member with userName {memberView.UserName} already exist");
            }

            #endregion

            // Insert ApplicationUser
            var userCreationResult = await _userManager.CreateAsync(applicationUserNew, memberView.Password);

            if (!userCreationResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreationResult);
            }

            var applicationUser = await _userManager.FindByNameAsync(applicationUserNew.UserName);

            // Insert ApplicationUser Roles
            var userCreateRoleResult = await _userManager.AddToRoleAsync(applicationUser, roleUser);

            if (!userCreateRoleResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreateRoleResult);
            }

            #region Set UserId to new Member. Save to Db. Get Member from Db with related entity User by UserId.

            // 1. Convert MemberView to Member.
            var newMember = memberView.GetModel(Mapper);

            // 2. Assign UserId to Member (After Save, when you try to get entity from Db, before assign UserId to entity then it has Related Entity User).
            newMember.UserId = applicationUser.Id;

            // 3. Save in Db.
            Uow.MemberRepository.Insert(newMember);
            Uow.Save();

            // 4. Clear cache for Members.
            Uow.MemberRepository.LinkedCacheClear();

            // 5. Get From Db -> Cache New Member. (Get entity With new created related entity - User)
            var memberByName = Uow.MemberRepository.LinkedCacheGetByName(memberView.UserName);

            #endregion

            // Identity #3. Create claims. Add Claims for user in AspNetUserClaims.
            var claimsUser       = ClaimsCreator.CreateUserClaims(applicationUser.UserName, memberView.FullName, memberView.Email, roleUser, memberByName.Id);
            var claimsUserResult = await _userManager.AddClaimsAsync(applicationUser, claimsUser);

            if (!claimsUserResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreateRoleResult);
            }

            var urlIcon          = _avatarService.GetUrlIcon(memberByName.Id);
            var memberViewResult = memberByName.GetView(Mapper, urlIcon);

            if (memberView.SendInvitationEmail)
            {
                await SentInvitationEmailAsync(memberView, baseUrl);
            }

            return(memberViewResult);
        }
Пример #4
0
        private static async Task InitializeUsers(string typeUser, string roleUser)
        {
            var users = Configuration.GetSection($"Users:{typeUser}").GetChildren();

            foreach (var user in users)
            {
                // Get Values
                var userName     = user["UserName"];
                var userFullName = user["FullName"];
                var userPassword = user["Password"];
                if (string.IsNullOrWhiteSpace(userPassword))
                {
                    userPassword = "******" + Guid.NewGuid();
                }
                var userEmail = user["Email"];

                #region Create ApplicationUser, Roles, Claims, Member

                // Create ApplicationUser
                var applicationUser = new ApplicationUser
                {
                    UserName  = userName,
                    Email     = userEmail,
                    IsAdmin   = roleUser == Constants.ApplicationRoleAdmin,
                    IsManager = false,
                    IsActive  = bool.Parse(user["IsActive"])
                };

                // Create Member
                var member = new Member
                {
                    UserId   = applicationUser.Id,
                    FullName = userFullName
                };

                #endregion

                #region Insert ApplicationUser, Roles, Claims

                // Insert ApplicationUser
                var userCreationResult = await UserManager.CreateAsync(applicationUser, userPassword);

                if (!userCreationResult.Succeeded)
                {
                    continue;
                }

                // Insert ApplicationUser Roles
                var roleForMemberResult = await UserManager.AddToRoleAsync(applicationUser, roleUser);

                if (!roleForMemberResult.Succeeded)
                {
                    continue;
                }

                #endregion

                #region Insert Member

                try
                {
                    // Insert Member
                    await DbContext.Members.AddAsync(member);

                    // Save DbContex
                    await DbContext.SaveChangesAsync();

                    // Create ApplicationUser claims
                    var claims = ClaimsCreator.CreateUserClaims(applicationUser.UserName, userFullName, userEmail, roleUser, member.Id);

                    // Insert ApplicationUser claims
                    var applicationUserClaimsResult = await UserManager.AddClaimsAsync(applicationUser, claims);

                    if (!applicationUserClaimsResult.Succeeded)
                    {
                        continue;
                    }
                }
                catch (Exception) { }

                #endregion
            }
        }