sledgemapper/Sledgemapper.Api/Handlers/BaseCommandHandler.cs
Michele Scandura 4fd77a1f17
Some checks failed
continuous-integration/drone/push Build is failing
working base entities creation
2021-09-20 15:16:43 +01:00

68 lines
2.2 KiB
C#

using MediatR;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Sledgemapper.Api.Models;
namespace Sledgemapper.Api.Handlers
{
public abstract class BaseCommandHandler<TRequest, TResponse> : IRequestHandler<TRequest, TResponse> where TRequest : BaseCommand<TResponse>
{
protected SledgemapperDbContext Dbcontext { get; }
protected IMediator Mediator { get; }
public abstract Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
public BaseCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext)
{
Dbcontext = dbcontext;
Mediator = mediator;
}
protected async Task CheckAuthorization(TRequest command)
{
var user = await Dbcontext.Users.FindAsync(command.UserId);
Dbcontext.Attach(user);
var campaign = await Dbcontext
.Campaigns
.Where(campaign => campaign.CampaignId == command.Campaign)
.Include(c => c.InvitedUsers)
.Include(c => c.Maps)
.Include(c => c.Owner)
.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).FirstAsync();
var maps = campaign.Maps.Any(s => s.SessionId == command.SessionId);
if (!maps)
{
throw new Exception("Unauthorized");
}
}
protected async Task<Session> SaveLog(TRequest command, string operation, string type, string data, CancellationToken cancellationToken)
{
var session = Dbcontext.Sessions.First(m => m.SessionId == command.SessionId);
Dbcontext.MapLogs.Add(new Models.MapLog
{
Operation = operation,
SessionId = session.SessionId,
Type = type,
Timestamp = command.Timestamp,
Object = data,
UserId = command.UserId,
});
await Dbcontext.SaveChangesAsync(cancellationToken);
return session;
}
}
}