Skip to content

Commit

Permalink
Send email on register
Browse files Browse the repository at this point in the history
  • Loading branch information
zysim committed Oct 26, 2023
1 parent 1edd19c commit 2092848
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 16 deletions.
24 changes: 24 additions & 0 deletions LeaderboardBackend.Test/Features/Users/RegistrationTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
Expand All @@ -7,9 +8,12 @@
using LeaderboardBackend.Models.Entities;
using LeaderboardBackend.Models.Requests;
using LeaderboardBackend.Models.ViewModels;
using LeaderboardBackend.Services;
using LeaderboardBackend.Test.Fixtures;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;

namespace LeaderboardBackend.Test.Features.Users;
Expand Down Expand Up @@ -65,6 +69,26 @@ public async Task Register_InvalidEmailFormat_ReturnsErrorCode()
});
}

[Test]
public async Task Register_EmailFailedToSend_ReturnsErrorCode()
{
Mock<IEmailSender> emailSenderMock = new();
emailSenderMock.Setup(x =>
x.EnqueueEmailAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())
).Throws(new Exception());

HttpClient client = _factory.WithWebHostBuilder(builder =>
builder.ConfigureTestServices(services =>
services.AddScoped(_ => emailSenderMock.Object)
)
).CreateClient();
RegisterRequest request = _registerReqFaker.Generate();

HttpResponseMessage res = await client.PostAsJsonAsync(Routes.REGISTER, request);

res.Should().HaveStatusCode(HttpStatusCode.InternalServerError);
}

[Test]
public async Task Register_InvalidUsername_ReturnsUsernameFormatErrorCode()
{
Expand Down
43 changes: 27 additions & 16 deletions LeaderboardBackend/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public AccountController(IUserService userService)
/// <param name="request">
/// The `RegisterRequest` instance from which register the `User`.
/// </param>
/// <param name="confirmationService">The IConfirmationService dependency.</param>
/// <response code="201">The `User` was registered and returned successfully.</response>
/// <response code="400">
/// The request was malformed.
Expand Down Expand Up @@ -54,27 +55,37 @@ public AccountController(IUserService userService)
[ApiConventionMethod(typeof(Conventions), nameof(Conventions.PostAnon))]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status409Conflict, Type = typeof(ValidationProblemDetails))]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[FeatureGate(Features.ACCOUNT_REGISTRATION)]
public async Task<ActionResult<UserViewModel>> Register([FromBody] RegisterRequest request)
public async Task<ActionResult<UserViewModel>> Register(
[FromBody] RegisterRequest request,
[FromServices] IAccountConfirmationService confirmationService
)
{
CreateUserResult result = await _userService.CreateUser(request);
return result.Match<ActionResult<UserViewModel>>(
user => CreatedAtAction(nameof(UsersController.GetUserById), "Users",
new { id = user.Id }, UserViewModel.MapFrom(user)),
conflicts =>
{
if (conflicts.Username)
{
ModelState.AddModelError(nameof(request.Username), "UsernameTaken");
}

if (conflicts.Email)
{
ModelState.AddModelError(nameof(request.Email), "EmailAlreadyUsed");
}
if (result.TryPickT0(out User user, out CreateUserConflicts conflicts))
{
CreateConfirmationResult r = await confirmationService.CreateConfirmationAndSendEmail(user);

return r.Match<ActionResult>(
confirmation => Ok(),
badRole => StatusCode(StatusCodes.Status500InternalServerError),
emailFailed => StatusCode(StatusCodes.Status500InternalServerError)
);
}

if (conflicts.Username)
{
ModelState.AddModelError(nameof(request.Username), "UsernameTaken");
}

if (conflicts.Email)
{
ModelState.AddModelError(nameof(request.Email), "EmailAlreadyUsed");
}

return Conflict(new ValidationProblemDetails(ModelState));
});
return Conflict(new ValidationProblemDetails(ModelState));
}

/// <summary>
Expand Down
3 changes: 3 additions & 0 deletions LeaderboardBackend/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
}
}
},
"500": {
"description": "Server Error"
},
"400": {
"description": "The request was malformed."
},
Expand Down

0 comments on commit 2092848

Please sign in to comment.