Beispiel #1
0
        public async Task <Result <AuditAdminDetailsModel> > Get(long id)
        {
            IBaseSpecification <AuditEntity, AuditAdminDetailsModel> selectSpecification = SpecificationBuilder
                                                                                           .Create <AuditEntity>()
                                                                                           .Where(x => x.Id == id)
                                                                                           .Select(x => new AuditAdminDetailsModel(
                                                                                                       x.Id,
                                                                                                       x.ActionType.GetDescription(),
                                                                                                       x.ObjectType,
                                                                                                       x.ObjectIdentifier,
                                                                                                       x.ObjectMetadata,
                                                                                                       x.SubjectType.GetDescription(),
                                                                                                       x.SubjectIdentifier,
                                                                                                       x.SubjectMetadata,
                                                                                                       x.GroupIdentifier,
                                                                                                       x.Host,
                                                                                                       x.RemoteIp,
                                                                                                       x.ResourceName,
                                                                                                       x.UserAgent,
                                                                                                       x.TraceIdentifier,
                                                                                                       x.AppVersion,
                                                                                                       x.Metadata,
                                                                                                       x.Created.ToString("o")))
                                                                                           .Build();

            AuditAdminDetailsModel auditDetailsModel = await _auditDAO.SingleOrDefault(selectSpecification);

            if (auditDetailsModel == null)
            {
                _logger.LogError($"No audit. AuditId {id}.");
                return(Result.Fail <AuditAdminDetailsModel>("no_audit", "No Audit"));
            }

            return(Result.Ok(auditDetailsModel));
        }
Beispiel #2
0
        private async Task <CommonUtils.Result.Result> AddToGlobalRole(AppUserEntity appUser, string roleId)
        {
            _logger.LogInformation($"Adding user to global role. UserId {appUser.Id}, RoleId {roleId}");

            IBaseSpecification <RoleEntity, RoleEntity> roleSpecification = SpecificationBuilder
                                                                            .Create <RoleEntity>()
                                                                            .Where(x => x.Id == roleId)
                                                                            .Where(x => x.Type == Data.Enums.Entity.RoleTypes.Global)
                                                                            .Build();

            RoleEntity role = await _roleDAO.SingleOrDefault(roleSpecification);

            if (role == null)
            {
                _logger.LogError($"No GlobalRole. RoleId {roleId}");
                return(CommonUtils.Result.Result.Fail(ROLE_NO_FOUND));
            }

            IdentityResult addResult = await _userManager.AddToRoleAsync(appUser, role.Name);

            if (!addResult.Succeeded)
            {
                _logger.LogError($"Failed to add role. UserId {appUser.Id}, RoleId {roleId}");
                return(CommonUtils.Result.Result.Fail(FAILED_TO_ADD_ROLE));
            }

            return(CommonUtils.Result.Result.Ok());
        }
Beispiel #3
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());
        }
        public async Task <Result <AuditDetailsModel> > Get(long id)
        {
            string userId = _httpContextAccessor.HttpContext.User.GetUserId();

            IBaseSpecification <AuditEntity, AuditDetailsModel> selectSpecification = SpecificationBuilder
                                                                                      .Create <AuditEntity>()
                                                                                      .Where(x => x.Id == id)
                                                                                      .WithUser(userId)
                                                                                      .Select(x => new AuditDetailsModel(
                                                                                                  x.Id,
                                                                                                  x.ActionType.GetDescription(),
                                                                                                  x.Created.ToString("o"),
                                                                                                  x.ResourceName,
                                                                                                  x.ObjectMetadata))
                                                                                      .Build();

            AuditDetailsModel auditDetailsModal = await _auditDAO.SingleOrDefault(selectSpecification);

            if (auditDetailsModal == null)
            {
                _logger.LogError($"No audit. AuditId {id}, UserId {userId}");
                return(Result.Fail <AuditDetailsModel>("no_audit", "No Audit"));
            }

            return(Result.Ok(auditDetailsModal));
        }
Beispiel #5
0
        private async Task <Result> AddAdminRole(string userId, string groupId)
        {
            IBaseSpecification <RoleEntity, RoleEntity> getGroupAdminRoleSpecification = SpecificationBuilder
                                                                                         .Create <RoleEntity>()
                                                                                         .Where(x => x.Type == Data.Enums.Entity.RoleTypes.Group)
                                                                                         .WithName(IdentityUIRoles.GROUP_ADMIN)
                                                                                         .Build();

            RoleEntity role = await _roleDAO.SingleOrDefault(getGroupAdminRoleSpecification);

            if (role == null)
            {
                _logger.LogError($"GroupAdmin role not found. RoleName {IdentityUIRoles.GROUP_ADMIN}");
                return(Result.Fail(ROLE_NOT_FOUND));
            }

            Result result = await _groupUserService.AddUserToGroupWithValidation(userId, groupId, role.Id);

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

            return(Result.Ok());
        }
Beispiel #6
0
        public Core.Models.Result.Result Remove(string id)
        {
            _logger.LogInformation($"Removing Invite. InviteId {id}");

            IBaseSpecification <InviteEntity, InviteEntity> specification = SpecificationBuilder
                                                                            .Create <InviteEntity>()
                                                                            .Where(x => x.Id == id)
                                                                            .Build();

            InviteEntity invite = _inviteDAO.SingleOrDefault(specification).Result;

            if (invite == null)
            {
                _logger.LogError($"No Invite. InviteId {id}");
                return(Result.Fail(INVITE_NOT_FOUND).ToOldResult());
            }

            return(Remove(invite).Result.ToOldResult());
        }
Beispiel #7
0
        public async Task <Result <TValue> > SingleOrDefault <TValue>(IBaseSpecification <GroupEntity, TValue> specification)
        {
            ApplayGroupFilter(specification);

            TValue group = await _groupDAO.SingleOrDefault(specification);

            if (group == null)
            {
                _logger.LogError($"Group not found");
                return(Result.Fail <TValue>(GROUP_NOT_FOUND));
            }

            return(Result.Ok(group));
        }
Beispiel #8
0
        private async Task <List <RoleListData> > GetRoleAssignments(string userId, string groupId)
        {
            IBaseSpecification <GroupUserEntity, RoleListData> getGroupRoleSpecification = SpecificationBuilder
                                                                                           .Create <GroupUserEntity>()
                                                                                           .Where(x => x.UserId == userId)
                                                                                           .Where(x => x.GroupId == groupId)
                                                                                           .Select(x => new RoleListData(
                                                                                                       x.Role.Id,
                                                                                                       x.Role.Name))
                                                                                           .Build();

            RoleListData role = await _groupUserDAO.SingleOrDefault(getGroupRoleSpecification);

            if (role == null)
            {
                _logger.LogInformation($"User has no groupRole. UserId {userId}, GroupId {groupId}");
                return(new List <RoleListData>());
            }

            IBaseSpecification <RoleAssignmentEntity, RoleListData> getRoleAssigmentsSpecification = SpecificationBuilder
                                                                                                     .Create <RoleAssignmentEntity>()
                                                                                                     .Where(x => x.RoleId == role.Id)
                                                                                                     .Select(x => new RoleListData(
                                                                                                                 x.CanAssigneRole.Id,
                                                                                                                 x.CanAssigneRole.Name))
                                                                                                     .Build();

            List <RoleListData> canAssigneRoles = await _roleAssignmentDAO.Get(getRoleAssigmentsSpecification);

            if (!canAssigneRoles.Any(x => x.Id == role.Id))
            {
                canAssigneRoles.Add(role);
            }

            return(canAssigneRoles);
        }
Beispiel #9
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());
        }