Beispiel #1
0
        public async Task <Result> RemoveUser(string userId)
        {
            _logger.LogInformation($"Removing user. UserId {userId}");

            IBaseSpecification <AppUserEntity, AppUserEntity> getUserSpecification = SpecificationBuilder
                                                                                     .Create <AppUserEntity>()
                                                                                     .Where(x => x.Id == userId)
                                                                                     .Build();

            AppUserEntity appUser = await _userDAO.SingleOrDefault(getUserSpecification);

            if (appUser == null)
            {
                _logger.LogWarning($"No User. UserId {userId}");
                return(Result.Fail(USER_NOT_FOUND));
            }

            Result removeUserImageResult = await _profileImageService.Remove(userId);

            if (removeUserImageResult.Failure)
            {
                return(Result.Fail(removeUserImageResult));
            }

            appUser.FirstName = null;
            appUser.LastName  = null;

            Guid guid = Guid.NewGuid();

            appUser.Email         = $"deleted_email_{guid}";
            appUser.UserName      = $"deleted_username_{guid}";
            appUser.SecurityStamp = Guid.NewGuid().ToString();

#if NET_CORE2
            appUser.NormalizedEmail = _userManager.NormalizeKey(appUser.Email);
            appUser.NormalizedEmail = _userManager.NormalizeKey(appUser.UserName);
#elif NET_CORE3
            appUser.NormalizedEmail    = _userManager.NormalizeEmail(appUser.Email);
            appUser.NormalizedUserName = _userManager.NormalizeName(appUser.UserName);
#endif

            bool updateResult = await _userDAO.Update(appUser);

            if (!updateResult)
            {
                _logger.LogError($"Failed to update user. UserId {userId}");
                return(Result.Fail(FAILED_TO_UPDATE_USER));
            }

            bool removeResult = _userRepository.Remove(appUser);
            if (!removeResult)
            {
                _logger.LogError($"Failed to remove user. UserId {userId}");
                return(Result.Fail(FAILED_TO_REMOVE_USER));
            }

            _logger.LogInformation($"User was removed. UserId {userId}");

            return(Result.Ok());
        }
Beispiel #2
0
        private async Task <Result> ChangeRoleAsync(long groupUserId, string roleId, string userId)
        {
            _logger.LogInformation($"Changing GroupUser role. GroupUserId {groupUserId}, roleId {roleId}");

            Result roleValidResult = await RoleIsValid(roleId);

            if (roleValidResult.Failure)
            {
                return(Result.Fail(roleValidResult));
            }

            List <RoleListData> canAssigneGroupRoles = _groupUserStore.CanAssigneGroupRoles();

            if (!canAssigneGroupRoles.Any(x => x.Id == roleId))
            {
                _logger.LogError($"User does not have permission to assign role. RoleId {roleId}");
                return(Result.Fail(NO_PERMISSION));
            }

            Core.Models.Result.Result <GroupUserEntity> getGroupUserResult = _groupUserStore.Get(groupUserId);
            if (getGroupUserResult.Failure)
            {
                return(getGroupUserResult.ToNewResult());
            }

            GroupUserEntity groupUser = getGroupUserResult.Value;

            List <RoleListData> canManageGroupRoles = _groupUserStore.CanManageGroupRoles();

            if (!canManageGroupRoles.Any(x => x.Id != groupUser.RoleId))
            {
                _logger.LogError($"User does not have permission to manage role. GroupUserId {groupUserId} RoleId {roleId}");
                return(Result.Fail(NO_PERMISSION));
            }

            if (!_groupUserStore.CanChangeOwnRole())
            {
                if (groupUser.UserId == userId)
                {
                    _logger.LogError($"User can not change his own role");
                    return(Result.Fail(USER_CAN_NOT_CHANGE_HIS_OWN_ROLE));
                }
            }

            groupUser.UpdateRole(roleId);

            bool updateResult = await _groupUserDAO.Update(groupUser);

            if (!updateResult)
            {
                _logger.LogError($"Failed to change group user role. GroupUserId {groupUserId}, roleId {roleId}");
                return(Result.Fail(FAILED_TO_CAHNGE_GROUP_USER_ROLE));
            }

            return(Result.Ok());
        }
        public bool UpdateItem(int id, T modifiedObject)
        {
            if (id <= 0 || modifiedObject == null)
            {
                return(false);
            }
            var modified = GetPropChangedOf(modifiedObject);

            if (modified.Count <= 0)
            {
                throw new Exception("There is nothing to Update");
            }
            bool re = _db.Update(id, modified);

            if (_cache != null && _CACHEKEY != null && re)
            {
                _cache.MarkChanged(_CACHEKEY);
            }
            return(re);
        }
