feat: добавил поддержку подписки на календарь и экспорт расписания лекций в формате .ics
Backend CI / build-and-test (push) Successful in 57s
Frontend CI / build-and-check (push) Failing after 26s
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Successful in 11s
🚀 Create and publish a Docker image / Build & publish backend image (push) Successful in 2m33s
🚀 Create and publish a Docker image / Build & publish frontend image (push) Successful in 33s
🚀 Create and publish a Docker image / Update stack on Portainer (push) Successful in 8s
Backend CI / build-and-test (push) Successful in 57s
Frontend CI / build-and-check (push) Failing after 26s
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Successful in 11s
🚀 Create and publish a Docker image / Build & publish backend image (push) Successful in 2m33s
🚀 Create and publish a Docker image / Build & publish frontend image (push) Successful in 33s
🚀 Create and publish a Docker image / Update stack on Portainer (push) Successful in 8s
This commit is contained in:
@@ -47,6 +47,9 @@ public class EndpointAuthorizationTests : IClassFixture<ApiWebApplicationFactory
|
||||
body: """{"displayName":"Test","avatarUrl":null}""");
|
||||
yield return E("users/me/stats [AnyAuth]", "GET", "api/v1/users/me/stats", "Student");
|
||||
yield return E("users/me/enrollments [AnyAuth]", "GET", "api/v1/users/me/enrollments", "Student");
|
||||
yield return E("users/me/enrollments/calendar-subscription [AnyAuth]", "GET", "api/v1/users/me/enrollments/calendar-subscription", "Student");
|
||||
yield return E("users/me/enrollments.ics [AnyAuth]", "GET", "api/v1/users/me/enrollments.ics", "Student");
|
||||
yield return E("users/me/enrollments/{id}.ics [AnyAuth]", "GET", "api/v1/users/me/enrollments/1.ics", "Student");
|
||||
yield return E("users/me/reviews [AnyAuth]", "GET", "api/v1/users/me/reviews", "Student");
|
||||
yield return E("users/me/achievements [AnyAuth]", "GET", "api/v1/users/me/achievements", "Student");
|
||||
yield return E("users/me/transactions [AnyAuth]", "GET", "api/v1/users/me/transactions", "Student");
|
||||
@@ -192,6 +195,7 @@ public class EndpointAuthorizationTests : IClassFixture<ApiWebApplicationFactory
|
||||
// dev login доступен в окружении Development
|
||||
yield return new object[] { "auth/login/dev POST", "POST", "api/v1/auth/login/dev",
|
||||
"""{"email":"test@test.com","displayName":"Test","role":"Student"}""" };
|
||||
yield return new object[] { "users/calendar/enrollments/{token}.ics GET", "GET", "api/v1/users/calendar/enrollments/bad-token.ics" };
|
||||
// refresh читает из cookie — возвращает 401, если нет cookie, но это не 401 от промежуточного ПО авторизации
|
||||
// (он возвращает 401 явно в теле действия, что отличается от Auth Challenge)
|
||||
// Мы тестируем это отдельно, чтобы убедиться, что заголовок JWT не требуется
|
||||
|
||||
@@ -20,6 +20,7 @@ using UniVerse.Application.DTOs.Tags;
|
||||
using UniVerse.Application.DTOs.Users;
|
||||
using UniVerse.Application.Interfaces;
|
||||
using UniVerse.Domain.Enums;
|
||||
using UniVerse.Domain.Exceptions;
|
||||
using UniVerse.Infrastructure.Data;
|
||||
|
||||
namespace UniVerse.Api.Tests.Helpers;
|
||||
@@ -177,6 +178,13 @@ public class ApiWebApplicationFactory : WebApplicationFactory<Program>
|
||||
3,
|
||||
[new EnrollmentSlotRuleDto(1, 3), new EnrollmentSlotRuleDto(3, 5), new EnrollmentSlotRuleDto(4, 7)]));
|
||||
stub.GetEnrollmentsAsync(Arg.Any<int>(), Arg.Any<PaginationRequest>()).Returns(pagedLectures);
|
||||
stub.GetMyEnrollmentsIcsAsync(Arg.Any<int>()).Returns("BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n");
|
||||
stub.GetEnrollmentIcsAsync(Arg.Any<int>(), Arg.Any<int>()).Returns("BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n");
|
||||
stub.GetCalendarSubscriptionTokenAsync(Arg.Any<int>()).Returns("test-token");
|
||||
stub.GetEnrollmentsIcsBySubscriptionTokenAsync("bad-token")
|
||||
.Returns(Task.FromException<string>(new ForbiddenException("Invalid calendar subscription token.")));
|
||||
stub.GetEnrollmentsIcsBySubscriptionTokenAsync(Arg.Is<string>(token => token != "bad-token"))
|
||||
.Returns(Task.FromResult("BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n"));
|
||||
stub.GetAllAsync(Arg.Any<UserFilterRequest>()).Returns(pagedUsers);
|
||||
stub.SetRolesAsync(Arg.Any<int>(), Arg.Any<IReadOnlyCollection<UserRole>>()).Returns(Task.CompletedTask);
|
||||
stub.SetActiveAsync(Arg.Any<int>(), Arg.Any<bool>()).Returns(Task.CompletedTask);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using UniVerse.Application.DTOs.Notifications;
|
||||
@@ -193,6 +194,56 @@ public class UserServiceTests
|
||||
Assert.Equal(2, Assert.Single(result.Items).Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CalendarSubscriptionToken_Roundtrip_ReturnsUserEnrollmentsIcs()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var startsAt = new DateTime(2026, 1, 10, 9, 0, 0, DateTimeKind.Utc);
|
||||
db.Users.Add(new User { Id = 1, Email = "student@test.local" });
|
||||
db.Courses.Add(new Course { Id = 1, Name = "Course" });
|
||||
db.Lectures.Add(Lecture(1, startsAt));
|
||||
db.LectureEnrollments.Add(new LectureEnrollment { LectureId = 1, UserId = 1 });
|
||||
await db.SaveChangesAsync();
|
||||
var service = CreateService(db);
|
||||
|
||||
var token = await service.GetCalendarSubscriptionTokenAsync(1);
|
||||
var ics = await service.GetEnrollmentsIcsBySubscriptionTokenAsync(token);
|
||||
|
||||
Assert.Contains("BEGIN:VCALENDAR", ics);
|
||||
Assert.Contains("Lecture 1", ics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CalendarSubscriptionToken_RejectsTamperedToken()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
db.Users.Add(new User { Id = 1, Email = "student@test.local" });
|
||||
await db.SaveChangesAsync();
|
||||
var service = CreateService(db);
|
||||
var token = await service.GetCalendarSubscriptionTokenAsync(1);
|
||||
var tampered = token[..^1] + (token[^1] == 'A' ? 'B' : 'A');
|
||||
|
||||
await Assert.ThrowsAsync<ForbiddenException>(() =>
|
||||
service.GetEnrollmentsIcsBySubscriptionTokenAsync(tampered));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEnrollmentIcsAsync_ReturnsLectureIcsWithoutEnrollment()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var startsAt = new DateTime(2026, 2, 10, 9, 0, 0, DateTimeKind.Utc);
|
||||
db.Users.Add(new User { Id = 1, Email = "student@test.local" });
|
||||
db.Courses.Add(new Course { Id = 1, Name = "Course" });
|
||||
db.Lectures.Add(Lecture(1853, startsAt));
|
||||
await db.SaveChangesAsync();
|
||||
var service = CreateService(db);
|
||||
|
||||
var ics = await service.GetEnrollmentIcsAsync(1, 1853);
|
||||
|
||||
Assert.Contains("BEGIN:VCALENDAR", ics);
|
||||
Assert.Contains("Lecture 1853", ics);
|
||||
}
|
||||
|
||||
private static AppDbContext CreateDbContext()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
@@ -215,7 +266,13 @@ public class UserServiceTests
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var gamification = new GamificationService(db, notifications, NullLogger<GamificationService>.Instance);
|
||||
return new UserService(db, gamification);
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Jwt:Secret"] = "test-calendar-subscription-secret-32chars"
|
||||
})
|
||||
.Build();
|
||||
return new UserService(db, gamification, config);
|
||||
}
|
||||
|
||||
private static void SeedLevelThresholds(AppDbContext db)
|
||||
|
||||
@@ -5,6 +5,7 @@ using UniVerse.Application.DTOs.Users;
|
||||
using UniVerse.Application.Interfaces;
|
||||
using UniVerse.Domain.Enums;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace UniVerse.Api.Controllers;
|
||||
|
||||
@@ -83,6 +84,52 @@ public class UsersController : ControllerBase
|
||||
public async Task<ActionResult> MyEnrollments([FromQuery] PaginationRequest pagination) =>
|
||||
Ok(await _users.GetEnrollmentsAsync(CurrentUserId, pagination));
|
||||
|
||||
[HttpGet("me/enrollments/calendar-subscription")]
|
||||
[ProducesResponseType(typeof(CalendarSubscriptionDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public async Task<ActionResult<CalendarSubscriptionDto>> CalendarSubscription()
|
||||
{
|
||||
var token = await _users.GetCalendarSubscriptionTokenAsync(CurrentUserId);
|
||||
var feedUrl = Url.Action(
|
||||
nameof(CalendarEnrollmentsIcs),
|
||||
null,
|
||||
new { token },
|
||||
Request.Scheme)
|
||||
?? $"{Request.Scheme}://{Request.Host}/api/v1/users/calendar/enrollments/{token}.ics";
|
||||
|
||||
return Ok(new CalendarSubscriptionDto(feedUrl));
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[HttpGet("calendar/enrollments/{token}.ics")]
|
||||
[Produces("text/calendar")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<FileContentResult> CalendarEnrollmentsIcs(string token)
|
||||
{
|
||||
var ics = await _users.GetEnrollmentsIcsBySubscriptionTokenAsync(token);
|
||||
return File(Encoding.UTF8.GetBytes(ics), "text/calendar; charset=utf-8", "my-lectures.ics");
|
||||
}
|
||||
|
||||
[HttpGet("me/enrollments.ics")]
|
||||
[Produces("text/calendar")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<FileContentResult> MyEnrollmentsIcs()
|
||||
{
|
||||
var ics = await _users.GetMyEnrollmentsIcsAsync(CurrentUserId);
|
||||
return File(Encoding.UTF8.GetBytes(ics), "text/calendar; charset=utf-8", "my-lectures.ics");
|
||||
}
|
||||
|
||||
[HttpGet("me/enrollments/{lectureId:int}.ics")]
|
||||
[Produces("text/calendar")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<FileContentResult> EnrollmentIcs(int lectureId)
|
||||
{
|
||||
var ics = await _users.GetEnrollmentIcsAsync(CurrentUserId, lectureId);
|
||||
return File(Encoding.UTF8.GetBytes(ics), "text/calendar; charset=utf-8", $"lecture-{lectureId}.ics");
|
||||
}
|
||||
|
||||
/// <summary>Получить отзывы текущего пользователя.</summary>
|
||||
/// <param name="pagination">Параметры пагинации.</param>
|
||||
/// <response code="200">Список отзывов (пагинированный).</response>
|
||||
|
||||
@@ -3789,6 +3789,146 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/users/me/enrollments/calendar-subscription": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"description": "**Required:** any authenticated user",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/CalendarSubscriptionDto"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"Bearer": [ ]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/users/calendar/enrollments/{token}.ics": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "token",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden",
|
||||
"content": {
|
||||
"text/calendar": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/users/me/enrollments.ics": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"description": "**Required:** any authenticated user",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized — JWT token missing or invalid"
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"Bearer": [ ]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/users/me/enrollments/{lectureId}.ics": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Users"
|
||||
],
|
||||
"description": "**Required:** any authenticated user",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "lectureId",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"format": "int32"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"404": {
|
||||
"description": "Not Found",
|
||||
"content": {
|
||||
"text/calendar": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized — JWT token missing or invalid"
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"Bearer": [ ]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/users/me/reviews": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -4843,6 +4983,16 @@
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"CalendarSubscriptionDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"feedUrl": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"CoinTransactionDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -51,6 +51,8 @@ public record AdminDashboardStatsDto(
|
||||
|
||||
public record EnrollmentSlotRuleDto(int Level, int Slots);
|
||||
|
||||
public record CalendarSubscriptionDto(string FeedUrl);
|
||||
|
||||
public record UpdateUserRequest(
|
||||
string? DisplayName,
|
||||
string? AvatarUrl
|
||||
|
||||
@@ -12,6 +12,10 @@ public interface IUserService
|
||||
Task<UserStatsDto> GetStatsAsync(int id);
|
||||
Task<AdminDashboardStatsDto> GetAdminDashboardStatsAsync();
|
||||
Task<PagedResult<LectureDto>> GetEnrollmentsAsync(int id, PaginationRequest pagination);
|
||||
Task<string> GetMyEnrollmentsIcsAsync(int userId);
|
||||
Task<string> GetEnrollmentIcsAsync(int userId, int lectureId);
|
||||
Task<string> GetCalendarSubscriptionTokenAsync(int userId);
|
||||
Task<string> GetEnrollmentsIcsBySubscriptionTokenAsync(string token);
|
||||
Task<PagedResult<UserDto>> GetAllAsync(UserFilterRequest filter);
|
||||
Task SetRolesAsync(int id, IReadOnlyCollection<UserRole> roles);
|
||||
Task SetActiveAsync(int id, bool isActive);
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Ical.Net;
|
||||
using Ical.Net.CalendarComponents;
|
||||
using Ical.Net.DataTypes;
|
||||
using Ical.Net.Serialization;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using UniVerse.Application.DTOs.Common;
|
||||
using UniVerse.Application.DTOs.Lectures;
|
||||
using UniVerse.Application.DTOs.Users;
|
||||
@@ -13,13 +21,20 @@ namespace UniVerse.Infrastructure.Services;
|
||||
|
||||
public class UserService : IUserService
|
||||
{
|
||||
private const byte CalendarTokenVersion = 1;
|
||||
private const int CalendarTokenPayloadLength = 5;
|
||||
private const int CalendarTokenSignatureLength = 32;
|
||||
private const string CalendarTokenKeyContext = "universe-calendar-subscription-v1";
|
||||
|
||||
private readonly AppDbContext _db;
|
||||
private readonly IGamificationService _gamification;
|
||||
private readonly IConfiguration _config;
|
||||
|
||||
public UserService(AppDbContext db, IGamificationService gamification)
|
||||
public UserService(AppDbContext db, IGamificationService gamification, IConfiguration config)
|
||||
{
|
||||
_db = db;
|
||||
_gamification = gamification;
|
||||
_config = config;
|
||||
}
|
||||
|
||||
public async Task<UserDto> GetByIdAsync(int id)
|
||||
@@ -115,6 +130,154 @@ public class UserService : IUserService
|
||||
pagination.PageSize);
|
||||
}
|
||||
|
||||
|
||||
public async Task<string> GetMyEnrollmentsIcsAsync(int userId)
|
||||
{
|
||||
if (!await _db.Users.AnyAsync(u => u.Id == userId))
|
||||
throw new NotFoundException("User", userId);
|
||||
|
||||
var lectures = await _db.LectureEnrollments
|
||||
.Where(e => e.UserId == userId)
|
||||
.Include(e => e.Lecture)
|
||||
.ThenInclude(l => l.Teacher)
|
||||
.Include(e => e.Lecture)
|
||||
.ThenInclude(l => l.Location)
|
||||
.OrderBy(e => e.Lecture.StartsAt)
|
||||
.Select(e => e.Lecture)
|
||||
.ToListAsync();
|
||||
|
||||
return BuildIcs(lectures, userId);
|
||||
}
|
||||
|
||||
public async Task<string> GetEnrollmentIcsAsync(int userId, int lectureId)
|
||||
{
|
||||
if (!await _db.Users.AnyAsync(u => u.Id == userId))
|
||||
throw new NotFoundException("User", userId);
|
||||
|
||||
var lecture = await _db.Lectures
|
||||
.Include(l => l.Teacher)
|
||||
.Include(l => l.Location)
|
||||
.FirstOrDefaultAsync(l => l.Id == lectureId)
|
||||
?? throw new NotFoundException("Lecture", lectureId);
|
||||
|
||||
return BuildIcs([lecture], userId);
|
||||
}
|
||||
|
||||
public async Task<string> GetCalendarSubscriptionTokenAsync(int userId)
|
||||
{
|
||||
if (!await _db.Users.AnyAsync(u => u.Id == userId))
|
||||
throw new NotFoundException("User", userId);
|
||||
|
||||
Span<byte> payload = stackalloc byte[CalendarTokenPayloadLength];
|
||||
payload[0] = CalendarTokenVersion;
|
||||
BinaryPrimitives.WriteInt32BigEndian(payload[1..], userId);
|
||||
|
||||
var signature = SignCalendarTokenPayload(payload);
|
||||
var tokenBytes = new byte[CalendarTokenPayloadLength + CalendarTokenSignatureLength];
|
||||
payload.CopyTo(tokenBytes);
|
||||
signature.CopyTo(tokenBytes.AsSpan(CalendarTokenPayloadLength));
|
||||
|
||||
return ToBase64Url(tokenBytes);
|
||||
}
|
||||
|
||||
public async Task<string> GetEnrollmentsIcsBySubscriptionTokenAsync(string token)
|
||||
{
|
||||
var userId = ValidateCalendarSubscriptionToken(token);
|
||||
return await GetMyEnrollmentsIcsAsync(userId);
|
||||
}
|
||||
|
||||
private int ValidateCalendarSubscriptionToken(string token)
|
||||
{
|
||||
var tokenBytes = FromBase64Url(token);
|
||||
if (tokenBytes.Length != CalendarTokenPayloadLength + CalendarTokenSignatureLength)
|
||||
throw new ForbiddenException("Invalid calendar subscription token.");
|
||||
|
||||
var payload = tokenBytes.AsSpan(0, CalendarTokenPayloadLength);
|
||||
var signature = tokenBytes.AsSpan(CalendarTokenPayloadLength, CalendarTokenSignatureLength);
|
||||
if (payload[0] != CalendarTokenVersion)
|
||||
throw new ForbiddenException("Invalid calendar subscription token.");
|
||||
|
||||
var expectedSignature = SignCalendarTokenPayload(payload);
|
||||
if (!CryptographicOperations.FixedTimeEquals(signature, expectedSignature))
|
||||
throw new ForbiddenException("Invalid calendar subscription token.");
|
||||
|
||||
var userId = BinaryPrimitives.ReadInt32BigEndian(payload[1..]);
|
||||
if (userId <= 0)
|
||||
throw new ForbiddenException("Invalid calendar subscription token.");
|
||||
|
||||
return userId;
|
||||
}
|
||||
|
||||
private byte[] SignCalendarTokenPayload(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
var calendarKey = DeriveCalendarTokenKey();
|
||||
return HMACSHA256.HashData(calendarKey, payload);
|
||||
}
|
||||
|
||||
private byte[] DeriveCalendarTokenKey()
|
||||
{
|
||||
var jwtSecret = _config["Jwt:Secret"];
|
||||
if (string.IsNullOrWhiteSpace(jwtSecret))
|
||||
throw new InvalidOperationException("Jwt:Secret is not configured.");
|
||||
|
||||
return HMACSHA256.HashData(
|
||||
Encoding.UTF8.GetBytes(jwtSecret),
|
||||
Encoding.UTF8.GetBytes(CalendarTokenKeyContext));
|
||||
}
|
||||
|
||||
private static string ToBase64Url(ReadOnlySpan<byte> bytes) =>
|
||||
Convert.ToBase64String(bytes)
|
||||
.TrimEnd('=')
|
||||
.Replace('+', '-')
|
||||
.Replace('/', '_');
|
||||
|
||||
private static byte[] FromBase64Url(string value)
|
||||
{
|
||||
try
|
||||
{
|
||||
var padded = value.Replace('-', '+').Replace('_', '/');
|
||||
padded = padded.PadRight(padded.Length + (4 - padded.Length % 4) % 4, '=');
|
||||
return Convert.FromBase64String(padded);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
throw new ForbiddenException("Invalid calendar subscription token.");
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildIcs(List<Domain.Entities.Lecture> lectures, int userId)
|
||||
{
|
||||
var calendar = new Calendar
|
||||
{
|
||||
Method = "PUBLISH",
|
||||
ProductId = "-//UniVerse//Lectures Calendar//EN"
|
||||
};
|
||||
|
||||
foreach (var lecture in lectures)
|
||||
{
|
||||
var location = lecture.Location is null
|
||||
? string.Empty
|
||||
: $"{lecture.Location.Building}{(string.IsNullOrWhiteSpace(lecture.Location.Room) ? string.Empty : $", ауд. {lecture.Location.Room}")}";
|
||||
|
||||
var teacherName = lecture.Teacher?.DisplayName
|
||||
?? lecture.Teacher?.Email
|
||||
?? "не указан";
|
||||
|
||||
calendar.Events.Add(new CalendarEvent
|
||||
{
|
||||
Uid = $"lecture-{lecture.Id}-user-{userId}@universe.local",
|
||||
Summary = lecture.Title,
|
||||
Description = $"{lecture.Description}\nПреподаватель: {teacherName}",
|
||||
Location = location,
|
||||
DtStart = new CalDateTime(DateTime.SpecifyKind(lecture.StartsAt, DateTimeKind.Utc)),
|
||||
DtEnd = new CalDateTime(DateTime.SpecifyKind(lecture.EndsAt, DateTimeKind.Utc)),
|
||||
DtStamp = new CalDateTime(DateTime.UtcNow)
|
||||
});
|
||||
}
|
||||
|
||||
return new CalendarSerializer().SerializeToString(calendar) ?? string.Empty;
|
||||
}
|
||||
|
||||
public async Task<PagedResult<UserDto>> GetAllAsync(UserFilterRequest filter)
|
||||
{
|
||||
var query = _db.Users.AsQueryable();
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.8" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.18.0" />
|
||||
<PackageReference Include="Quartz" Version="3.18.1" />
|
||||
<PackageReference Include="Ical.Net" Version="5.2.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in New Issue
Block a user