Skip to content

Commit aed85ad

Browse files
author
bird_egop
committed
Register User
1 parent 7bb3236 commit aed85ad

File tree

7 files changed

+130
-5
lines changed

7 files changed

+130
-5
lines changed

BusinessLogic/BusinessException.cs

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
namespace BusinessLogic;
2+
3+
public class BusinessException : Exception
4+
{
5+
public BusinessException(string message) : base(message)
6+
{
7+
}
8+
}

BusinessLogic/BusinessLogic.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
</ItemGroup>
1818

1919
<ItemGroup>
20-
<Folder Include="Mediatr" />
20+
<ProjectReference Include="..\DataAccess\DataAccess.csproj" />
2121
</ItemGroup>
2222

2323
</Project>

BusinessLogic/Mediatr/RegisterUser.cs

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
using DataAccess.Models;
2+
using DataAccess.RepositoryNew;
3+
using FluentValidation;
4+
using MediatR;
5+
using Microsoft.EntityFrameworkCore;
6+
7+
namespace BusinessLogic.Mediatr;
8+
9+
public static class RegisterUser
10+
{
11+
public record Command(string Email, string Password) : IRequest<Unit>;
12+
13+
public class CommandValidator : AbstractValidator<Command>
14+
{
15+
public CommandValidator()
16+
{
17+
RuleFor(x => x.Email)
18+
.NotEmpty()
19+
.EmailAddress();
20+
21+
RuleFor(x => x.Password)
22+
.NotEmpty()
23+
.Length(8, 50);
24+
}
25+
}
26+
27+
public class Handler : IRequestHandler<Command, Unit>
28+
{
29+
private readonly IRepository<AppUser> _repository;
30+
31+
public Handler(IRepository<AppUser> repository)
32+
{
33+
_repository = repository;
34+
}
35+
36+
public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
37+
{
38+
if (await _repository.GetAll()
39+
.AnyAsync(x => x.Email == request.Email, cancellationToken))
40+
{
41+
throw new BusinessException("Email уже занят");
42+
}
43+
44+
var appUser = new AppUser()
45+
{
46+
Email = request.Email,
47+
Password = request.Password,
48+
Username = ""
49+
};
50+
51+
await _repository.Add(appUser, cancellationToken);
52+
53+
return Unit.Value;
54+
}
55+
}
56+
}

BusinessLogic/ValidationBehavior.cs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using FluentValidation;
2+
using MediatR;
3+
4+
namespace BusinessLogic;
5+
6+
//all validators must ne inherited from abstract AbstractValidator<TValidator>
7+
8+
public class ValidationBehavior <TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
9+
where TRequest : IRequest<TResponse>
10+
{
11+
private readonly IEnumerable<IValidator<TRequest>> _validators;
12+
13+
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
14+
{
15+
_validators = validators;
16+
}
17+
18+
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
19+
{
20+
if (_validators.Any())
21+
{
22+
var context = new ValidationContext<TRequest>(request);
23+
var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellation: cancellationToken)));
24+
var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
25+
if (failures.Count != 0)
26+
throw new ValidationException(failures);
27+
}
28+
29+
return await next();
30+
}
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using BusinessLogic.Mediatr;
2+
using MediatR;
3+
using Microsoft.AspNetCore.Mvc;
4+
5+
namespace ProjectManager.Controllers;
6+
7+
[Route("[controller]/[action]")]
8+
[ProducesResponseType(typeof(ErrorDto), 400)]
9+
[Produces("application/json")]
10+
[ResponseCache(NoStore = true, Duration = 0)]
11+
public class AuthController : Controller
12+
{
13+
private readonly IMediator _mediator;
14+
15+
public AuthController(IMediator mediator)
16+
{
17+
_mediator = mediator;
18+
}
19+
20+
[HttpPost]
21+
[ProducesResponseType(200)]
22+
public async Task<ActionResult> Register([FromBody] RegisterUser.Command command, CancellationToken cancellationToken)
23+
{
24+
await _mediator.Send(command, cancellationToken);
25+
26+
return Ok();
27+
}
28+
}

ProjectManager/Middlewares/ExceptionCatcherMiddleware.cs

+6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Net;
2+
using FluentValidation;
23

34
namespace ProjectManager.Middlewares;
45

@@ -17,6 +18,11 @@ public async Task InvokeAsync(HttpContext context, ILogger<ExceptionCatcherMiddl
1718
{
1819
await _next(context);
1920
}
21+
catch (ValidationException ex)
22+
{
23+
context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
24+
await context.Response.WriteAsJsonAsync(new ErrorDto(string.Join("\n", ex.Errors.Select(x => x.ErrorMessage))));
25+
}
2026
catch (Exception ex)
2127
{
2228
logger.LogCritical(ex, "Unhandled Exception");

ProjectManager/ProjectManager.csproj

-4
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@
77
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
88
</PropertyGroup>
99

10-
<ItemGroup>
11-
<Folder Include="Controllers" />
12-
</ItemGroup>
13-
1410
<ItemGroup>
1511
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.9" />
1612
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.13" />

0 commit comments

Comments
 (0)