| | | 1 | | using Microsoft.AspNetCore.Mvc; |
| | | 2 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using OzonRepositories.Context; |
| | | 5 | | |
| | | 6 | | namespace OzonOrdersWeb.Authorization; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Разрешает анонимный доступ к read-only страницам Studio2 при валидном ключе листа подбора (query accessKey). |
| | | 10 | | /// Аутентифицированные User/Admin проходят без ключа. |
| | | 11 | | /// </summary> |
| | | 12 | | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] |
| | | 13 | | public sealed class AssemblyListPublicAccessAttribute : Attribute, IAsyncAuthorizationFilter |
| | | 14 | | { |
| | | 15 | | public async Task OnAuthorizationAsync(AuthorizationFilterContext context) |
| | | 16 | | { |
| | 0 | 17 | | var user = context.HttpContext.User; |
| | 0 | 18 | | if (user.Identity?.IsAuthenticated == true |
| | 0 | 19 | | && (user.IsInRole("User") || user.IsInRole("Admin"))) |
| | | 20 | | { |
| | 0 | 21 | | return; |
| | | 22 | | } |
| | | 23 | | |
| | 0 | 24 | | var accessKey = context.HttpContext.Request.Query["accessKey"].ToString(); |
| | 0 | 25 | | if (string.IsNullOrWhiteSpace(accessKey)) |
| | | 26 | | { |
| | 0 | 27 | | context.Result = new ChallengeResult(); |
| | 0 | 28 | | return; |
| | | 29 | | } |
| | | 30 | | |
| | 0 | 31 | | var db = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>(); |
| | 0 | 32 | | var isValid = await db.AssemblyListAccessKeys.AsNoTracking().AnyAsync(k => |
| | 0 | 33 | | k.AccessKey == accessKey |
| | 0 | 34 | | && k.IsActive |
| | 0 | 35 | | && (k.ExpiresAt == null || k.ExpiresAt > DateTime.UtcNow)); |
| | | 36 | | |
| | 0 | 37 | | if (!isValid) |
| | 0 | 38 | | context.Result = new NotFoundResult(); |
| | 0 | 39 | | } |
| | | 40 | | } |