| | | 1 | | using Microsoft.AspNetCore.Authentication; |
| | | 2 | | using Microsoft.AspNetCore.Authorization; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 5 | | using OzonOrdersWeb.Authorization; |
| | | 6 | | using OzonOrdersWeb.Extensions; |
| | | 7 | | using Services.PartnerServices; |
| | | 8 | | |
| | | 9 | | namespace OzonOrdersWeb.Api.Partner; |
| | | 10 | | |
| | | 11 | | /// <summary>Почта партнёра. Пустое или неверное значение отвечает так же, как неизвестная почта: ответ не подсказывает, |
| | | 12 | | public sealed record PartnerEmailRequest(string? Email); |
| | | 13 | | |
| | | 14 | | /// <summary>Почта и код из письма (код входа или код из приглашения; пробелы в коде допустимы).</summary> |
| | | 15 | | public sealed record PartnerCodeVerifyRequest(string? Email, string? Code); |
| | | 16 | | |
| | | 17 | | /// <summary>Вход и выход партнёра в кабинет PartnerOffice. Отдельная cookie-схема, не связанная с Identity сотрудников. |
| | | 18 | | [ApiController] |
| | | 19 | | [ApiExplorerSettings(GroupName = PartnerOfficeExtensions.SwaggerDocName)] |
| | | 20 | | [ServiceEndpoint] |
| | | 21 | | [IgnoreAntiforgeryToken] |
| | | 22 | | [Route("partner-api/auth")] |
| | | 23 | | [EnableRateLimiting(AuthorizationExtensions.AuthRateLimitPolicy)] |
| | 0 | 24 | | public sealed class PartnerAuthController( |
| | 0 | 25 | | IPartnerAuthService auth, |
| | 0 | 26 | | IPartnerManagementService management) : ControllerBase |
| | | 27 | | { |
| | | 28 | | /// <summary>Название организации по почте. Всегда 200 и один формат ответа: для чужой почты name = null.</summary> |
| | | 29 | | [HttpPost("lookup")] |
| | | 30 | | [AllowAnonymous] |
| | | 31 | | [EnableRateLimiting(AuthorizationExtensions.PartnerLookupRateLimitPolicy)] |
| | | 32 | | public async Task<IActionResult> Lookup([FromBody] PartnerEmailRequest request, CancellationToken ct) |
| | | 33 | | { |
| | 0 | 34 | | Response.Headers.CacheControl = "no-store"; |
| | 0 | 35 | | var name = await auth.LookupNameByEmailAsync(request.Email ?? string.Empty, ct); |
| | 0 | 36 | | return Ok(new { name }); |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | /// <summary>Отправляет код входа на почту. Для неизвестной почты отвечает так же (202), письмо не уходит.</summary> |
| | | 40 | | [HttpPost("code/request")] |
| | | 41 | | [AllowAnonymous] |
| | | 42 | | public async Task<IActionResult> RequestCode([FromBody] PartnerEmailRequest request, CancellationToken ct) |
| | | 43 | | { |
| | 0 | 44 | | var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); |
| | 0 | 45 | | var result = await auth.RequestCodeAsync(request.Email ?? string.Empty, ip, ct); |
| | | 46 | | |
| | 0 | 47 | | switch (result.Status) |
| | | 48 | | { |
| | | 49 | | case PartnerCodeRequestStatus.Throttled: |
| | 0 | 50 | | Response.Headers.RetryAfter = result.RetryAfterSeconds.ToString(); |
| | 0 | 51 | | return StatusCode(StatusCodes.Status429TooManyRequests, new |
| | 0 | 52 | | { |
| | 0 | 53 | | error = $"Код уже отправлен. Повторить можно через {result.RetryAfterSeconds} с.", |
| | 0 | 54 | | retryAfterSeconds = result.RetryAfterSeconds |
| | 0 | 55 | | }); |
| | | 56 | | case PartnerCodeRequestStatus.Locked: |
| | 0 | 57 | | return StatusCode(StatusCodes.Status429TooManyRequests, new |
| | 0 | 58 | | { |
| | 0 | 59 | | error = "Слишком много неверных кодов. Повторите позже.", |
| | 0 | 60 | | lockedUntilUtc = result.LockedUntilUtc |
| | 0 | 61 | | }); |
| | | 62 | | case PartnerCodeRequestStatus.MailFailed: |
| | 0 | 63 | | return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "Не удалось отправить письмо. П |
| | | 64 | | default: |
| | 0 | 65 | | return Accepted(); |
| | | 66 | | } |
| | 0 | 67 | | } |
| | | 68 | | |
| | | 69 | | [HttpPost("code/verify")] |
| | | 70 | | [AllowAnonymous] |
| | | 71 | | public async Task<IActionResult> VerifyCode([FromBody] PartnerCodeVerifyRequest request, CancellationToken ct) |
| | | 72 | | { |
| | 0 | 73 | | var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); |
| | 0 | 74 | | var result = await auth.SignInWithCodeAsync(request.Email ?? string.Empty, request.Code ?? string.Empty, ip, ct) |
| | | 75 | | |
| | 0 | 76 | | switch (result.Status) |
| | | 77 | | { |
| | | 78 | | case PartnerLoginStatus.Success: |
| | 0 | 79 | | await HttpContext.SignInAsync( |
| | 0 | 80 | | PartnerOfficeExtensions.PartnerCookieScheme, |
| | 0 | 81 | | PartnerOfficeExtensions.CreatePartnerPrincipal(result.Partner!)); |
| | 0 | 82 | | return Ok(new { result.Partner!.Id, result.Partner.Name, result.Partner.Email }); |
| | | 83 | | case PartnerLoginStatus.Locked: |
| | 0 | 84 | | return StatusCode(StatusCodes.Status429TooManyRequests, new |
| | 0 | 85 | | { |
| | 0 | 86 | | error = "Слишком много неверных кодов. Повторите позже.", |
| | 0 | 87 | | lockedUntilUtc = result.LockedUntilUtc |
| | 0 | 88 | | }); |
| | | 89 | | default: |
| | | 90 | | // Отключённого партнёра и неверный код не различаем: ответ не должен раскрывать состояние учётной запис |
| | 0 | 91 | | return Unauthorized(new { error = "Неверный или просроченный код." }); |
| | | 92 | | } |
| | 0 | 93 | | } |
| | | 94 | | |
| | | 95 | | [HttpPost("logout")] |
| | | 96 | | [Authorize(AuthenticationSchemes = PartnerOfficeExtensions.PartnerCookieScheme)] |
| | | 97 | | public async Task<IActionResult> Logout() |
| | | 98 | | { |
| | 0 | 99 | | await HttpContext.SignOutAsync(PartnerOfficeExtensions.PartnerCookieScheme); |
| | 0 | 100 | | return NoContent(); |
| | 0 | 101 | | } |
| | | 102 | | |
| | | 103 | | [HttpGet("me")] |
| | | 104 | | [Authorize(AuthenticationSchemes = PartnerOfficeExtensions.PartnerCookieScheme)] |
| | | 105 | | public async Task<IActionResult> Me(CancellationToken ct) |
| | | 106 | | { |
| | 0 | 107 | | if (!User.TryGetPartnerId(out var id)) return Unauthorized(); |
| | 0 | 108 | | var partner = await management.GetAsync(id, ct); |
| | 0 | 109 | | return partner is null |
| | 0 | 110 | | ? Unauthorized() |
| | 0 | 111 | | : Ok(new { partner.Id, partner.Name, partner.Email, partner.Permissions }); |
| | 0 | 112 | | } |
| | | 113 | | } |