Beispiel #4
0
        public async Task <Result> RemoveAsync(string id)
        {
            IBaseSpecification <GroupEntity, GroupEntity> specification = SpecificationBuilder
                                                                          .Create <GroupEntity>()
                                                                          .Where(x => x.Id == id)
                                                                          .Include(x => x.Invites)
                                                                          .Include(x => x.Users)
                                                                          .Build();

            Result <GroupEntity> getGroupResult = await _groupStore.SingleOrDefault(specification);

            if (getGroupResult.Failure)
            {
                return(Result.Fail(getGroupResult));
            }

            _logger.LogInformation($"Removing group. GroupId {id}");

            GroupEntity groupEntity = getGroupResult.Value;

            string guid = Guid.NewGuid().ToString();

            groupEntity.Name = $"deleted_group_{guid}";

            bool updateResult = await _groupDAO.Update(groupEntity);

            if (!updateResult)
            {
                _logger.LogError($"Failed to update group for deleting. GroupId {id}");
                return(Result.Fail(FAILED_TO_UPDATE_USER));
            }

            if (groupEntity.Invites.Any())
            {
                _logger.LogInformation($"Removing group invites. GroupId {groupEntity.Id}");

                bool removeGroupInvitesResult = await _inviteDAO.RemoveRange(groupEntity.Invites);

                if (!removeGroupInvitesResult)
                {
                    _logger.LogError($"Failed to remove group invites. GroupId {groupEntity.Id}");
                }
            }

            if (groupEntity.Users.Any())
            {
                _logger.LogInformation($"Removing group users. GroupId {groupEntity.Id}");

                bool removeGroupUsersResult = await _groupUserDAO.RemoveRange(groupEntity.Users);

                if (!removeGroupUsersResult)
                {
                    _logger.LogError($"Failed to remove group users. GroupId {groupEntity.Id}");
                }
            }

            bool removeResult = await _groupDAO.Remove(groupEntity);

            if (!removeResult)
            {
                _logger.LogError($"Failed to remove Group. GroupId {id}");
                return(Result.Fail("failed_to_remove_group", "Failed to remove group"));
            }

            return(Result.Ok());
        }
