using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Bit.Core.Enums; using Bit.Core.Models.Data.Organizations.Policies; using Bit.Core.Repositories; using Bit.Infrastructure.EntityFramework.Models; using Bit.Infrastructure.EntityFramework.Repositories.Queries; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace Bit.Infrastructure.EntityFramework.Repositories { public class PolicyRepository : Repository, IPolicyRepository { public PolicyRepository(IServiceScopeFactory serviceScopeFactory, IMapper mapper) : base(serviceScopeFactory, mapper, (DatabaseContext context) => context.Policies) { } public async Task GetByOrganizationIdTypeAsync(Guid organizationId, PolicyType type) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var results = await dbContext.Policies .FirstOrDefaultAsync(p => p.OrganizationId == organizationId && p.Type == type); return Mapper.Map(results); } } public async Task> GetManyByOrganizationIdAsync(Guid organizationId) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var results = await dbContext.Policies .Where(p => p.OrganizationId == organizationId) .ToListAsync(); return Mapper.Map>(results); } } public async Task> GetManyByUserIdAsync(Guid userId) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = new PolicyReadByUserIdQuery(userId); var results = await query.Run(dbContext).ToListAsync(); return Mapper.Map>(results); } } public async Task> GetManyByTypeApplicableToUserIdAsync(Guid userId, PolicyType policyType, OrganizationUserStatusType minStatus) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = new PolicyReadByTypeApplicableToUserQuery(userId, policyType, minStatus); var results = await query.Run(dbContext).ToListAsync(); return Mapper.Map>(results); } } public async Task GetCountByTypeApplicableToUserIdAsync(Guid userId, PolicyType policyType, OrganizationUserStatusType minStatus) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = new PolicyReadByTypeApplicableToUserQuery(userId, policyType, minStatus); return await GetCountFromQuery(query); } } } }