Beispiel #5
0
        public async Task <Core.Models.Result.Result> AcceptInvite(AcceptInviteRequest acceptInvite)
        {
            ValidationResult acceptInviteValidationResult = _acceptInviteValidator.Validate(acceptInvite);

            if (!acceptInviteValidationResult.IsValid)
            {
                _logger.LogWarning($"Invalid {typeof(AcceptInviteRequest).Name} model");
            }

            IBaseSpecification <InviteEntity, InviteEntity> getInviteSpecification = SpecificationBuilder
                                                                                     .Create <InviteEntity>()
                                                                                     .Where(x => x.Token == acceptInvite.Code)
                                                                                     .Where(x => x.Status == Data.Enums.Entity.InviteStatuses.Pending)
                                                                                     .Build();

            InviteEntity inviteEntity = await _inviteDAO.SingleOrDefault(getInviteSpecification);

            if (inviteEntity == null)
            {
                _logger.LogError($"No Invite. Token {acceptInvite.Code}");
                return(Core.Models.Result.Result.Fail("no_invite", "No Invite"));
            }

            if (inviteEntity.ExpiresAt < DateTimeOffset.UtcNow)
            {
                _logger.LogError($"Invite has expired");
                return(Core.Models.Result.Result.Fail("no_invite", "No Invite"));
            }

            if (inviteEntity.GroupId != null)
            {
                Result groupValidResult = await _groupUserService.ValidateGroup(inviteEntity.GroupId);

                if (groupValidResult.Failure)
                {
                    return(Result.Fail(groupValidResult).ToOldResult());
                }

                Result groupRoleValidResult = await _groupUserService.RoleIsValid(inviteEntity.GroupRoleId);

                if (groupRoleValidResult.Failure)
                {
                    return(Result.Fail(groupRoleValidResult).ToOldResult());
                }
            }

            acceptInvite.Email = inviteEntity.Email;

            Result <AppUserEntity> addUserResult = await AddUser(acceptInvite, sendConfirmationMail : false, emailConfirmed : true);

            if (addUserResult.Failure)
            {
                return(addUserResult.ToOldResult());
            }

            AppUserEntity appUser = addUserResult.Value;

            inviteEntity.Update(Data.Enums.Entity.InviteStatuses.Accepted);
            bool updateInvite = await _inviteDAO.Update(inviteEntity);

            if (!updateInvite)
            {
                _logger.LogWarning($"Failed to update invite status. InnivteId {inviteEntity.Id}, UserId {appUser.Id}");
            }

            if (inviteEntity.GroupId != null)
            {
                Result addToGroupResult = await _groupUserService.AddUserToGroupWithoutValidation(appUser.Id, inviteEntity.GroupId, inviteEntity.GroupRoleId);
            }

            if (inviteEntity.RoleId != null)
            {
                Result addToGlobalRole = await AddToGlobalRole(appUser, inviteEntity.RoleId);
            }

            return(Core.Models.Result.Result.Ok());
        }
        public async Task <Core.Models.Result.Result> UpdateProfileImage(string userId, UploadProfileImageRequest uploadProfileImageRequest)
        {
            if (uploadProfileImageRequest == null || uploadProfileImageRequest.File == null)
            {
                _logger.LogWarning($"No image. UserId {userId}");
                return(Result.Fail(PROFILE_IMAGE_NOT_FOUND).ToOldResult());
            }

            //TODO: changed how image format is validated
            string imageExtension = Path.GetExtension(uploadProfileImageRequest.File.FileName);

            if (!VALID_IMAGE_FORMATS.Contains(imageExtension.ToUpper()))
            {
                _logger.LogWarning($"Invalid image format. UserId {userId}, image extension {imageExtension}");
                return(Result.Fail(INVALID_PROFILE_IMAGE_FORMAT, VALID_IMAGE_FORMATS).ToOldResult());
            }

            if (uploadProfileImageRequest.File.Length > _identityUIOptions.MaxProfileImageSize)
            {
                _logger.LogWarning($"Image is to big. UserId {userId}, image size {uploadProfileImageRequest.File.Length}");
                return(Result.Fail(PROFILE_IMAGE_TOO_BIG, _identityUIOptions.MaxProfileImageSize / 1024).ToOldResult());
            }

            if (uploadProfileImageRequest.File.FileName.Length > 250)
            {
                _logger.LogWarning($"Image name is to long. Image name length {uploadProfileImageRequest.File.FileName.Length}");
                return(Result.Fail(PROFILE_IMAGE_NAME_TOO_LONG, 250).ToOldResult());
            }

            byte[] image;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                await uploadProfileImageRequest.File.CopyToAsync(memoryStream);

                image = memoryStream.ToArray();
            }

            string blobCacheKey = string.Format(BLOBL_CACHE_KEY, userId);
            string urlCacheKey  = string.Format(URL_CACHE_KEY, userId);

            _memoryCache.Remove(blobCacheKey);
            _memoryCache.Remove(urlCacheKey);

            IBaseSpecification <UserImageEntity, UserImageEntity> getUserImageSpecification = SpecificationBuilder
                                                                                              .Create <UserImageEntity>()
                                                                                              .Where(x => x.UserId == userId)
                                                                                              .Build();

            UserImageEntity userImage = await _userImageDAO.SingleOrDefault(getUserImageSpecification);

            if (userImage == null)
            {
                UserImageEntity newUserImage = new UserImageEntity(
                    userId: userId,
                    blobImage: image,
                    fileName: uploadProfileImageRequest.File.FileName);

                bool addResult = await _userImageDAO.Add(newUserImage);

                if (!addResult)
                {
                    _logger.LogError($"Failed to add user image. UserId {userId}");
                    return(Result.Fail(FAILED_TO_ADD_PROFILE_IMAGE).ToOldResult());
                }

                return(Result.Ok().ToOldResult());
            }

            userImage.BlobImage = image;
            userImage.FileName  = uploadProfileImageRequest.File.FileName;

            bool updateResult = await _userImageDAO.Update(userImage);

            if (!updateResult)
            {
                _logger.LogError($"Failed to update user image. UserId {userId}");
                return(Result.Fail(FAILED_TO_UPDATE_PROFILE_IMAGE).ToOldResult());
            }

            return(Result.Ok().ToOldResult());
        }