Добавьте файлы проекта.
This commit is contained in:
30
.dockerignore
Normal file
30
.dockerignore
Normal file
@@ -0,0 +1,30 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
!**/.gitignore
|
||||
!.git/HEAD
|
||||
!.git/config
|
||||
!.git/packed-refs
|
||||
!.git/refs/heads/**
|
||||
75
PlaylistShared.Api/Controllers/AccountController.cs
Normal file
75
PlaylistShared.Api/Controllers/AccountController.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using PlaylistShared.Api.Services;
|
||||
using PlaylistShared.Shared.DTO;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AccountController : ControllerBase
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly JwtService _jwtService;
|
||||
|
||||
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, JwtService jwtService)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
_jwtService = jwtService;
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
public async Task<ActionResult<ApiResponse<LoginResponse>>> Register(RegisterRequest request)
|
||||
{
|
||||
var user = new ApplicationUser
|
||||
{
|
||||
UserName = request.Username,
|
||||
Email = request.Email
|
||||
};
|
||||
var result = await _userManager.CreateAsync(user, request.Password);
|
||||
if (!result.Succeeded)
|
||||
return BadRequest(ApiResponse<LoginResponse>.Fail(new ErrorResponse
|
||||
{
|
||||
StatusCode = 400,
|
||||
Message = string.Join(", ", result.Errors.Select(e => e.Description))
|
||||
}));
|
||||
|
||||
return await GenerateTokenResponse(user);
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
public async Task<ActionResult<ApiResponse<LoginResponse>>> Login(LoginRequest request)
|
||||
{
|
||||
var user = await _userManager.FindByNameAsync(request.Username);
|
||||
if (user == null)
|
||||
return Unauthorized(ApiResponse<LoginResponse>.Fail(new ErrorResponse { StatusCode = 401, Message = "Неверное имя пользователя или пароль" }));
|
||||
|
||||
var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
|
||||
if (!result.Succeeded)
|
||||
return Unauthorized(ApiResponse<LoginResponse>.Fail(new ErrorResponse { StatusCode = 401, Message = "Неверное имя пользователя или пароль" }));
|
||||
|
||||
return await GenerateTokenResponse(user);
|
||||
}
|
||||
|
||||
private async Task<ActionResult<ApiResponse<LoginResponse>>> GenerateTokenResponse(ApplicationUser user)
|
||||
{
|
||||
var (token, refreshToken, expiration) = await _jwtService.GenerateTokenAsync(user);
|
||||
return Ok(ApiResponse<LoginResponse>.Ok(new LoginResponse
|
||||
{
|
||||
Token = token,
|
||||
RefreshToken = refreshToken,
|
||||
Expiration = expiration
|
||||
}));
|
||||
}
|
||||
|
||||
[HttpPost("refresh-token")]
|
||||
public async Task<ActionResult<ApiResponse<LoginResponse>>> RefreshToken([FromBody] RefreshTokenRequest request)
|
||||
{
|
||||
var user = _userManager.Users.FirstOrDefault(u => u.RefreshToken == request.RefreshToken && u.RefreshTokenExpiryUtc > DateTime.UtcNow);
|
||||
if (user == null)
|
||||
return Unauthorized(ApiResponse<LoginResponse>.Fail(new ErrorResponse { StatusCode = 401, Message = "Неверный или просроченный refresh token" }));
|
||||
|
||||
return await GenerateTokenResponse(user);
|
||||
}
|
||||
}
|
||||
76
PlaylistShared.Api/Controllers/OpenIdController.cs
Normal file
76
PlaylistShared.Api/Controllers/OpenIdController.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using PlaylistShared.Api.Services;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace PlaylistShared.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class OpenIdController : ControllerBase
|
||||
{
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly JwtService _jwtService;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public OpenIdController(
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
JwtService jwtService,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
_signInManager = signInManager;
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
[HttpGet("login")]
|
||||
public IActionResult Login(string? returnUrl = null)
|
||||
{
|
||||
var redirectUrl = Url.Action(nameof(Callback), "OpenId", new { returnUrl });
|
||||
var properties = _signInManager.ConfigureExternalAuthenticationProperties("Keycloak", redirectUrl);
|
||||
return Challenge(properties, "Keycloak");
|
||||
}
|
||||
|
||||
[HttpGet("callback")]
|
||||
public async Task<IActionResult> Callback(string? returnUrl = null, string? remoteError = null)
|
||||
{
|
||||
if (remoteError != null)
|
||||
return BadRequest($"Ошибка внешнего входа: {remoteError}");
|
||||
|
||||
var info = await _signInManager.GetExternalLoginInfoAsync();
|
||||
if (info == null)
|
||||
return BadRequest("Не удалось получить информацию от провайдера");
|
||||
|
||||
var email = info.Principal.FindFirst(ClaimTypes.Email)?.Value;
|
||||
var userName = info.Principal.FindFirst(ClaimTypes.Name)?.Value ?? email;
|
||||
|
||||
var user = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
|
||||
if (user == null)
|
||||
{
|
||||
user = await _userManager.FindByEmailAsync(email);
|
||||
if (user == null)
|
||||
{
|
||||
user = new ApplicationUser
|
||||
{
|
||||
UserName = userName,
|
||||
Email = email
|
||||
};
|
||||
var createResult = await _userManager.CreateAsync(user);
|
||||
if (!createResult.Succeeded)
|
||||
return BadRequest(createResult.Errors);
|
||||
}
|
||||
|
||||
var loginResult = await _userManager.AddLoginAsync(user, info);
|
||||
if (!loginResult.Succeeded)
|
||||
return BadRequest(loginResult.Errors);
|
||||
}
|
||||
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
var (token, refreshToken, _) = await _jwtService.GenerateTokenAsync(user);
|
||||
return Redirect($"{_configuration["Client:BaseUrl"]}/auth-callback?token={token}&refreshToken={refreshToken}");
|
||||
}
|
||||
}
|
||||
174
PlaylistShared.Api/Controllers/PlaylistController.cs
Normal file
174
PlaylistShared.Api/Controllers/PlaylistController.cs
Normal file
@@ -0,0 +1,174 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using PlaylistShared.Api.Extensions;
|
||||
using PlaylistShared.Api.Services;
|
||||
using PlaylistShared.Shared.DTO;
|
||||
using PlaylistShared.Shared.Enums;
|
||||
using PlaylistShared.Shared.Models;
|
||||
using YandexMusic;
|
||||
|
||||
namespace PlaylistShared.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize]
|
||||
public class PlaylistController : ControllerBase
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly SharedPlaylistService _sharedService;
|
||||
private readonly YandexMusicService _yandexService;
|
||||
private readonly TrackAdditionLogService _trackLogService;
|
||||
|
||||
public PlaylistController(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
SharedPlaylistService sharedService,
|
||||
YandexMusicService yandexService,
|
||||
TrackAdditionLogService trackLogService)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_sharedService = sharedService;
|
||||
_yandexService = yandexService;
|
||||
_trackLogService = trackLogService;
|
||||
}
|
||||
|
||||
[HttpPost("add-tracks")]
|
||||
public async Task<ActionResult<ApiResponse<object>>> AddTracks([FromBody] AddTrackRequest request)
|
||||
{
|
||||
var currentUserId = User.GetUserId();
|
||||
var playlist = await _sharedService.GetEntityByTokenAsync(request.SharedPlaylistToken);
|
||||
if (playlist == null)
|
||||
return NotFound(ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 404, Message = "Плейлист не найден" }));
|
||||
|
||||
if (!await _sharedService.CanAddTrackAsync(playlist, currentUserId))
|
||||
return StatusCode(403, ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 403, Message = "Недостаточно прав для добавления треков" }));
|
||||
|
||||
var creator = await _userManager.FindByIdAsync(playlist.CreatorUserId.ToString());
|
||||
if (creator == null)
|
||||
return StatusCode(500, ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 500, Message = "Владелец плейлиста не найден" }));
|
||||
|
||||
var updatedPlaylist = await _yandexService.AddTracksAsync(creator, playlist.YandexPlaylistOwnerUid, playlist.YandexPlaylistKind, request.TrackIds);
|
||||
if (updatedPlaylist == null)
|
||||
return StatusCode(500, ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 500, Message = "Ошибка при добавлении треков в Яндекс.Музыку" }));
|
||||
|
||||
// Логируем добавления для права AddedByUserOnly
|
||||
foreach (var trackId in request.TrackIds)
|
||||
await _trackLogService.LogAdditionAsync(playlist.Id, trackId, currentUserId);
|
||||
|
||||
return Ok(ApiResponse<object>.Ok(new { message = "Треки успешно добавлены" }));
|
||||
}
|
||||
|
||||
[HttpPost("remove-tracks")]
|
||||
public async Task<ActionResult<ApiResponse<object>>> RemoveTracks([FromBody] AddTrackRequest request)
|
||||
{
|
||||
var currentUserId = User.GetUserId();
|
||||
var playlist = await _sharedService.GetEntityByTokenAsync(request.SharedPlaylistToken);
|
||||
if (playlist == null)
|
||||
return NotFound(ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 404, Message = "Плейлист не найден" }));
|
||||
|
||||
// Проверяем права на удаление каждого трека
|
||||
foreach (var trackId in request.TrackIds)
|
||||
{
|
||||
if (!await _sharedService.CanRemoveTrackAsync(playlist, currentUserId, trackId))
|
||||
return StatusCode(403, ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 403, Message = $"Недостаточно прав для удаления трека {trackId}" }));
|
||||
}
|
||||
|
||||
var creator = await _userManager.FindByIdAsync(playlist.CreatorUserId.ToString());
|
||||
if (creator == null)
|
||||
return StatusCode(500, ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 500, Message = "Владелец плейлиста не найден" }));
|
||||
|
||||
var updatedPlaylist = await _yandexService.RemoveTracksAsync(creator, playlist.YandexPlaylistOwnerUid, playlist.YandexPlaylistKind, request.TrackIds);
|
||||
if (updatedPlaylist == null)
|
||||
return StatusCode(500, ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 500, Message = "Ошибка при удалении треков из Яндекс.Музыки" }));
|
||||
|
||||
// Удаляем логи добавления для этих треков
|
||||
foreach (var trackId in request.TrackIds)
|
||||
await _trackLogService.RemoveLogsForTrackAsync(playlist.Id, trackId);
|
||||
|
||||
return Ok(ApiResponse<object>.Ok(new { message = "Треки успешно удалены" }));
|
||||
}
|
||||
|
||||
[HttpGet("info/{ownerUid}/{kind}")]
|
||||
public async Task<ActionResult<ApiResponse<object>>> GetPlaylistInfo(string ownerUid, string kind)
|
||||
{
|
||||
var currentUserId = User.GetUserId();
|
||||
// Найти шеринг-плейлист по данным Яндекс
|
||||
var shared = await _sharedService.GetEntityByTokenAsync(null); // не можем по токену, надо по параметрам
|
||||
// Для простоты сделаем отдельный метод поиска по kind/ownerUid
|
||||
var playlistEntity = await _sharedService.GetByYandexIdsAsync(ownerUid, kind);
|
||||
if (playlistEntity == null)
|
||||
return NotFound(ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 404, Message = "Плейлист не найден" }));
|
||||
|
||||
if (!await _sharedService.CanViewAsync(playlistEntity, currentUserId))
|
||||
return Unauthorized();
|
||||
|
||||
var creator = await _userManager.FindByIdAsync(playlistEntity.CreatorUserId.ToString());
|
||||
var yandexPlaylist = await _yandexService.GetPlaylistAsync(creator, ownerUid, kind);
|
||||
return Ok(ApiResponse<object>.Ok(yandexPlaylist));
|
||||
}
|
||||
|
||||
[HttpGet("my")]
|
||||
public async Task<ActionResult<ApiResponse<List<YandexPlaylistInfo>>>> GetMyPlaylists()
|
||||
{
|
||||
var userId = User.GetUserId();
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString());
|
||||
if (user == null) return Unauthorized();
|
||||
|
||||
var decryptedToken = _yandexService.DecryptToken(user.YandexAccessToken);
|
||||
if (string.IsNullOrEmpty(decryptedToken))
|
||||
return BadRequest(ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 400, Message = "Токен Яндекс.Музыки не установлен или недействителен" }));
|
||||
|
||||
var yandexClient = new YandexMusicClient();
|
||||
var authSuccess = await yandexClient.Authorize(decryptedToken);
|
||||
if (!authSuccess)
|
||||
return BadRequest(ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 400, Message = "Не удалось авторизоваться в Яндекс.Музыке. Проверьте токен." }));
|
||||
|
||||
var favorites = await yandexClient.GetFavoritesAsync();
|
||||
var ownPlaylists = favorites.Where(p => p.Owner.Uid == yandexClient.Account.Uid).ToList();
|
||||
|
||||
var sharedPlaylists = await _sharedService.GetAllByUserAsync(userId);
|
||||
|
||||
var result = ownPlaylists.Select(p => new YandexPlaylistInfo
|
||||
{
|
||||
Kind = p.Kind,
|
||||
OwnerUid = p.Owner.Uid,
|
||||
Title = p.Title,
|
||||
CoverUrl = p.Cover?.GetUrl() ?? "",
|
||||
TrackCount = p.TrackCount,
|
||||
IsShared = sharedPlaylists.Any(s => s.YandexPlaylistKind == p.Kind && s.YandexPlaylistOwnerUid == p.Owner.Uid),
|
||||
ShareToken = sharedPlaylists.FirstOrDefault(s => s.YandexPlaylistKind == p.Kind && s.YandexPlaylistOwnerUid == p.Owner.Uid)?.ShareToken,
|
||||
}).ToList();
|
||||
|
||||
return Ok(ApiResponse<List<YandexPlaylistInfo>>.Ok(result));
|
||||
}
|
||||
|
||||
[HttpPost("share")]
|
||||
public async Task<ActionResult<ApiResponse<SharedPlaylistDto>>> SharePlaylist([FromBody] SharePlaylistRequest request)
|
||||
{
|
||||
var userId = User.GetUserId();
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString());
|
||||
if (user == null) return Unauthorized();
|
||||
|
||||
// Проверяем, что плейлист действительно принадлежит пользователю
|
||||
var yandexClient = new YandexMusicClient();
|
||||
await yandexClient.Authorize(_yandexService.DecryptToken(user.YandexAccessToken));
|
||||
var playlist = await yandexClient.GetPlaylistAsync(request.OwnerUid, request.Kind);
|
||||
if (playlist == null || playlist.Owner.Uid != yandexClient.Account.Uid)
|
||||
return BadRequest(ApiResponse<object>.Fail(new ErrorResponse { StatusCode = 400, Message = "Плейлист не принадлежит вам" }));
|
||||
|
||||
var dto = new SharePlaylistDto
|
||||
{
|
||||
YandexPlaylistKind = request.Kind,
|
||||
YandexPlaylistOwnerUid = request.OwnerUid,
|
||||
Title = playlist.Title,
|
||||
Description = playlist.Description,
|
||||
ViewPermission = ViewPermission.Everyone,
|
||||
AddPermission = EditPermission.AuthorizedOnly,
|
||||
RemovePermission = EditPermission.AddedByUserOnly
|
||||
};
|
||||
|
||||
var result = await _sharedService.CreateAsync(userId, dto);
|
||||
return Ok(ApiResponse<SharedPlaylistDto>.Ok(result));
|
||||
}
|
||||
}
|
||||
71
PlaylistShared.Api/Controllers/SharedPlaylistController.cs
Normal file
71
PlaylistShared.Api/Controllers/SharedPlaylistController.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlaylistShared.Api.Extensions;
|
||||
using PlaylistShared.Api.Services;
|
||||
using PlaylistShared.Shared.DTO;
|
||||
using PlaylistShared.Shared.Models;
|
||||
|
||||
namespace PlaylistShared.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class SharedPlaylistController : ControllerBase
|
||||
{
|
||||
private readonly SharedPlaylistService _sharedService;
|
||||
private readonly YandexMusicService _yandexService;
|
||||
|
||||
public SharedPlaylistController(SharedPlaylistService sharedService, YandexMusicService yandexService)
|
||||
{
|
||||
_sharedService = sharedService;
|
||||
_yandexService = yandexService;
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ApiResponse<SharedPlaylistDto>>> Create([FromBody] SharePlaylistDto dto)
|
||||
{
|
||||
var userId = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
||||
if (string.IsNullOrEmpty(userId) || !Guid.TryParse(userId, out var guid))
|
||||
return Unauthorized();
|
||||
|
||||
var result = await _sharedService.CreateAsync(guid, dto);
|
||||
return Ok(ApiResponse<SharedPlaylistDto>.Ok(result));
|
||||
}
|
||||
|
||||
[HttpGet("{token}")]
|
||||
public async Task<ActionResult<ApiResponse<SharedPlaylistDto>>> GetByToken(string token)
|
||||
{
|
||||
var playlist = await _sharedService.GetByTokenAsync(token);
|
||||
if (playlist == null)
|
||||
return NotFound(ApiResponse<SharedPlaylistDto>.Fail(new ErrorResponse { StatusCode = 404, Message = "Плейлист не найден" }));
|
||||
|
||||
var currentUserId = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
||||
var userIdGuid = !string.IsNullOrEmpty(currentUserId) ? Guid.Parse(currentUserId) : (Guid?)null;
|
||||
|
||||
// Проверка прав просмотра (требует доступа к сущности)
|
||||
var entity = await _sharedService.GetEntityByTokenAsync(token);
|
||||
if (entity == null || !await _sharedService.CanViewAsync(entity, userIdGuid))
|
||||
return Unauthorized(ApiResponse<SharedPlaylistDto>.Fail(new ErrorResponse { StatusCode = 401, Message = "Недостаточно прав" }));
|
||||
|
||||
return Ok(ApiResponse<SharedPlaylistDto>.Ok(playlist));
|
||||
}
|
||||
|
||||
[HttpPut("{token}/permissions")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ApiResponse<SharedPlaylistDto>>> UpdatePermissions(string token, [FromBody] UpdatePermissionsDto dto)
|
||||
{
|
||||
var userId = User.GetUserId();
|
||||
var playlist = await _sharedService.GetEntityByTokenAsync(token);
|
||||
if (playlist == null)
|
||||
return NotFound(ApiResponse<SharedPlaylistDto>.Fail(new ErrorResponse { StatusCode = 404, Message = "Плейлист не найден" }));
|
||||
|
||||
if (playlist.CreatorUserId != userId)
|
||||
return Forbid();
|
||||
|
||||
var updated = await _sharedService.UpdatePermissionsAsync(playlist.Id, dto);
|
||||
if (updated == null)
|
||||
return BadRequest(ApiResponse<SharedPlaylistDto>.Fail(new ErrorResponse { StatusCode = 400, Message = "Ошибка обновления прав" }));
|
||||
|
||||
return Ok(ApiResponse<SharedPlaylistDto>.Ok(updated));
|
||||
}
|
||||
}
|
||||
57
PlaylistShared.Api/Controllers/YandexTokenController.cs
Normal file
57
PlaylistShared.Api/Controllers/YandexTokenController.cs
Normal file
@@ -0,0 +1,57 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using PlaylistShared.Api.Extensions;
|
||||
using PlaylistShared.Api.Services;
|
||||
using PlaylistShared.Shared.DTO;
|
||||
|
||||
namespace PlaylistShared.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize]
|
||||
public class YandexTokenController : ControllerBase
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly YandexMusicService _yandexService;
|
||||
|
||||
public YandexTokenController(UserManager<ApplicationUser> userManager, YandexMusicService yandexService)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_yandexService = yandexService;
|
||||
}
|
||||
|
||||
[HttpPost("set")]
|
||||
public async Task<ActionResult<ApiResponse<object>>> SetToken([FromBody] SetYandexTokenRequest request)
|
||||
{
|
||||
var userId = User.GetUserId();
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString());
|
||||
if (user == null) return Unauthorized();
|
||||
|
||||
user.YandexAccessToken = _yandexService.EncryptToken(request.Token);
|
||||
// Не храним refresh-токен, так как пользователь вводит только access-токен
|
||||
user.YandexTokenExpiryUtc = DateTime.UtcNow.AddMonths(1); // условно, т.к. срок жизни токена неизвестен
|
||||
await _userManager.UpdateAsync(user);
|
||||
|
||||
return Ok(ApiResponse<object>.Ok(new { message = "Токен сохранён" }));
|
||||
}
|
||||
|
||||
[HttpGet("status")]
|
||||
public async Task<ActionResult<ApiResponse<YandexTokenStatus>>> GetStatus()
|
||||
{
|
||||
var userId = User.GetUserId();
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString());
|
||||
if (user == null) return Unauthorized();
|
||||
|
||||
var hasToken = !string.IsNullOrEmpty(user.YandexAccessToken);
|
||||
var isValid = hasToken && user.YandexTokenExpiryUtc > DateTime.UtcNow;
|
||||
|
||||
return Ok(ApiResponse<YandexTokenStatus>.Ok(new YandexTokenStatus
|
||||
{
|
||||
HasToken = hasToken,
|
||||
IsValid = isValid,
|
||||
ExpiryUtc = user.YandexTokenExpiryUtc
|
||||
}));
|
||||
}
|
||||
}
|
||||
46
PlaylistShared.Api/Data/ApplicationDbContext.cs
Normal file
46
PlaylistShared.Api/Data/ApplicationDbContext.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PlaylistShared.Api.Entities;
|
||||
|
||||
namespace PlaylistShared.Api.Data;
|
||||
|
||||
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid>
|
||||
{
|
||||
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
|
||||
|
||||
public DbSet<SharedPlaylistEntity> SharedPlaylists => Set<SharedPlaylistEntity>();
|
||||
public DbSet<TrackAdditionLogEntity> TrackAdditionLogs => Set<TrackAdditionLogEntity>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
base.OnModelCreating(builder);
|
||||
|
||||
builder.Entity<SharedPlaylistEntity>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => e.ShareToken).IsUnique();
|
||||
entity.HasOne(e => e.Creator)
|
||||
.WithMany(u => u.OwnedPlaylists)
|
||||
.HasForeignKey(e => e.CreatorUserId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
entity.Property(e => e.YandexPlaylistKind).IsRequired().HasMaxLength(50);
|
||||
entity.Property(e => e.YandexPlaylistOwnerUid).IsRequired().HasMaxLength(50);
|
||||
entity.Property(e => e.Title).IsRequired().HasMaxLength(255);
|
||||
});
|
||||
|
||||
builder.Entity<TrackAdditionLogEntity>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.HasIndex(e => new { e.SharedPlaylistId, e.TrackId });
|
||||
entity.HasOne(e => e.SharedPlaylist)
|
||||
.WithMany(sp => sp.TrackAdditionLogs)
|
||||
.HasForeignKey(e => e.SharedPlaylistId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
entity.HasOne(e => e.AddedByUser)
|
||||
.WithMany()
|
||||
.HasForeignKey(e => e.AddedByUserId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
});
|
||||
}
|
||||
}
|
||||
426
PlaylistShared.Api/Data/Migrations/20260412171234_InitialCreate.Designer.cs
generated
Normal file
426
PlaylistShared.Api/Data/Migrations/20260412171234_InitialCreate.Designer.cs
generated
Normal file
@@ -0,0 +1,426 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using PlaylistShared.Api.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PlaylistShared.Api.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20260412171234_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.5")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("RoleNameIndex")
|
||||
.HasFilter("[NormalizedName] IS NOT NULL");
|
||||
|
||||
b.ToTable("AspNetRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("AspNetRoleClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("AspNetUserClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("ProviderKey")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("ProviderDisplayName")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("LoginProvider", "ProviderKey");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("AspNetUserLogins", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("AspNetUserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.HasKey("UserId", "LoginProvider", "Name");
|
||||
|
||||
b.ToTable("AspNetUserTokens", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("RefreshToken")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTime>("RefreshTokenExpiryUtc")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("UserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("YandexAccessToken")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("YandexId")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("YandexRefreshToken")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTime>("YandexTokenExpiryUtc")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
||||
b.HasIndex("NormalizedUserName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UserNameIndex")
|
||||
.HasFilter("[NormalizedUserName] IS NOT NULL");
|
||||
|
||||
b.ToTable("AspNetUsers", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.SharedPlaylistEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<int>("AddPermission")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("CoverUrl")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<Guid>("CreatorUserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<int>("RemovePermission")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("nvarchar(255)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ViewPermission")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("YandexPlaylistKind")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.Property<string>("YandexPlaylistOwnerUid")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatorUserId");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("SharedPlaylists");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.TrackAdditionLogEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<DateTime>("AddedAtUtc")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<Guid>("AddedByUserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<Guid>("SharedPlaylistId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("TrackId")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AddedByUserId");
|
||||
|
||||
b.HasIndex("SharedPlaylistId", "TrackId");
|
||||
|
||||
b.ToTable("TrackAdditionLogs");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.SharedPlaylistEntity", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", "Creator")
|
||||
.WithMany("OwnedPlaylists")
|
||||
.HasForeignKey("CreatorUserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Creator");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.TrackAdditionLogEntity", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", "AddedByUser")
|
||||
.WithMany()
|
||||
.HasForeignKey("AddedByUserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PlaylistShared.Api.Entities.SharedPlaylistEntity", "SharedPlaylist")
|
||||
.WithMany("TrackAdditionLogs")
|
||||
.HasForeignKey("SharedPlaylistId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("AddedByUser");
|
||||
|
||||
b.Navigation("SharedPlaylist");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Navigation("OwnedPlaylists");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.SharedPlaylistEntity", b =>
|
||||
{
|
||||
b.Navigation("TrackAdditionLogs");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PlaylistShared.Api.Data.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AspNetRoles",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
|
||||
NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
|
||||
ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AspNetUsers",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
YandexId = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
YandexAccessToken = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
YandexRefreshToken = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
YandexTokenExpiryUtc = table.Column<DateTime>(type: "datetime2", nullable: false),
|
||||
RefreshToken = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
RefreshTokenExpiryUtc = table.Column<DateTime>(type: "datetime2", nullable: false),
|
||||
UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
|
||||
NormalizedUserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
|
||||
Email = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
|
||||
NormalizedEmail = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
|
||||
EmailConfirmed = table.Column<bool>(type: "bit", nullable: false),
|
||||
PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
SecurityStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
PhoneNumberConfirmed = table.Column<bool>(type: "bit", nullable: false),
|
||||
TwoFactorEnabled = table.Column<bool>(type: "bit", nullable: false),
|
||||
LockoutEnd = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
|
||||
LockoutEnabled = table.Column<bool>(type: "bit", nullable: false),
|
||||
AccessFailedCount = table.Column<int>(type: "int", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AspNetRoleClaims",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
RoleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
|
||||
column: x => x.RoleId,
|
||||
principalTable: "AspNetRoles",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AspNetUserClaims",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AspNetUserLogins",
|
||||
columns: table => new
|
||||
{
|
||||
LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false),
|
||||
ProviderKey = table.Column<string>(type: "nvarchar(450)", nullable: false),
|
||||
ProviderDisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
|
||||
table.ForeignKey(
|
||||
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AspNetUserRoles",
|
||||
columns: table => new
|
||||
{
|
||||
UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
RoleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
|
||||
table.ForeignKey(
|
||||
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
|
||||
column: x => x.RoleId,
|
||||
principalTable: "AspNetRoles",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AspNetUserTokens",
|
||||
columns: table => new
|
||||
{
|
||||
UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false),
|
||||
Name = table.Column<string>(type: "nvarchar(450)", nullable: false),
|
||||
Value = table.Column<string>(type: "nvarchar(max)", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
|
||||
table.ForeignKey(
|
||||
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "SharedPlaylists",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
CreatorUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
YandexPlaylistKind = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
|
||||
YandexPlaylistOwnerUid = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
|
||||
Title = table.Column<string>(type: "nvarchar(255)", maxLength: 255, nullable: false),
|
||||
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
CoverUrl = table.Column<string>(type: "nvarchar(max)", nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
|
||||
UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
|
||||
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
|
||||
ShareToken = table.Column<string>(type: "nvarchar(450)", nullable: false),
|
||||
ViewPermission = table.Column<int>(type: "int", nullable: false),
|
||||
AddPermission = table.Column<int>(type: "int", nullable: false),
|
||||
RemovePermission = table.Column<int>(type: "int", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_SharedPlaylists", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_SharedPlaylists_AspNetUsers_CreatorUserId",
|
||||
column: x => x.CreatorUserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "TrackAdditionLogs",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
SharedPlaylistId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
TrackId = table.Column<string>(type: "nvarchar(450)", nullable: false),
|
||||
AddedByUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
|
||||
AddedAtUtc = table.Column<DateTime>(type: "datetime2", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_TrackAdditionLogs", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_TrackAdditionLogs_AspNetUsers_AddedByUserId",
|
||||
column: x => x.AddedByUserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
table.ForeignKey(
|
||||
name: "FK_TrackAdditionLogs_SharedPlaylists_SharedPlaylistId",
|
||||
column: x => x.SharedPlaylistId,
|
||||
principalTable: "SharedPlaylists",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AspNetRoleClaims_RoleId",
|
||||
table: "AspNetRoleClaims",
|
||||
column: "RoleId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "RoleNameIndex",
|
||||
table: "AspNetRoles",
|
||||
column: "NormalizedName",
|
||||
unique: true,
|
||||
filter: "[NormalizedName] IS NOT NULL");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AspNetUserClaims_UserId",
|
||||
table: "AspNetUserClaims",
|
||||
column: "UserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AspNetUserLogins_UserId",
|
||||
table: "AspNetUserLogins",
|
||||
column: "UserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AspNetUserRoles_RoleId",
|
||||
table: "AspNetUserRoles",
|
||||
column: "RoleId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "EmailIndex",
|
||||
table: "AspNetUsers",
|
||||
column: "NormalizedEmail");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "UserNameIndex",
|
||||
table: "AspNetUsers",
|
||||
column: "NormalizedUserName",
|
||||
unique: true,
|
||||
filter: "[NormalizedUserName] IS NOT NULL");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_SharedPlaylists_CreatorUserId",
|
||||
table: "SharedPlaylists",
|
||||
column: "CreatorUserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_SharedPlaylists_ShareToken",
|
||||
table: "SharedPlaylists",
|
||||
column: "ShareToken",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_TrackAdditionLogs_AddedByUserId",
|
||||
table: "TrackAdditionLogs",
|
||||
column: "AddedByUserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_TrackAdditionLogs_SharedPlaylistId_TrackId",
|
||||
table: "TrackAdditionLogs",
|
||||
columns: new[] { "SharedPlaylistId", "TrackId" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "AspNetRoleClaims");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AspNetUserClaims");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AspNetUserLogins");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AspNetUserRoles");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AspNetUserTokens");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "TrackAdditionLogs");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AspNetRoles");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "SharedPlaylists");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using PlaylistShared.Api.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PlaylistShared.Api.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.5")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("RoleNameIndex")
|
||||
.HasFilter("[NormalizedName] IS NOT NULL");
|
||||
|
||||
b.ToTable("AspNetRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("AspNetRoleClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("AspNetUserClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("ProviderKey")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("ProviderDisplayName")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("LoginProvider", "ProviderKey");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("AspNetUserLogins", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("AspNetUserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.HasKey("UserId", "LoginProvider", "Name");
|
||||
|
||||
b.ToTable("AspNetUserTokens", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("RefreshToken")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTime>("RefreshTokenExpiryUtc")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("UserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
|
||||
b.Property<string>("YandexAccessToken")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("YandexId")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("YandexRefreshToken")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTime>("YandexTokenExpiryUtc")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
||||
b.HasIndex("NormalizedUserName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UserNameIndex")
|
||||
.HasFilter("[NormalizedUserName] IS NOT NULL");
|
||||
|
||||
b.ToTable("AspNetUsers", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.SharedPlaylistEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<int>("AddPermission")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("CoverUrl")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<Guid>("CreatorUserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<int>("RemovePermission")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("nvarchar(255)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ViewPermission")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("YandexPlaylistKind")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.Property<string>("YandexPlaylistOwnerUid")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatorUserId");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("SharedPlaylists");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.TrackAdditionLogEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<DateTime>("AddedAtUtc")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<Guid>("AddedByUserId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<Guid>("SharedPlaylistId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("TrackId")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(450)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AddedByUserId");
|
||||
|
||||
b.HasIndex("SharedPlaylistId", "TrackId");
|
||||
|
||||
b.ToTable("TrackAdditionLogs");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.SharedPlaylistEntity", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", "Creator")
|
||||
.WithMany("OwnedPlaylists")
|
||||
.HasForeignKey("CreatorUserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Creator");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.TrackAdditionLogEntity", b =>
|
||||
{
|
||||
b.HasOne("PlaylistShared.Api.Entities.ApplicationUser", "AddedByUser")
|
||||
.WithMany()
|
||||
.HasForeignKey("AddedByUserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PlaylistShared.Api.Entities.SharedPlaylistEntity", "SharedPlaylist")
|
||||
.WithMany("TrackAdditionLogs")
|
||||
.HasForeignKey("SharedPlaylistId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("AddedByUser");
|
||||
|
||||
b.Navigation("SharedPlaylist");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Navigation("OwnedPlaylists");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PlaylistShared.Api.Entities.SharedPlaylistEntity", b =>
|
||||
{
|
||||
b.Navigation("TrackAdditionLogs");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
31
PlaylistShared.Api/Dockerfile
Normal file
31
PlaylistShared.Api/Dockerfile
Normal file
@@ -0,0 +1,31 @@
|
||||
# См. статью по ссылке https://aka.ms/customizecontainer, чтобы узнать как настроить контейнер отладки и как Visual Studio использует этот Dockerfile для создания образов для ускорения отладки.
|
||||
|
||||
# Этот этап используется при запуске из VS в быстром режиме (по умолчанию для конфигурации отладки)
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
|
||||
USER $APP_UID
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
EXPOSE 8081
|
||||
|
||||
|
||||
# Этот этап используется для сборки проекта службы
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["nuget.config", "."]
|
||||
COPY ["PlaylistShared.Api/PlaylistShared.Api.csproj", "PlaylistShared.Api/"]
|
||||
RUN dotnet restore "./PlaylistShared.Api/PlaylistShared.Api.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/PlaylistShared.Api"
|
||||
RUN dotnet build "./PlaylistShared.Api.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
# Этот этап используется для публикации проекта службы, который будет скопирован на последний этап
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./PlaylistShared.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
# Этот этап используется в рабочей среде или при запуске из VS в обычном режиме (по умолчанию, когда конфигурация отладки не используется)
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "PlaylistShared.Api.dll"]
|
||||
28
PlaylistShared.Api/Entities/ApplicationUser.cs
Normal file
28
PlaylistShared.Api/Entities/ApplicationUser.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace PlaylistShared.Api.Entities;
|
||||
|
||||
/// <summary>Пользователь приложения (расширяет IdentityUser).</summary>
|
||||
public class ApplicationUser : IdentityUser<Guid>
|
||||
{
|
||||
/// <summary>Идентификатор пользователя в Яндексе (если привязан).</summary>
|
||||
public string? YandexId { get; set; }
|
||||
|
||||
/// <summary>Access токен Яндекс.Музыки (зашифрованный).</summary>
|
||||
public string? YandexAccessToken { get; set; }
|
||||
|
||||
/// <summary>Refresh токен Яндекс.Музыки (зашифрованный).</summary>
|
||||
public string? YandexRefreshToken { get; set; }
|
||||
|
||||
/// <summary>Время истечения access токена Яндекса.</summary>
|
||||
public DateTime YandexTokenExpiryUtc { get; set; }
|
||||
|
||||
/// <summary>Refresh токен для JWT (хранится в БД).</summary>
|
||||
public string? RefreshToken { get; set; }
|
||||
|
||||
/// <summary>Время истечения refresh токена JWT.</summary>
|
||||
public DateTime RefreshTokenExpiryUtc { get; set; }
|
||||
|
||||
/// <summary>Плейлисты, созданные пользователем.</summary>
|
||||
public ICollection<SharedPlaylistEntity> OwnedPlaylists { get; set; } = new List<SharedPlaylistEntity>();
|
||||
}
|
||||
26
PlaylistShared.Api/Entities/SharedPlaylistEntity.cs
Normal file
26
PlaylistShared.Api/Entities/SharedPlaylistEntity.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using PlaylistShared.Shared.Enums;
|
||||
|
||||
namespace PlaylistShared.Api.Entities;
|
||||
|
||||
/// <summary>Сущность шеринг-плейлиста (таблица в БД).</summary>
|
||||
public class SharedPlaylistEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid CreatorUserId { get; set; }
|
||||
public string YandexPlaylistKind { get; set; } = null!;
|
||||
public string YandexPlaylistOwnerUid { get; set; } = null!;
|
||||
public string Title { get; set; } = null!;
|
||||
public string? Description { get; set; }
|
||||
public string? CoverUrl { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
public bool IsDeleted { get; set; }
|
||||
public string ShareToken { get; set; } = null!;
|
||||
public ViewPermission ViewPermission { get; set; }
|
||||
public EditPermission AddPermission { get; set; }
|
||||
public EditPermission RemovePermission { get; set; }
|
||||
|
||||
// Навигационные свойства
|
||||
public ApplicationUser Creator { get; set; } = null!;
|
||||
public ICollection<TrackAdditionLogEntity> TrackAdditionLogs { get; set; } = new List<TrackAdditionLogEntity>();
|
||||
}
|
||||
15
PlaylistShared.Api/Entities/TrackAdditionLogEntity.cs
Normal file
15
PlaylistShared.Api/Entities/TrackAdditionLogEntity.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace PlaylistShared.Api.Entities;
|
||||
|
||||
/// <summary>Лог добавления трека (таблица в БД).</summary>
|
||||
public class TrackAdditionLogEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid SharedPlaylistId { get; set; }
|
||||
public string TrackId { get; set; } = null!;
|
||||
public Guid AddedByUserId { get; set; }
|
||||
public DateTime AddedAtUtc { get; set; }
|
||||
|
||||
// Навигационные свойства
|
||||
public SharedPlaylistEntity SharedPlaylist { get; set; } = null!;
|
||||
public ApplicationUser AddedByUser { get; set; } = null!;
|
||||
}
|
||||
20
PlaylistShared.Api/Extensions/ClaimsPrincipalExtensions.cs
Normal file
20
PlaylistShared.Api/Extensions/ClaimsPrincipalExtensions.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace PlaylistShared.Api.Extensions;
|
||||
|
||||
public static class ClaimsPrincipalExtensions
|
||||
{
|
||||
public static Guid GetUserId(this ClaimsPrincipal user)
|
||||
{
|
||||
var id = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (string.IsNullOrEmpty(id))
|
||||
throw new UnauthorizedAccessException("User ID not found");
|
||||
return Guid.Parse(id);
|
||||
}
|
||||
|
||||
public static Guid? GetUserIdOrNull(this ClaimsPrincipal user)
|
||||
{
|
||||
var id = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
return string.IsNullOrEmpty(id) ? null : Guid.Parse(id);
|
||||
}
|
||||
}
|
||||
19
PlaylistShared.Api/Extensions/YCoverExtensions.cs
Normal file
19
PlaylistShared.Api/Extensions/YCoverExtensions.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using YandexMusic.API.Models.Common.Cover;
|
||||
|
||||
namespace PlaylistShared.Api.Extensions;
|
||||
|
||||
public static class YCoverExtensions
|
||||
{
|
||||
public static string GetUrl(this YCover cover, string size = "200x200")
|
||||
{
|
||||
switch (cover)
|
||||
{
|
||||
case YCoverImage img when !string.IsNullOrEmpty(img.Uri):
|
||||
return $"https://{img.Uri.Replace("%%", size)}";
|
||||
case YCoverPic pic when !string.IsNullOrEmpty(pic.Uri):
|
||||
return $"https://{pic.Uri.Replace("%%", size)}";
|
||||
default:
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
16
PlaylistShared.Api/Mapping/AppMappingProfile.cs
Normal file
16
PlaylistShared.Api/Mapping/AppMappingProfile.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using AutoMapper;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using PlaylistShared.Shared.Models;
|
||||
|
||||
namespace PlaylistShared.Api.Mapping;
|
||||
|
||||
public class AppMappingProfile : Profile
|
||||
{
|
||||
public AppMappingProfile()
|
||||
{
|
||||
CreateMap<SharedPlaylistEntity, SharedPlaylistDto>()
|
||||
.ForMember(dest => dest.Creator, opt => opt.MapFrom(src => src.Creator));
|
||||
CreateMap<ApplicationUser, ApplicationUserDto>();
|
||||
CreateMap<TrackAdditionLogEntity, TrackAdditionLogDto>();
|
||||
}
|
||||
}
|
||||
35
PlaylistShared.Api/PlaylistShared.Api.csproj
Normal file
35
PlaylistShared.Api/PlaylistShared.Api.csproj
Normal file
@@ -0,0 +1,35 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>a29c84f3-dccf-4a45-b139-f8effd676cd0</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<DockerComposeProjectPath>..\docker-compose.dcproj</DockerComposeProjectPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="16.1.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" />
|
||||
<PackageReference Include="AspNet.Security.OAuth.Yandex" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="10.1.7" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.7" />
|
||||
<PackageReference Include="YandexMusic" Version="0.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PlaylistShared.Shared\PlaylistShared.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
133
PlaylistShared.Api/Program.cs
Normal file
133
PlaylistShared.Api/Program.cs
Normal file
@@ -0,0 +1,133 @@
|
||||
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using PlaylistShared.Api.Data;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using PlaylistShared.Api.Mapping;
|
||||
using PlaylistShared.Api.Services;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Text;
|
||||
|
||||
namespace PlaylistShared.Api;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
|
||||
|
||||
// DbContext
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||||
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));// Identity
|
||||
builder.Services.AddIdentity<ApplicationUser, IdentityRole<Guid>>(options =>
|
||||
{
|
||||
options.User.RequireUniqueEmail = true;
|
||||
options.Password.RequireDigit = false;
|
||||
options.Password.RequiredLength = 6;
|
||||
options.Password.RequireNonAlphanumeric = false;
|
||||
options.Password.RequireUppercase = false;
|
||||
})
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
// JWT
|
||||
var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = builder.Configuration["Jwt:Issuer"],
|
||||
ValidAudience = builder.Configuration["Jwt:Audience"],
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
|
||||
};
|
||||
})
|
||||
.AddOpenIdConnect("Keycloak", options =>
|
||||
{
|
||||
options.Authority = builder.Configuration["Keycloak:Authority"];
|
||||
options.ClientId = builder.Configuration["Keycloak:ClientId"];
|
||||
options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
|
||||
options.ResponseType = "code";
|
||||
options.SaveTokens = true;
|
||||
options.GetClaimsFromUserInfoEndpoint = true;
|
||||
options.Scope.Add("openid");
|
||||
options.Scope.Add("profile");
|
||||
options.Scope.Add("email");
|
||||
options.CallbackPath = "/api/auth/keycloak-callback";
|
||||
options.SignInScheme = IdentityConstants.ExternalScheme;
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddAutoMapper(t => t.AddProfile<AppMappingProfile>());
|
||||
builder.Services.AddScoped<YandexMusicService>();
|
||||
builder.Services.AddScoped<SharedPlaylistService>();
|
||||
builder.Services.AddScoped<TrackAdditionLogService>();
|
||||
builder.Services.AddScoped<JwtService>();
|
||||
builder.Services.AddDataProtection();
|
||||
|
||||
builder.Services.AddHttpClient();
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("Development", policy =>
|
||||
{
|
||||
policy.WithOrigins("http://localhost:5053", "https://localhost:7225", "http://localhost:5181", "https://api.playlistshare.frigat.duckdns.org", "https://playlistshare.frigat.duckdns.org")
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials();
|
||||
});
|
||||
|
||||
options.AddPolicy("Production", policy =>
|
||||
{
|
||||
policy.WithOrigins("https://api.playlistshare.frigat.duckdns.org", "https://playlistshare.frigat.duckdns.org")
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials();
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapOpenApi();
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseCors("Development");
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseCors("Production");
|
||||
}
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
31
PlaylistShared.Api/Properties/launchSettings.json
Normal file
31
PlaylistShared.Api/Properties/launchSettings.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "http://localhost:5053"
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "https://localhost:7270;http://localhost:5053"
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker",
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_HTTPS_PORTS": "8081",
|
||||
"ASPNETCORE_HTTP_PORTS": "8080"
|
||||
},
|
||||
"publishAllPorts": true,
|
||||
"useSSL": true
|
||||
}
|
||||
},
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json"
|
||||
}
|
||||
49
PlaylistShared.Api/Services/JwtService.cs
Normal file
49
PlaylistShared.Api/Services/JwtService.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace PlaylistShared.Api.Services;
|
||||
|
||||
public class JwtService
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
|
||||
public JwtService(IConfiguration configuration, UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
public async Task<(string Token, string RefreshToken, DateTime Expiration)> GenerateTokenAsync(ApplicationUser user)
|
||||
{
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
|
||||
var key = Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!);
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, user.UserName!),
|
||||
new Claim(ClaimTypes.Email, user.Email!),
|
||||
}),
|
||||
Expires = DateTime.UtcNow.AddHours(1),
|
||||
Issuer = _configuration["Jwt:Issuer"],
|
||||
Audience = _configuration["Jwt:Audience"],
|
||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
||||
};
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
var tokenString = tokenHandler.WriteToken(token);
|
||||
|
||||
var refreshToken = Guid.NewGuid().ToString();
|
||||
user.RefreshToken = refreshToken;
|
||||
user.RefreshTokenExpiryUtc = DateTime.UtcNow.AddDays(7);
|
||||
await _userManager.UpdateAsync(user);
|
||||
|
||||
return (tokenString, refreshToken, tokenDescriptor.Expires.Value);
|
||||
}
|
||||
}
|
||||
136
PlaylistShared.Api/Services/SharedPlaylistService.cs
Normal file
136
PlaylistShared.Api/Services/SharedPlaylistService.cs
Normal file
@@ -0,0 +1,136 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PlaylistShared.Api.Data;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using PlaylistShared.Shared.DTO;
|
||||
using PlaylistShared.Shared.Enums;
|
||||
using PlaylistShared.Shared.Models;
|
||||
|
||||
namespace PlaylistShared.Api.Services;
|
||||
|
||||
public class SharedPlaylistService
|
||||
{
|
||||
private readonly ApplicationDbContext _db;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly TrackAdditionLogService _trackLogService;
|
||||
|
||||
public SharedPlaylistService(ApplicationDbContext db, IMapper mapper, TrackAdditionLogService trackLogService)
|
||||
{
|
||||
_db = db;
|
||||
_mapper = mapper;
|
||||
_trackLogService = trackLogService;
|
||||
}
|
||||
|
||||
public async Task<SharedPlaylistDto> CreateAsync(Guid creatorUserId, SharePlaylistDto dto)
|
||||
{
|
||||
var entity = new SharedPlaylistEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
CreatorUserId = creatorUserId,
|
||||
YandexPlaylistKind = dto.YandexPlaylistKind,
|
||||
YandexPlaylistOwnerUid = dto.YandexPlaylistOwnerUid,
|
||||
Title = dto.Title,
|
||||
Description = dto.Description,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
ShareToken = GenerateToken(),
|
||||
ViewPermission = dto.ViewPermission,
|
||||
AddPermission = dto.AddPermission,
|
||||
RemovePermission = dto.RemovePermission
|
||||
};
|
||||
_db.SharedPlaylists.Add(entity);
|
||||
await _db.SaveChangesAsync();
|
||||
return _mapper.Map<SharedPlaylistDto>(entity);
|
||||
}
|
||||
|
||||
public async Task<SharedPlaylistDto?> GetByTokenAsync(string token)
|
||||
{
|
||||
var entity = await _db.SharedPlaylists
|
||||
.Include(sp => sp.Creator)
|
||||
.FirstOrDefaultAsync(sp => sp.ShareToken == token && !sp.IsDeleted);
|
||||
return entity == null ? null : _mapper.Map<SharedPlaylistDto>(entity);
|
||||
}
|
||||
|
||||
public async Task<SharedPlaylistEntity?> GetEntityByTokenAsync(string token)
|
||||
{
|
||||
return await _db.SharedPlaylists
|
||||
.Include(sp => sp.Creator)
|
||||
.FirstOrDefaultAsync(sp => sp.ShareToken == token && !sp.IsDeleted);
|
||||
}
|
||||
|
||||
public async Task<SharedPlaylistDto?> UpdatePermissionsAsync(Guid playlistId, UpdatePermissionsDto dto)
|
||||
{
|
||||
var entity = await _db.SharedPlaylists.FindAsync(playlistId);
|
||||
if (entity == null) return null;
|
||||
entity.ViewPermission = dto.ViewPermission;
|
||||
entity.AddPermission = dto.AddPermission;
|
||||
entity.RemovePermission = dto.RemovePermission;
|
||||
entity.UpdatedAt = DateTime.UtcNow;
|
||||
await _db.SaveChangesAsync();
|
||||
return _mapper.Map<SharedPlaylistDto>(entity);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid playlistId)
|
||||
{
|
||||
var entity = await _db.SharedPlaylists.FindAsync(playlistId);
|
||||
if (entity == null) return false;
|
||||
entity.IsDeleted = true;
|
||||
entity.UpdatedAt = DateTime.UtcNow;
|
||||
await _db.SaveChangesAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<bool> CanViewAsync(SharedPlaylistEntity playlist, Guid? currentUserId)
|
||||
{
|
||||
if (currentUserId == playlist.CreatorUserId) return true;
|
||||
return playlist.ViewPermission == ViewPermission.Everyone ||
|
||||
(playlist.ViewPermission == ViewPermission.AuthorizedOnly && currentUserId.HasValue);
|
||||
}
|
||||
|
||||
public async Task<bool> CanAddTrackAsync(SharedPlaylistEntity playlist, Guid? currentUserId)
|
||||
{
|
||||
if (currentUserId == playlist.CreatorUserId) return true;
|
||||
return playlist.AddPermission == EditPermission.Everyone ||
|
||||
(playlist.AddPermission == EditPermission.AuthorizedOnly && currentUserId.HasValue);
|
||||
}
|
||||
|
||||
public async Task<bool> CanRemoveTrackAsync(SharedPlaylistEntity playlist, Guid? currentUserId, string trackId)
|
||||
{
|
||||
if (currentUserId == playlist.CreatorUserId) return true;
|
||||
return playlist.RemovePermission switch
|
||||
{
|
||||
EditPermission.Everyone => true,
|
||||
EditPermission.AuthorizedOnly => currentUserId.HasValue,
|
||||
EditPermission.AddedByUserOnly when currentUserId.HasValue =>
|
||||
await _trackLogService.IsTrackAddedByUserAsync(playlist.Id, trackId, currentUserId.Value),
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<bool> IsCreatorAsync(Guid playlistId, Guid userId)
|
||||
{
|
||||
var playlist = await _db.SharedPlaylists.FindAsync(playlistId);
|
||||
return playlist != null && playlist.CreatorUserId == userId;
|
||||
}
|
||||
|
||||
private string GenerateToken()
|
||||
{
|
||||
return Convert.ToBase64String(Guid.NewGuid().ToByteArray())
|
||||
.Replace("/", "_")
|
||||
.Replace("+", "-")
|
||||
.TrimEnd('=');
|
||||
}
|
||||
|
||||
public async Task<SharedPlaylistEntity?> GetByYandexIdsAsync(string ownerUid, string kind)
|
||||
{
|
||||
return await _db.SharedPlaylists
|
||||
.FirstOrDefaultAsync(sp => sp.YandexPlaylistOwnerUid == ownerUid && sp.YandexPlaylistKind == kind && !sp.IsDeleted);
|
||||
}
|
||||
|
||||
public async Task<List<SharedPlaylistEntity>> GetAllByUserAsync(Guid userId)
|
||||
{
|
||||
return await _db.SharedPlaylists
|
||||
.Where(sp => sp.CreatorUserId == userId && !sp.IsDeleted)
|
||||
.ToListAsync();
|
||||
}
|
||||
}
|
||||
44
PlaylistShared.Api/Services/TrackAdditionLogService.cs
Normal file
44
PlaylistShared.Api/Services/TrackAdditionLogService.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PlaylistShared.Api.Data;
|
||||
using PlaylistShared.Api.Entities;
|
||||
|
||||
namespace PlaylistShared.Api.Services;
|
||||
|
||||
public class TrackAdditionLogService
|
||||
{
|
||||
private readonly ApplicationDbContext _db;
|
||||
|
||||
public TrackAdditionLogService(ApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task LogAdditionAsync(Guid sharedPlaylistId, string trackId, Guid addedByUserId)
|
||||
{
|
||||
var log = new TrackAdditionLogEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
SharedPlaylistId = sharedPlaylistId,
|
||||
TrackId = trackId,
|
||||
AddedByUserId = addedByUserId,
|
||||
AddedAtUtc = DateTime.UtcNow
|
||||
};
|
||||
_db.TrackAdditionLogs.Add(log);
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<bool> IsTrackAddedByUserAsync(Guid sharedPlaylistId, string trackId, Guid userId)
|
||||
{
|
||||
return await _db.TrackAdditionLogs
|
||||
.AnyAsync(l => l.SharedPlaylistId == sharedPlaylistId && l.TrackId == trackId && l.AddedByUserId == userId);
|
||||
}
|
||||
|
||||
public async Task RemoveLogsForTrackAsync(Guid sharedPlaylistId, string trackId)
|
||||
{
|
||||
var logs = await _db.TrackAdditionLogs
|
||||
.Where(l => l.SharedPlaylistId == sharedPlaylistId && l.TrackId == trackId)
|
||||
.ToListAsync();
|
||||
_db.TrackAdditionLogs.RemoveRange(logs);
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
88
PlaylistShared.Api/Services/YandexMusicService.cs
Normal file
88
PlaylistShared.Api/Services/YandexMusicService.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using PlaylistShared.Api.Entities;
|
||||
using YandexMusic;
|
||||
using YandexMusic.API.Extensions.API;
|
||||
using YandexMusic.API.Models.Playlist;
|
||||
|
||||
namespace PlaylistShared.Api.Services;
|
||||
|
||||
public class YandexMusicService
|
||||
{
|
||||
private readonly IDataProtector _dataProtector;
|
||||
|
||||
public YandexMusicService(IDataProtectionProvider provider)
|
||||
{
|
||||
_dataProtector = provider.CreateProtector("YandexTokens");
|
||||
}
|
||||
|
||||
private async Task<YandexMusicClient?> CreateClientAsync(ApplicationUser user)
|
||||
{
|
||||
if (string.IsNullOrEmpty(user.YandexAccessToken))
|
||||
return null;
|
||||
|
||||
string decryptedToken;
|
||||
try
|
||||
{
|
||||
decryptedToken = _dataProtector.Unprotect(user.YandexAccessToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var client = new YandexMusicClient();
|
||||
var success = await client.Authorize(decryptedToken);
|
||||
return success ? client : null;
|
||||
}
|
||||
|
||||
public async Task<YPlaylist?> GetPlaylistAsync(ApplicationUser user, string ownerUid, string kind)
|
||||
{
|
||||
var client = await CreateClientAsync(user);
|
||||
if (client == null) return null;
|
||||
return await client.GetPlaylistAsync(ownerUid, kind);
|
||||
}
|
||||
|
||||
public async Task<YPlaylist?> CreatePlaylistAsync(ApplicationUser user, string title)
|
||||
{
|
||||
var client = await CreateClientAsync(user);
|
||||
if (client == null) return null;
|
||||
return await client.CreatePlaylistAsync(title);
|
||||
}
|
||||
|
||||
public async Task<YPlaylist?> AddTracksAsync(ApplicationUser user, string ownerUid, string kind, IEnumerable<string> trackIds)
|
||||
{
|
||||
var client = await CreateClientAsync(user);
|
||||
if (client == null) return null;
|
||||
// Получаем треки по ID
|
||||
var tracks = await client.GetTracksAsync(trackIds);
|
||||
if (tracks == null || !tracks.Any()) return null;
|
||||
var playlist = await client.GetPlaylistAsync(ownerUid, kind);
|
||||
if (playlist == null) return null;
|
||||
return await playlist.InsertTracksAsync(tracks.ToArray());
|
||||
}
|
||||
|
||||
public async Task<YPlaylist?> RemoveTracksAsync(ApplicationUser user, string ownerUid, string kind, IEnumerable<string> trackIds)
|
||||
{
|
||||
var client = await CreateClientAsync(user);
|
||||
if (client == null) return null;
|
||||
var tracks = await client.GetTracksAsync(trackIds);
|
||||
if (tracks == null || !tracks.Any()) return null;
|
||||
var playlist = await client.GetPlaylistAsync(ownerUid, kind);
|
||||
if (playlist == null) return null;
|
||||
return await playlist.RemoveTracksAsync(tracks.ToArray());
|
||||
}
|
||||
|
||||
public string EncryptToken(string token) => _dataProtector.Protect(token);
|
||||
|
||||
public string DecryptToken(string encryptedToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _dataProtector.Unprotect(encryptedToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
21
PlaylistShared.Api/appsettings.Development.json
Normal file
21
PlaylistShared.Api/appsettings.Development.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=FRIGAT-PC;Database=PlaylistShared;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"
|
||||
},
|
||||
"Jwt": {
|
||||
"Key": "your-32-character-secret-key-for-jwt-minimum-length",
|
||||
"Issuer": "PlaylistShared.Api",
|
||||
"Audience": "PlaylistShared.Client"
|
||||
},
|
||||
"Yandex": {
|
||||
"ClientId": "0916685f8a3641ca8fc382dbccf77236",
|
||||
"ClientSecret": "f7398893cd814f8b84b85aeb2a0a6698"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
29
PlaylistShared.Api/appsettings.json
Normal file
29
PlaylistShared.Api/appsettings.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=FRIGAT-PC;Database=PlaylistShared;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"
|
||||
},
|
||||
"Jwt": {
|
||||
"Key": "your-32-character-secret-key-for-jwt-minimum-length",
|
||||
"Issuer": "PlaylistShared.Api",
|
||||
"Audience": "PlaylistShared.Client"
|
||||
},
|
||||
"Yandex": {
|
||||
"ClientId": "your-yandex-oauth-client-id",
|
||||
"ClientSecret": "your-yandex-oauth-client-secret"
|
||||
},
|
||||
"Client": {
|
||||
"BaseUrl": "https://localhost:5002"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Keycloak": {
|
||||
"Authority": "https://your-keycloak-domain/auth/realms/your-realm",
|
||||
"ClientId": "playlist-shared-client",
|
||||
"ClientSecret": "your-secret"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
19
PlaylistShared.PWA2123/App.razor
Normal file
19
PlaylistShared.PWA2123/App.razor
Normal file
@@ -0,0 +1,19 @@
|
||||
<CascadingAuthenticationState>
|
||||
<Router AppAssembly="@typeof(App).Assembly" NotFoundPage="typeof(Pages.NotFound)" >
|
||||
<Found Context="routeData">
|
||||
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
|
||||
<NotAuthorized>
|
||||
@if (context.User.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
<RedirectToLogin />
|
||||
}
|
||||
else
|
||||
{
|
||||
<p role="alert">You are not authorized to access this resource.</p>
|
||||
}
|
||||
</NotAuthorized>
|
||||
</AuthorizeRouteView>
|
||||
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
|
||||
</Found>
|
||||
</Router>
|
||||
</CascadingAuthenticationState>
|
||||
19
PlaylistShared.PWA2123/Layout/LoginDisplay.razor
Normal file
19
PlaylistShared.PWA2123/Layout/LoginDisplay.razor
Normal file
@@ -0,0 +1,19 @@
|
||||
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<AuthorizeView>
|
||||
<Authorized>
|
||||
<MudText Typo="Typo.body2" Class="d-inline mr-2">Hello, @context.User.Identity?.Name!</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="BeginLogOut">Log out</MudButton>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
<MudLink Href="authentication/login" Color="Color.Inherit" Underline="Underline.Hover" Typo="Typo.body2">Log in</MudLink>
|
||||
</NotAuthorized>
|
||||
</AuthorizeView>
|
||||
|
||||
@code{
|
||||
public void BeginLogOut()
|
||||
{
|
||||
Navigation.NavigateToLogout("authentication/logout");
|
||||
}
|
||||
}
|
||||
100
PlaylistShared.PWA2123/Layout/MainLayout.razor
Normal file
100
PlaylistShared.PWA2123/Layout/MainLayout.razor
Normal file
@@ -0,0 +1,100 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<MudThemeProvider Theme="@_theme" IsDarkMode="_isDarkMode" />
|
||||
<MudPopoverProvider />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
|
||||
<MudLayout>
|
||||
<MudAppBar Elevation="1">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" OnClick="@DrawerToggle" />
|
||||
<MudText Typo="Typo.h6" Class="ml-2">Application</MudText>
|
||||
<MudSpacer />
|
||||
<LoginDisplay />
|
||||
<MudIconButton Icon="@(DarkLightModeButtonIcon)" Color="Color.Inherit" OnClick="@DarkModeToggle" Class="ml-2" />
|
||||
<MudLink Href="https://learn.microsoft.com/aspnet/core/" Target="_blank" Color="Color.Inherit" Underline="Underline.None" Class="ml-4">
|
||||
About
|
||||
</MudLink>
|
||||
</MudAppBar>
|
||||
|
||||
<MudDrawer @bind-Open="_drawerOpen" ClipMode="DrawerClipMode.Always" Elevation="2">
|
||||
<NavMenu />
|
||||
</MudDrawer>
|
||||
|
||||
<MudMainContent Class="pt-16 pa-4">
|
||||
@Body
|
||||
</MudMainContent>
|
||||
</MudLayout>
|
||||
|
||||
@code {
|
||||
private bool _drawerOpen = true;
|
||||
private bool _isDarkMode = true;
|
||||
private MudTheme? _theme;
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
base.OnInitialized();
|
||||
|
||||
_theme = new()
|
||||
{
|
||||
PaletteLight = _lightPalette,
|
||||
PaletteDark = _darkPalette,
|
||||
LayoutProperties = new LayoutProperties()
|
||||
};
|
||||
}
|
||||
|
||||
private void DrawerToggle()
|
||||
{
|
||||
_drawerOpen = !_drawerOpen;
|
||||
}
|
||||
|
||||
private void DarkModeToggle()
|
||||
{
|
||||
_isDarkMode = !_isDarkMode;
|
||||
}
|
||||
|
||||
private readonly PaletteLight _lightPalette = new()
|
||||
{
|
||||
Black = "#110e2d",
|
||||
AppbarText = "#424242",
|
||||
AppbarBackground = "rgba(255,255,255,0.8)",
|
||||
DrawerBackground = "#ffffff",
|
||||
GrayLight = "#e8e8e8",
|
||||
GrayLighter = "#f9f9f9",
|
||||
};
|
||||
|
||||
private readonly PaletteDark _darkPalette = new()
|
||||
{
|
||||
Primary = "#7e6fff",
|
||||
Surface = "#1e1e2d",
|
||||
Background = "#1a1a27",
|
||||
BackgroundGray = "#151521",
|
||||
AppbarText = "#92929f",
|
||||
AppbarBackground = "rgba(26,26,39,0.8)",
|
||||
DrawerBackground = "#1a1a27",
|
||||
ActionDefault = "#74718e",
|
||||
ActionDisabled = "#9999994d",
|
||||
ActionDisabledBackground = "#605f6d4d",
|
||||
TextPrimary = "#b2b0bf",
|
||||
TextSecondary = "#92929f",
|
||||
TextDisabled = "#ffffff33",
|
||||
DrawerIcon = "#92929f",
|
||||
DrawerText = "#92929f",
|
||||
GrayLight = "#2a2833",
|
||||
GrayLighter = "#1e1e2d",
|
||||
Info = "#4a86ff",
|
||||
Success = "#3dcb6c",
|
||||
Warning = "#ffb545",
|
||||
Error = "#ff3f5f",
|
||||
LinesDefault = "#33323e",
|
||||
TableLines = "#33323e",
|
||||
Divider = "#292838",
|
||||
OverlayLight = "#1e1e2d80",
|
||||
};
|
||||
|
||||
public string DarkLightModeButtonIcon => _isDarkMode switch
|
||||
{
|
||||
true => Icons.Material.Rounded.AutoMode,
|
||||
false => Icons.Material.Outlined.DarkMode,
|
||||
};
|
||||
}
|
||||
77
PlaylistShared.PWA2123/Layout/MainLayout.razor.css
Normal file
77
PlaylistShared.PWA2123/Layout/MainLayout.razor.css
Normal file
@@ -0,0 +1,77 @@
|
||||
.page {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
main {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
|
||||
}
|
||||
|
||||
.top-row {
|
||||
background-color: #f7f7f7;
|
||||
border-bottom: 1px solid #d6d5d5;
|
||||
justify-content: flex-end;
|
||||
height: 3.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.top-row ::deep a, .top-row ::deep .btn-link {
|
||||
white-space: nowrap;
|
||||
margin-left: 1.5rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.top-row ::deep a:hover, .top-row ::deep .btn-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.top-row ::deep a:first-child {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
@media (max-width: 640.98px) {
|
||||
.top-row {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.top-row ::deep a, .top-row ::deep .btn-link {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 641px) {
|
||||
.page {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
height: 100vh;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.top-row {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.top-row.auth ::deep a:first-child {
|
||||
flex: 1;
|
||||
text-align: right;
|
||||
width: 0;
|
||||
}
|
||||
|
||||
.top-row, article {
|
||||
padding-left: 2rem !important;
|
||||
padding-right: 1.5rem !important;
|
||||
}
|
||||
}
|
||||
9
PlaylistShared.PWA2123/Layout/NavMenu.razor
Normal file
9
PlaylistShared.PWA2123/Layout/NavMenu.razor
Normal file
@@ -0,0 +1,9 @@
|
||||
<MudNavMenu>
|
||||
<MudNavLink Href="/" Match="NavLinkMatch.All" Icon="@Icons.Material.Filled.Home">Home</MudNavLink>
|
||||
<AuthorizeView>
|
||||
<Authorized>
|
||||
<MudNavLink Href="/create" Icon="@Icons.Material.Filled.Add">Создать плейлист</MudNavLink>
|
||||
<MudNavLink Href="/my" Icon="@Icons.Material.Filled.List">Мои ссылки</MudNavLink>
|
||||
</Authorized>
|
||||
</AuthorizeView>
|
||||
</MudNavMenu>
|
||||
9
PlaylistShared.PWA2123/Layout/RedirectToLogin.razor
Normal file
9
PlaylistShared.PWA2123/Layout/RedirectToLogin.razor
Normal file
@@ -0,0 +1,9 @@
|
||||
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@code {
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
Navigation.NavigateToLogin("authentication/login");
|
||||
}
|
||||
}
|
||||
24
PlaylistShared.PWA2123/Pages/AuthCallback.razor
Normal file
24
PlaylistShared.PWA2123/Pages/AuthCallback.razor
Normal file
@@ -0,0 +1,24 @@
|
||||
@page "/auth-callback"
|
||||
@using PlaylistShared.PWA.Services
|
||||
@inject NavigationManager Navigation
|
||||
@inject AuthStateProvider AuthProvider
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
@code {
|
||||
[Parameter] public string? Token { get; set; }
|
||||
[Parameter] public string? RefreshToken { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Token) && !string.IsNullOrEmpty(RefreshToken))
|
||||
{
|
||||
await AuthProvider.MarkUserAsAuthenticated(Token, RefreshToken);
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Ошибка аутентификации через Яндекс", Severity.Error);
|
||||
Navigation.NavigateTo("/login");
|
||||
}
|
||||
}
|
||||
}
|
||||
7
PlaylistShared.PWA2123/Pages/Authentication.razor
Normal file
7
PlaylistShared.PWA2123/Pages/Authentication.razor
Normal file
@@ -0,0 +1,7 @@
|
||||
@page "/authentication/{action}"
|
||||
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
|
||||
<RemoteAuthenticatorView Action="@Action" />
|
||||
|
||||
@code{
|
||||
[Parameter] public string? Action { get; set; }
|
||||
}
|
||||
18
PlaylistShared.PWA2123/Pages/Counter.razor
Normal file
18
PlaylistShared.PWA2123/Pages/Counter.razor
Normal file
@@ -0,0 +1,18 @@
|
||||
@page "/counter"
|
||||
|
||||
<PageTitle>Counter</PageTitle>
|
||||
|
||||
<MudText Typo="Typo.h3" GutterBottom="true">Counter</MudText>
|
||||
|
||||
<MudText Class="mb-4">Current count: @currentCount</MudText>
|
||||
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" @onclick="IncrementCount">Click me</MudButton>
|
||||
|
||||
@code {
|
||||
private int currentCount = 0;
|
||||
|
||||
private void IncrementCount()
|
||||
{
|
||||
currentCount++;
|
||||
}
|
||||
}
|
||||
18
PlaylistShared.PWA2123/Pages/Home.razor
Normal file
18
PlaylistShared.PWA2123/Pages/Home.razor
Normal file
@@ -0,0 +1,18 @@
|
||||
@page "/"
|
||||
|
||||
<PageTitle>Home</PageTitle>
|
||||
|
||||
<MudText Typo="Typo.h3" GutterBottom="true">Hello, world!</MudText>
|
||||
<MudText Class="mb-8">Welcome to your new app, powered by MudBlazor and the .NET 10 Template!</MudText>
|
||||
|
||||
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Dense="true" Class="mb-6">
|
||||
Before authentication will function correctly, you must configure your provider details in <code>Program.cs</code>.
|
||||
</MudAlert>
|
||||
|
||||
|
||||
<MudAlert Severity="Severity.Normal" ContentAlignment="HorizontalAlignment.Start">
|
||||
You can find documentation and examples on our website here:
|
||||
<MudLink Href="https://mudblazor.com" Target="_blank" Typo="Typo.body2" Color="Color.Primary">
|
||||
<b>www.mudblazor.com</b>
|
||||
</MudLink>
|
||||
</MudAlert>
|
||||
52
PlaylistShared.PWA2123/Pages/Login.razor
Normal file
52
PlaylistShared.PWA2123/Pages/Login.razor
Normal file
@@ -0,0 +1,52 @@
|
||||
@page "/login"
|
||||
@using PlaylistShared.PWA.Services
|
||||
@inject NavigationManager Navigation
|
||||
@inject AuthStateProvider AuthProvider
|
||||
@inject ApiClient ApiClient
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Small" Class="mt-16">
|
||||
<MudCard>
|
||||
<MudCardContent Class="text-center">
|
||||
<MudText Typo="Typo.h5" Class="mb-4">Вход в PlaylistShared</MudText>
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="LoginWithYandex" StartIcon="@Icons.Custom.Brands.Yandex" FullWidth="true">
|
||||
Войти через Яндекс
|
||||
</MudButton>
|
||||
|
||||
<MudDivider Class="my-4">или</MudDivider>
|
||||
|
||||
<MudTextField Label="Логин" @bind-Value="_username" Variant="Variant.Outlined" FullWidth="true" />
|
||||
<MudTextField Label="Пароль" @bind-Value="_password" InputType="InputType.Password" Variant="Variant.Outlined" FullWidth="true" />
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Secondary" OnClick="LoginWithPassword" FullWidth="true">Войти по паролю</MudButton>
|
||||
|
||||
<MudText Class="mt-4">
|
||||
Нет аккаунта? <MudLink Href="/register">Зарегистрироваться</MudLink>
|
||||
</MudText>
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private string _username = "";
|
||||
private string _password = "";
|
||||
|
||||
private void LoginWithYandex()
|
||||
{
|
||||
Navigation.NavigateTo("https://localhost:5001/api/externalauth/login-yandex", true);
|
||||
}
|
||||
|
||||
private async Task LoginWithPassword()
|
||||
{
|
||||
var result = await ApiClient.LoginAsync(_username, _password);
|
||||
if (result != null)
|
||||
{
|
||||
await AuthProvider.MarkUserAsAuthenticated(result.Token, result.RefreshToken);
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Неверный логин или пароль", Severity.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
11
PlaylistShared.PWA2123/Pages/LoginDisplay.razor
Normal file
11
PlaylistShared.PWA2123/Pages/LoginDisplay.razor
Normal file
@@ -0,0 +1,11 @@
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<AuthorizeView>
|
||||
<Authorized>
|
||||
<MudText Typo="Typo.body2" Class="d-inline mr-2">Hello, @context.User.Identity?.Name!</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="() => Navigation.NavigateTo("/logout")">Log out</MudButton>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
<MudLink Href="/login" Color="Color.Inherit" Underline="Underline.Hover" Typo="Typo.body2">Log in</MudLink>
|
||||
</NotAuthorized>
|
||||
</AuthorizeView>
|
||||
12
PlaylistShared.PWA2123/Pages/Logout.razor
Normal file
12
PlaylistShared.PWA2123/Pages/Logout.razor
Normal file
@@ -0,0 +1,12 @@
|
||||
@page "/logout"
|
||||
@using PlaylistShared.PWA.Services
|
||||
@inject AuthStateProvider AuthProvider
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@code {
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await AuthProvider.MarkUserAsLoggedOut();
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
}
|
||||
9
PlaylistShared.PWA2123/Pages/NotFound.razor
Normal file
9
PlaylistShared.PWA2123/Pages/NotFound.razor
Normal file
@@ -0,0 +1,9 @@
|
||||
@page "/not-found"
|
||||
@layout MainLayout
|
||||
|
||||
<PageTitle>Not Found</PageTitle>
|
||||
|
||||
<MudText Typo="Typo.h3" GutterBottom="true">404 - Page Not Found</MudText>
|
||||
<MudText Class="mb-8">Sorry, the content you are looking for does not exist.</MudText>
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Href="/">Go to Home</MudButton>
|
||||
52
PlaylistShared.PWA2123/Pages/Weather.razor
Normal file
52
PlaylistShared.PWA2123/Pages/Weather.razor
Normal file
@@ -0,0 +1,52 @@
|
||||
@page "/weather"
|
||||
@inject HttpClient Http
|
||||
|
||||
<PageTitle>Weather</PageTitle>
|
||||
|
||||
<MudText Typo="Typo.h3" GutterBottom="true">Weather forecast</MudText>
|
||||
<MudText Typo="Typo.body1" Class="mb-8">This component demonstrates fetching data from the server.</MudText>
|
||||
|
||||
@if (forecasts == null)
|
||||
{
|
||||
<MudProgressCircular Color="Color.Default" Indeterminate="true" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="forecasts" Hover="true" SortLabel="Sort By" Elevation="0" AllowUnsorted="false">
|
||||
<HeaderContent>
|
||||
<MudTh><MudTableSortLabel InitialDirection="SortDirection.Ascending" SortBy="new Func<WeatherForecast, object>(x => x.Date)">Date</MudTableSortLabel></MudTh>
|
||||
<MudTh><MudTableSortLabel SortBy="new Func<WeatherForecast, object>(x => x.TemperatureC)">Temp. (C)</MudTableSortLabel></MudTh>
|
||||
<MudTh><MudTableSortLabel SortBy="new Func<WeatherForecast, object>(x => x.TemperatureF)">Temp. (F)</MudTableSortLabel></MudTh>
|
||||
<MudTh><MudTableSortLabel SortBy="new Func<WeatherForecast, object>(x => x.Summary!)">Summary</MudTableSortLabel></MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="Date">@context.Date</MudTd>
|
||||
<MudTd DataLabel="Temp. (C)">@context.TemperatureC</MudTd>
|
||||
<MudTd DataLabel="Temp. (F)">@context.TemperatureF</MudTd>
|
||||
<MudTd DataLabel="Summary">@context.Summary</MudTd>
|
||||
</RowTemplate>
|
||||
<PagerContent>
|
||||
<MudTablePager PageSizeOptions="new int[] { 50, 100 }" />
|
||||
</PagerContent>
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
@code {
|
||||
private WeatherForecast[]? forecasts;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
|
||||
}
|
||||
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public string? Summary { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
}
|
||||
}
|
||||
25
PlaylistShared.PWA2123/PlaylistShared.PWA.csproj
Normal file
25
PlaylistShared.PWA2123/PlaylistShared.PWA.csproj
Normal file
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<OverrideHtmlAssetPlaceholders>true</OverrideHtmlAssetPlaceholders>
|
||||
<ServiceWorkerAssetsManifest>service-worker-assets.js</ServiceWorkerAssetsManifest>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AspNet.Security.OAuth.Yandex" Version="10.0.0" />
|
||||
<PackageReference Include="MudBlazor" Version="9.3.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.17.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PlaylistShared.Shared\PlaylistShared.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ServiceWorker Include="wwwroot\\service-worker.js" PublishedContent="wwwroot\\service-worker.published.js" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
36
PlaylistShared.PWA2123/Program.cs
Normal file
36
PlaylistShared.PWA2123/Program.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
||||
using MudBlazor.Services;
|
||||
using PlaylistShared.PWA;
|
||||
using PlaylistShared.PWA.Services;
|
||||
|
||||
internal class Program
|
||||
{
|
||||
private static async global::System.Threading.Tasks.Task Main(string[] args)
|
||||
{
|
||||
var builder = WebAssemblyHostBuilder.CreateDefault(args);
|
||||
builder.RootComponents.Add<App>("#app");
|
||||
builder.RootComponents.Add<HeadOutlet>("head::after");
|
||||
|
||||
builder.Services.AddMudServices();
|
||||
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
|
||||
|
||||
builder.Services.AddScoped<TokenStorage>();
|
||||
builder.Services.AddScoped<AuthStateProvider>();
|
||||
builder.Services.AddScoped<ApiClient>();
|
||||
|
||||
builder.Services.AddAuthorizationCore();
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
|
||||
/*
|
||||
builder.Services.AddOidcAuthentication(options =>
|
||||
{
|
||||
// Configure your authentication provider options here.
|
||||
// For more information, see https://aka.ms/blazor-standalone-auth
|
||||
builder.Configuration.Bind("Local", options.ProviderOptions);
|
||||
});
|
||||
*/
|
||||
|
||||
await builder.Build().RunAsync();
|
||||
}
|
||||
}
|
||||
15
PlaylistShared.PWA2123/Properties/launchSettings.json
Normal file
15
PlaylistShared.PWA2123/Properties/launchSettings.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
|
||||
"applicationUrl": "https://localhost:7244;http://localhost:5143",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
77
PlaylistShared.PWA2123/Services/ApiClient.cs
Normal file
77
PlaylistShared.PWA2123/Services/ApiClient.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
using PlaylistShared.Shared.DTO;
|
||||
using PlaylistShared.Shared.Models;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace PlaylistShared.PWA.Services;
|
||||
|
||||
public class ApiClient
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly TokenStorage _tokenStorage;
|
||||
|
||||
public ApiClient(HttpClient http, TokenStorage tokenStorage)
|
||||
{
|
||||
_http = http;
|
||||
_tokenStorage = tokenStorage;
|
||||
}
|
||||
|
||||
public async Task<LoginResponse?> RefreshTokenAsync(string? refreshToken)
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/account/refresh-token", new RefreshTokenRequest { RefreshToken = refreshToken });
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<LoginResponse>>();
|
||||
return apiResponse?.Data;
|
||||
}
|
||||
|
||||
public async Task<LoginResponse?> LoginAsync(string username, string password)
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/account/login", new LoginRequest { Username = username, Password = password });
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<LoginResponse>>();
|
||||
return apiResponse?.Data;
|
||||
}
|
||||
|
||||
public async Task<LoginResponse?> RegisterAsync(string username, string email, string password)
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/account/register", new RegisterRequest { Username = username, Email = email, Password = password });
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<LoginResponse>>();
|
||||
return apiResponse?.Data;
|
||||
}
|
||||
|
||||
public async Task<SharedPlaylistDto?> CreateSharedPlaylistAsync(SharePlaylistDto dto)
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/sharedplaylist", dto);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<SharedPlaylistDto>>();
|
||||
return apiResponse?.Data;
|
||||
}
|
||||
|
||||
public async Task<SharedPlaylistDto?> GetSharedPlaylistAsync(string token)
|
||||
{
|
||||
var response = await _http.GetAsync($"/api/sharedplaylist/{token}");
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<SharedPlaylistDto>>();
|
||||
return apiResponse?.Data;
|
||||
}
|
||||
|
||||
public async Task<bool> AddTracksAsync(string sharedPlaylistToken, List<string> trackIds)
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/playlist/add-tracks", new AddTrackRequest
|
||||
{
|
||||
SharedPlaylistToken = sharedPlaylistToken,
|
||||
TrackIds = trackIds
|
||||
});
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveTracksAsync(string sharedPlaylistToken, List<string> trackIds)
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/playlist/remove-tracks", new AddTrackRequest
|
||||
{
|
||||
SharedPlaylistToken = sharedPlaylistToken,
|
||||
TrackIds = trackIds
|
||||
});
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
}
|
||||
99
PlaylistShared.PWA2123/Services/AuthStateProvider.cs
Normal file
99
PlaylistShared.PWA2123/Services/AuthStateProvider.cs
Normal file
@@ -0,0 +1,99 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace PlaylistShared.PWA.Services;
|
||||
|
||||
public class AuthStateProvider : AuthenticationStateProvider, IDisposable
|
||||
{
|
||||
private readonly TokenStorage _tokenStorage;
|
||||
private readonly ApiClient _apiClient;
|
||||
private readonly HttpClient _http;
|
||||
private Timer? _refreshTimer;
|
||||
private ClaimsPrincipal _currentUser = new(new ClaimsIdentity());
|
||||
|
||||
public AuthStateProvider(TokenStorage tokenStorage, ApiClient apiClient, HttpClient http)
|
||||
{
|
||||
_tokenStorage = tokenStorage;
|
||||
_apiClient = apiClient;
|
||||
_http = http;
|
||||
}
|
||||
|
||||
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
var (token, refreshToken) = await _tokenStorage.GetTokensAsync();
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return new AuthenticationState(_currentUser);
|
||||
|
||||
var principal = ParseToken(token);
|
||||
if (principal == null)
|
||||
return new AuthenticationState(_currentUser);
|
||||
|
||||
_currentUser = principal;
|
||||
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
ScheduleTokenRefresh(token, refreshToken);
|
||||
return new AuthenticationState(principal);
|
||||
}
|
||||
|
||||
public async Task MarkUserAsAuthenticated(string token, string refreshToken)
|
||||
{
|
||||
await _tokenStorage.SetTokensAsync(token, refreshToken);
|
||||
var principal = ParseToken(token);
|
||||
_currentUser = principal ?? new ClaimsPrincipal(new ClaimsIdentity());
|
||||
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
|
||||
public async Task MarkUserAsLoggedOut()
|
||||
{
|
||||
await _tokenStorage.ClearTokensAsync();
|
||||
_currentUser = new ClaimsPrincipal(new ClaimsIdentity());
|
||||
_http.DefaultRequestHeaders.Authorization = null;
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
|
||||
private ClaimsPrincipal? ParseToken(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwt = handler.ReadJwtToken(token);
|
||||
var identity = new ClaimsIdentity(jwt.Claims, "jwt");
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void ScheduleTokenRefresh(string token, string? refreshToken)
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwt = handler.ReadJwtToken(token);
|
||||
var expiresAt = jwt.ValidTo;
|
||||
var timeToExpiry = expiresAt - DateTime.UtcNow;
|
||||
var refreshTime = timeToExpiry - TimeSpan.FromMinutes(5);
|
||||
|
||||
if (refreshTime > TimeSpan.Zero && !string.IsNullOrEmpty(refreshToken))
|
||||
{
|
||||
_refreshTimer?.Dispose();
|
||||
_refreshTimer = new Timer(async _ =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var newToken = await _apiClient.RefreshTokenAsync(refreshToken);
|
||||
if (newToken != null)
|
||||
await MarkUserAsAuthenticated(newToken.Token, newToken.RefreshToken);
|
||||
else
|
||||
await MarkUserAsLoggedOut();
|
||||
}
|
||||
catch
|
||||
{
|
||||
await MarkUserAsLoggedOut();
|
||||
}
|
||||
}, null, (int)refreshTime.TotalMilliseconds, Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _refreshTimer?.Dispose();
|
||||
}
|
||||
31
PlaylistShared.PWA2123/Services/TokenStorage.cs
Normal file
31
PlaylistShared.PWA2123/Services/TokenStorage.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace PlaylistShared.PWA.Services;
|
||||
|
||||
public class TokenStorage
|
||||
{
|
||||
private readonly IJSRuntime _js;
|
||||
private const string TokenKey = "jwt_token";
|
||||
private const string RefreshTokenKey = "refresh_token";
|
||||
|
||||
public TokenStorage(IJSRuntime js) => _js = js;
|
||||
|
||||
public async Task SetTokensAsync(string token, string refreshToken)
|
||||
{
|
||||
await _js.InvokeVoidAsync("localStorage.setItem", TokenKey, token);
|
||||
await _js.InvokeVoidAsync("localStorage.setItem", RefreshTokenKey, refreshToken);
|
||||
}
|
||||
|
||||
public async Task<(string? token, string? refreshToken)> GetTokensAsync()
|
||||
{
|
||||
var token = await _js.InvokeAsync<string>("localStorage.getItem", TokenKey);
|
||||
var refreshToken = await _js.InvokeAsync<string>("localStorage.getItem", RefreshTokenKey);
|
||||
return (token, refreshToken);
|
||||
}
|
||||
|
||||
public async Task ClearTokensAsync()
|
||||
{
|
||||
await _js.InvokeVoidAsync("localStorage.removeItem", TokenKey);
|
||||
await _js.InvokeVoidAsync("localStorage.removeItem", RefreshTokenKey);
|
||||
}
|
||||
}
|
||||
13
PlaylistShared.PWA2123/_Imports.razor
Normal file
13
PlaylistShared.PWA2123/_Imports.razor
Normal file
@@ -0,0 +1,13 @@
|
||||
@using System.Net.Http
|
||||
@using System.Net.Http.Json
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.AspNetCore.Components.Web.Virtualization
|
||||
@using Microsoft.AspNetCore.Components.WebAssembly.Http
|
||||
@using Microsoft.JSInterop
|
||||
@using PlaylistShared.PWA
|
||||
@using PlaylistShared.PWA.Layout
|
||||
@using PlaylistShared.PWA.Services
|
||||
@using MudBlazor
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"Local": {
|
||||
"Authority": "https://login.microsoftonline.com/",
|
||||
"ClientId": "33333333-3333-3333-33333333333333333"
|
||||
}
|
||||
}
|
||||
6
PlaylistShared.PWA2123/wwwroot/appsettings.json
Normal file
6
PlaylistShared.PWA2123/wwwroot/appsettings.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"Local": {
|
||||
"Authority": "https://login.microsoftonline.com/",
|
||||
"ClientId": "33333333-3333-3333-33333333333333333"
|
||||
}
|
||||
}
|
||||
110
PlaylistShared.PWA2123/wwwroot/css/app.css
Normal file
110
PlaylistShared.PWA2123/wwwroot/css/app.css
Normal file
@@ -0,0 +1,110 @@
|
||||
html, body {
|
||||
font-family: 'Roboto', Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
#blazor-error-ui {
|
||||
color-scheme: light;
|
||||
background: rgba(30, 30, 45, 0.95);
|
||||
color: #f5f5f7;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
|
||||
backdrop-filter: blur(6px);
|
||||
box-sizing: border-box;
|
||||
display: none;
|
||||
left: 50%;
|
||||
right: auto;
|
||||
bottom: 1rem;
|
||||
width: min(52rem, calc(100vw - 2rem));
|
||||
transform: translateX(-50%);
|
||||
padding: 0.85rem 4rem 0.85rem 1rem;
|
||||
position: fixed;
|
||||
z-index: 2000;
|
||||
}
|
||||
|
||||
#blazor-error-ui .reload {
|
||||
color: #594AE2;
|
||||
font-weight: 600;
|
||||
margin-left: 0.5rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#blazor-error-ui .reload:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#blazor-error-ui .dismiss {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: 1rem;
|
||||
top: 0.55rem;
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
line-height: 1.65rem;
|
||||
text-align: center;
|
||||
border-radius: 999px;
|
||||
color: #d7d7df;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
#blazor-error-ui .dismiss:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.blazor-error-boundary {
|
||||
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121;
|
||||
padding: 1rem 1rem 1rem 3.7rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.blazor-error-boundary::after {
|
||||
content: "An error has occurred."
|
||||
}
|
||||
|
||||
.loading-progress {
|
||||
position: absolute;
|
||||
display: block;
|
||||
width: 8rem;
|
||||
height: 8rem;
|
||||
inset: 20vh 0 auto 0;
|
||||
margin: 0 auto 0 auto;
|
||||
}
|
||||
|
||||
.loading-progress circle {
|
||||
fill: none;
|
||||
stroke: #e0e0e0;
|
||||
stroke-width: 0.6rem;
|
||||
transform-origin: 50% 50%;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.loading-progress circle:last-child {
|
||||
stroke: #594AE2;
|
||||
stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%;
|
||||
transition: stroke-dasharray 0.05s ease-in-out;
|
||||
}
|
||||
|
||||
.loading-progress-text {
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
inset: calc(20vh + 3.25rem) 0 auto 0.2rem;
|
||||
}
|
||||
|
||||
.loading-progress-text:after {
|
||||
content: var(--blazor-load-percentage-text, "Loading");
|
||||
}
|
||||
|
||||
code {
|
||||
color: #c02d76;
|
||||
}
|
||||
|
||||
.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder {
|
||||
color: var(--bs-secondary-color);
|
||||
text-align: end;
|
||||
}
|
||||
|
||||
.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder {
|
||||
text-align: start;
|
||||
}
|
||||
BIN
PlaylistShared.PWA2123/wwwroot/favicon.png
Normal file
BIN
PlaylistShared.PWA2123/wwwroot/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.5 KiB |
BIN
PlaylistShared.PWA2123/wwwroot/icon-192.png
Normal file
BIN
PlaylistShared.PWA2123/wwwroot/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
BIN
PlaylistShared.PWA2123/wwwroot/icon-512.png
Normal file
BIN
PlaylistShared.PWA2123/wwwroot/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
41
PlaylistShared.PWA2123/wwwroot/index.html
Normal file
41
PlaylistShared.PWA2123/wwwroot/index.html
Normal file
@@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>PlaylistShared.PWA</title>
|
||||
<base href="/" />
|
||||
<link rel="preload" id="webassembly" />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="_content/MudBlazor/MudBlazor.min.css" />
|
||||
<link rel="stylesheet" href="css/app.css" />
|
||||
<link rel="icon" type="image/png" href="favicon.png" />
|
||||
<link href="PlaylistShared.PWA.styles.css" rel="stylesheet" />
|
||||
<link href="manifest.webmanifest" rel="manifest" />
|
||||
<link rel="apple-touch-icon" sizes="512x512" href="icon-512.png" />
|
||||
<link rel="apple-touch-icon" sizes="192x192" href="icon-192.png" />
|
||||
<script type="importmap"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app">
|
||||
<svg class="loading-progress">
|
||||
<circle r="40%" cx="50%" cy="50%" />
|
||||
<circle r="40%" cx="50%" cy="50%" />
|
||||
</svg>
|
||||
<div class="loading-progress-text"></div>
|
||||
</div>
|
||||
|
||||
<div id="blazor-error-ui">
|
||||
An unhandled error has occurred.
|
||||
<a href="." class="reload">Reload</a>
|
||||
<span class="dismiss">🗙</span>
|
||||
</div>
|
||||
<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
|
||||
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
|
||||
<script src="_framework/blazor.webassembly#[.{fingerprint}].js"></script>
|
||||
<script>navigator.serviceWorker.register('service-worker.js', { updateViaCache: 'none' });</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
22
PlaylistShared.PWA2123/wwwroot/manifest.webmanifest
Normal file
22
PlaylistShared.PWA2123/wwwroot/manifest.webmanifest
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "PlaylistShared.PWA",
|
||||
"short_name": "PlaylistShared.PWA",
|
||||
"id": "./",
|
||||
"start_url": "./",
|
||||
"display": "standalone",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#03173d",
|
||||
"prefer_related_applications": false,
|
||||
"icons": [
|
||||
{
|
||||
"src": "icon-512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
},
|
||||
{
|
||||
"src": "icon-192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
}
|
||||
]
|
||||
}
|
||||
27
PlaylistShared.PWA2123/wwwroot/sample-data/weather.json
Normal file
27
PlaylistShared.PWA2123/wwwroot/sample-data/weather.json
Normal file
@@ -0,0 +1,27 @@
|
||||
[
|
||||
{
|
||||
"date": "2022-01-06",
|
||||
"temperatureC": 1,
|
||||
"summary": "Freezing"
|
||||
},
|
||||
{
|
||||
"date": "2022-01-07",
|
||||
"temperatureC": 14,
|
||||
"summary": "Bracing"
|
||||
},
|
||||
{
|
||||
"date": "2022-01-08",
|
||||
"temperatureC": -13,
|
||||
"summary": "Freezing"
|
||||
},
|
||||
{
|
||||
"date": "2022-01-09",
|
||||
"temperatureC": -16,
|
||||
"summary": "Balmy"
|
||||
},
|
||||
{
|
||||
"date": "2022-01-10",
|
||||
"temperatureC": -2,
|
||||
"summary": "Chilly"
|
||||
}
|
||||
]
|
||||
4
PlaylistShared.PWA2123/wwwroot/service-worker.js
Normal file
4
PlaylistShared.PWA2123/wwwroot/service-worker.js
Normal file
@@ -0,0 +1,4 @@
|
||||
// In development, always fetch from the network and do not enable offline support.
|
||||
// This is because caching would make development more difficult (changes would not
|
||||
// be reflected on the first load after each change).
|
||||
self.addEventListener('fetch', () => { });
|
||||
55
PlaylistShared.PWA2123/wwwroot/service-worker.published.js
Normal file
55
PlaylistShared.PWA2123/wwwroot/service-worker.published.js
Normal file
@@ -0,0 +1,55 @@
|
||||
// Caution! Be sure you understand the caveats before publishing an application with
|
||||
// offline support. See https://aka.ms/blazor-offline-considerations
|
||||
|
||||
self.importScripts('./service-worker-assets.js');
|
||||
self.addEventListener('install', event => event.waitUntil(onInstall(event)));
|
||||
self.addEventListener('activate', event => event.waitUntil(onActivate(event)));
|
||||
self.addEventListener('fetch', event => event.respondWith(onFetch(event)));
|
||||
|
||||
const cacheNamePrefix = 'offline-cache-';
|
||||
const cacheName = `${cacheNamePrefix}${self.assetsManifest.version}`;
|
||||
const offlineAssetsInclude = [ /\.dll$/, /\.pdb$/, /\.wasm/, /\.html/, /\.js$/, /\.json$/, /\.css$/, /\.woff$/, /\.png$/, /\.jpe?g$/, /\.gif$/, /\.ico$/, /\.blat$/, /\.dat$/, /\.webmanifest$/ ];
|
||||
const offlineAssetsExclude = [ /^service-worker\.js$/ ];
|
||||
|
||||
// Replace with your base path if you are hosting on a subfolder. Ensure there is a trailing '/'.
|
||||
const base = "/";
|
||||
const baseUrl = new URL(base, self.origin);
|
||||
const manifestUrlList = self.assetsManifest.assets.map(asset => new URL(asset.url, baseUrl).href);
|
||||
|
||||
async function onInstall(event) {
|
||||
console.info('Service worker: Install');
|
||||
|
||||
// Fetch and cache all matching items from the assets manifest
|
||||
const assetsRequests = self.assetsManifest.assets
|
||||
.filter(asset => offlineAssetsInclude.some(pattern => pattern.test(asset.url)))
|
||||
.filter(asset => !offlineAssetsExclude.some(pattern => pattern.test(asset.url)))
|
||||
.map(asset => new Request(asset.url, { integrity: asset.hash, cache: 'no-cache' }));
|
||||
await caches.open(cacheName).then(cache => cache.addAll(assetsRequests));
|
||||
}
|
||||
|
||||
async function onActivate(event) {
|
||||
console.info('Service worker: Activate');
|
||||
|
||||
// Delete unused caches
|
||||
const cacheKeys = await caches.keys();
|
||||
await Promise.all(cacheKeys
|
||||
.filter(key => key.startsWith(cacheNamePrefix) && key !== cacheName)
|
||||
.map(key => caches.delete(key)));
|
||||
}
|
||||
|
||||
async function onFetch(event) {
|
||||
let cachedResponse = null;
|
||||
if (event.request.method === 'GET') {
|
||||
// For all navigation requests, try to serve index.html from cache,
|
||||
// unless that request is for an offline resource.
|
||||
// If you need some URLs to be server-rendered, edit the following check to exclude those URLs
|
||||
const shouldServeIndexHtml = event.request.mode === 'navigate'
|
||||
&& !manifestUrlList.some(url => url === event.request.url);
|
||||
|
||||
const request = shouldServeIndexHtml ? 'index.html' : event.request;
|
||||
const cache = await caches.open(cacheName);
|
||||
cachedResponse = await cache.match(request);
|
||||
}
|
||||
|
||||
return cachedResponse || fetch(event.request);
|
||||
}
|
||||
30
PlaylistShared.Pwa/.dockerignore
Normal file
30
PlaylistShared.Pwa/.dockerignore
Normal file
@@ -0,0 +1,30 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
!**/.gitignore
|
||||
!.git/HEAD
|
||||
!.git/config
|
||||
!.git/packed-refs
|
||||
!.git/refs/heads/**
|
||||
19
PlaylistShared.Pwa/App.razor
Normal file
19
PlaylistShared.Pwa/App.razor
Normal file
@@ -0,0 +1,19 @@
|
||||
<CascadingAuthenticationState>
|
||||
<Router AppAssembly="@typeof(App).Assembly" NotFoundPage="typeof(Pages.NotFound)" >
|
||||
<Found Context="routeData">
|
||||
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
|
||||
<NotAuthorized>
|
||||
@if (context.User.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
<RedirectToLogin />
|
||||
}
|
||||
else
|
||||
{
|
||||
<p role="alert">You are not authorized to access this resource.</p>
|
||||
}
|
||||
</NotAuthorized>
|
||||
</AuthorizeRouteView>
|
||||
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
|
||||
</Found>
|
||||
</Router>
|
||||
</CascadingAuthenticationState>
|
||||
41
PlaylistShared.Pwa/Dockerfile
Normal file
41
PlaylistShared.Pwa/Dockerfile
Normal file
@@ -0,0 +1,41 @@
|
||||
# ---- Stage 1: Build ----
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
|
||||
# Устанавливаем Python (необходим для WebAssembly компиляции)
|
||||
RUN apt-get update && apt-get install -y python3 && ln -s /usr/bin/python3 /usr/bin/python
|
||||
|
||||
# Устанавливаем workload для WebAssembly
|
||||
RUN dotnet workload install wasm-tools
|
||||
|
||||
# Копируем csproj всех проектов для восстановления зависимостей
|
||||
COPY ["PlaylistShared.Pwa/PlaylistShared.Pwa.csproj", "PlaylistShared.Pwa/"]
|
||||
COPY ["PlaylistShared.Shared/PlaylistShared.Shared.csproj", "PlaylistShared.Shared/"]
|
||||
|
||||
# Восстанавливаем зависимости
|
||||
RUN dotnet restore "PlaylistShared.Pwa/PlaylistShared.Pwa.csproj"
|
||||
|
||||
# Копируем весь исходный код
|
||||
COPY . .
|
||||
|
||||
# Переходим в папку проекта и публикуем
|
||||
WORKDIR "/src/PlaylistShared.Pwa"
|
||||
RUN dotnet publish "./PlaylistShared.Pwa.csproj" -c $BUILD_CONFIGURATION -o /app/publish
|
||||
|
||||
RUN ls -la /app/publish/wwwroot
|
||||
|
||||
# ---- Stage 2: Nginx ----
|
||||
FROM nginx:alpine AS final
|
||||
|
||||
# Копируем кастомную конфигурацию Nginx
|
||||
COPY PlaylistShared.Pwa/nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# Удаляем дефолтную статику Nginx
|
||||
RUN rm -rf /usr/share/nginx/html/*
|
||||
|
||||
# Копируем собранные файлы Blazor (wwwroot) в папку Nginx
|
||||
COPY --from=build /app/publish/wwwroot /usr/share/nginx/html
|
||||
|
||||
# Открываем порт 80
|
||||
EXPOSE 80
|
||||
20
PlaylistShared.Pwa/Layout/LoginDisplay.razor
Normal file
20
PlaylistShared.Pwa/Layout/LoginDisplay.razor
Normal file
@@ -0,0 +1,20 @@
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<AuthorizeView>
|
||||
<Authorized>
|
||||
<MudText Typo="Typo.body2" Class="d-inline mr-2">Здравствуйте, @context.User.Identity?.Name!</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="BeginLogOut">Выйти</MudButton>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
<MudLink Href="/login" Color="Color.Inherit" Underline="Underline.Hover" Typo="Typo.body2">Вход</MudLink>
|
||||
<MudText Class="d-inline mx-1">|</MudText>
|
||||
<MudLink Href="/register" Color="Color.Inherit" Underline="Underline.Hover" Typo="Typo.body2">Регистрация</MudLink>
|
||||
</NotAuthorized>
|
||||
</AuthorizeView>
|
||||
|
||||
@code {
|
||||
public void BeginLogOut()
|
||||
{
|
||||
Navigation.NavigateTo("/logout");
|
||||
}
|
||||
}
|
||||
100
PlaylistShared.Pwa/Layout/MainLayout.razor
Normal file
100
PlaylistShared.Pwa/Layout/MainLayout.razor
Normal file
@@ -0,0 +1,100 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<MudThemeProvider Theme="@_theme" IsDarkMode="_isDarkMode" />
|
||||
<MudPopoverProvider />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
|
||||
<MudLayout>
|
||||
<MudAppBar Elevation="1">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" OnClick="@DrawerToggle" />
|
||||
<MudText Typo="Typo.h6" Class="ml-2">Application</MudText>
|
||||
<MudSpacer />
|
||||
<LoginDisplay />
|
||||
<MudIconButton Icon="@(DarkLightModeButtonIcon)" Color="Color.Inherit" OnClick="@DarkModeToggle" Class="ml-2" />
|
||||
<MudLink Href="https://learn.microsoft.com/aspnet/core/" Target="_blank" Color="Color.Inherit" Underline="Underline.None" Class="ml-4">
|
||||
About
|
||||
</MudLink>
|
||||
</MudAppBar>
|
||||
|
||||
<MudDrawer @bind-Open="_drawerOpen" ClipMode="DrawerClipMode.Always" Elevation="2">
|
||||
<NavMenu />
|
||||
</MudDrawer>
|
||||
|
||||
<MudMainContent Class="pt-16 pa-4">
|
||||
@Body
|
||||
</MudMainContent>
|
||||
</MudLayout>
|
||||
|
||||
@code {
|
||||
private bool _drawerOpen = true;
|
||||
private bool _isDarkMode = true;
|
||||
private MudTheme? _theme;
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
base.OnInitialized();
|
||||
|
||||
_theme = new()
|
||||
{
|
||||
PaletteLight = _lightPalette,
|
||||
PaletteDark = _darkPalette,
|
||||
LayoutProperties = new LayoutProperties()
|
||||
};
|
||||
}
|
||||
|
||||
private void DrawerToggle()
|
||||
{
|
||||
_drawerOpen = !_drawerOpen;
|
||||
}
|
||||
|
||||
private void DarkModeToggle()
|
||||
{
|
||||
_isDarkMode = !_isDarkMode;
|
||||
}
|
||||
|
||||
private readonly PaletteLight _lightPalette = new()
|
||||
{
|
||||
Black = "#110e2d",
|
||||
AppbarText = "#424242",
|
||||
AppbarBackground = "rgba(255,255,255,0.8)",
|
||||
DrawerBackground = "#ffffff",
|
||||
GrayLight = "#e8e8e8",
|
||||
GrayLighter = "#f9f9f9",
|
||||
};
|
||||
|
||||
private readonly PaletteDark _darkPalette = new()
|
||||
{
|
||||
Primary = "#7e6fff",
|
||||
Surface = "#1e1e2d",
|
||||
Background = "#1a1a27",
|
||||
BackgroundGray = "#151521",
|
||||
AppbarText = "#92929f",
|
||||
AppbarBackground = "rgba(26,26,39,0.8)",
|
||||
DrawerBackground = "#1a1a27",
|
||||
ActionDefault = "#74718e",
|
||||
ActionDisabled = "#9999994d",
|
||||
ActionDisabledBackground = "#605f6d4d",
|
||||
TextPrimary = "#b2b0bf",
|
||||
TextSecondary = "#92929f",
|
||||
TextDisabled = "#ffffff33",
|
||||
DrawerIcon = "#92929f",
|
||||
DrawerText = "#92929f",
|
||||
GrayLight = "#2a2833",
|
||||
GrayLighter = "#1e1e2d",
|
||||
Info = "#4a86ff",
|
||||
Success = "#3dcb6c",
|
||||
Warning = "#ffb545",
|
||||
Error = "#ff3f5f",
|
||||
LinesDefault = "#33323e",
|
||||
TableLines = "#33323e",
|
||||
Divider = "#292838",
|
||||
OverlayLight = "#1e1e2d80",
|
||||
};
|
||||
|
||||
public string DarkLightModeButtonIcon => _isDarkMode switch
|
||||
{
|
||||
true => Icons.Material.Rounded.AutoMode,
|
||||
false => Icons.Material.Outlined.DarkMode,
|
||||
};
|
||||
}
|
||||
77
PlaylistShared.Pwa/Layout/MainLayout.razor.css
Normal file
77
PlaylistShared.Pwa/Layout/MainLayout.razor.css
Normal file
@@ -0,0 +1,77 @@
|
||||
.page {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
main {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
|
||||
}
|
||||
|
||||
.top-row {
|
||||
background-color: #f7f7f7;
|
||||
border-bottom: 1px solid #d6d5d5;
|
||||
justify-content: flex-end;
|
||||
height: 3.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.top-row ::deep a, .top-row ::deep .btn-link {
|
||||
white-space: nowrap;
|
||||
margin-left: 1.5rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.top-row ::deep a:hover, .top-row ::deep .btn-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.top-row ::deep a:first-child {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
@media (max-width: 640.98px) {
|
||||
.top-row {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.top-row ::deep a, .top-row ::deep .btn-link {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 641px) {
|
||||
.page {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
height: 100vh;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.top-row {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.top-row.auth ::deep a:first-child {
|
||||
flex: 1;
|
||||
text-align: right;
|
||||
width: 0;
|
||||
}
|
||||
|
||||
.top-row, article {
|
||||
padding-left: 2rem !important;
|
||||
padding-right: 1.5rem !important;
|
||||
}
|
||||
}
|
||||
11
PlaylistShared.Pwa/Layout/NavMenu.razor
Normal file
11
PlaylistShared.Pwa/Layout/NavMenu.razor
Normal file
@@ -0,0 +1,11 @@
|
||||
<MudNavMenu>
|
||||
<MudNavLink Href="/" Match="NavLinkMatch.All" Icon="@Icons.Material.Filled.Home">Главная</MudNavLink>
|
||||
<AuthorizeView>
|
||||
<Authorized>
|
||||
<MudNavLink Href="/my-playlists" Icon="@Icons.Material.Filled.QueueMusic">Мои плейлисты</MudNavLink>
|
||||
<MudNavLink Href="/profile" Icon="@Icons.Material.Filled.Person">Профиль</MudNavLink>
|
||||
<MudNavLink Href="/create" Icon="@Icons.Material.Filled.Add">Создать плейлист</MudNavLink>
|
||||
<MudNavLink Href="/my" Icon="@Icons.Material.Filled.List">Мои ссылки</MudNavLink>
|
||||
</Authorized>
|
||||
</AuthorizeView>
|
||||
</MudNavMenu>
|
||||
24
PlaylistShared.Pwa/Pages/AuthCallback.razor
Normal file
24
PlaylistShared.Pwa/Pages/AuthCallback.razor
Normal file
@@ -0,0 +1,24 @@
|
||||
@page "/auth-callback"
|
||||
@using PlaylistShared.Pwa.Services
|
||||
@inject NavigationManager Navigation
|
||||
@inject AuthStateProvider AuthProvider
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
@code {
|
||||
[Parameter] public string? Token { get; set; }
|
||||
[Parameter] public string? RefreshToken { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Token) && !string.IsNullOrEmpty(RefreshToken))
|
||||
{
|
||||
await AuthProvider.MarkUserAsAuthenticated(Token, RefreshToken);
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Ошибка аутентификации через Яндекс", Severity.Error);
|
||||
Navigation.NavigateTo("/login");
|
||||
}
|
||||
}
|
||||
}
|
||||
18
PlaylistShared.Pwa/Pages/Home.razor
Normal file
18
PlaylistShared.Pwa/Pages/Home.razor
Normal file
@@ -0,0 +1,18 @@
|
||||
@page "/"
|
||||
|
||||
<PageTitle>Home</PageTitle>
|
||||
|
||||
<MudText Typo="Typo.h3" GutterBottom="true">Hello, world!</MudText>
|
||||
<MudText Class="mb-8">Welcome to your new app, powered by MudBlazor and the .NET 10 Template!</MudText>
|
||||
|
||||
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Dense="true" Class="mb-6">
|
||||
Before authentication will function correctly, you must configure your provider details in <code>Program.cs</code>.
|
||||
</MudAlert>
|
||||
|
||||
|
||||
<MudAlert Severity="Severity.Normal" ContentAlignment="HorizontalAlignment.Start">
|
||||
You can find documentation and examples on our website here:
|
||||
<MudLink Href="https://mudblazor.com" Target="_blank" Typo="Typo.body2" Color="Color.Primary">
|
||||
<b>www.mudblazor.com</b>
|
||||
</MudLink>
|
||||
</MudAlert>
|
||||
75
PlaylistShared.Pwa/Pages/Login.razor
Normal file
75
PlaylistShared.Pwa/Pages/Login.razor
Normal file
@@ -0,0 +1,75 @@
|
||||
@page "/login"
|
||||
@using PlaylistShared.Shared.DTO
|
||||
@using PlaylistShared.Pwa.Services
|
||||
@inject HttpClient Http
|
||||
@inject AuthStateProvider AuthProvider
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Small" Class="mt-16">
|
||||
<MudCard>
|
||||
<MudCardContent Class="text-center">
|
||||
<MudText Typo="Typo.h5" Class="mb-4">Вход в PlaylistShared</MudText>
|
||||
|
||||
<MudText Typo="Typo.body2" Class="mb-6">
|
||||
Войдите через учётную запись Keycloak или используйте локальный аккаунт.
|
||||
</MudText>
|
||||
|
||||
<!-- Кнопка входа через Keycloak -->
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="LoginWithKeycloak" StartIcon="@Icons.Material.Filled.Login" FullWidth="true" Class="mb-4">
|
||||
Войти через Keycloak
|
||||
</MudButton>
|
||||
|
||||
<MudDivider Class="my-4">или</MudDivider>
|
||||
|
||||
<!-- Локальная форма входа -->
|
||||
<MudTextField @bind-Value="_loginModel.Username" Label="Имя пользователя" Variant="Variant.Outlined" FullWidth="true" Class="mb-3" />
|
||||
<MudTextField @bind-Value="_loginModel.Password" Label="Пароль" Variant="Variant.Outlined" FullWidth="true" Type="InputType.Password" />
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Secondary" OnClick="LocalLogin" FullWidth="true" Class="mt-4">
|
||||
Войти (локально)
|
||||
</MudButton>
|
||||
|
||||
<MudText Class="mt-4" Typo="Typo.body2">
|
||||
Нет аккаунта? <MudLink Href="/register">Зарегистрироваться</MudLink>
|
||||
</MudText>
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private LoginModel _loginModel = new();
|
||||
|
||||
private void LoginWithKeycloak()
|
||||
{
|
||||
Navigation.NavigateTo("/api/openid/login", true);
|
||||
}
|
||||
|
||||
private async Task LocalLogin()
|
||||
{
|
||||
var response = await Http.PostAsJsonAsync("/api/account/login", _loginModel);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadFromJsonAsync<ApiResponse<LoginResponse>>();
|
||||
if (result?.Success == true && result.Data != null)
|
||||
{
|
||||
await AuthProvider.MarkUserAsAuthenticated(result.Data.Token, result.Data.RefreshToken);
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result?.Error?.Message ?? "Ошибка входа", Severity.Error);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Неверное имя пользователя или пароль", Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
public class LoginModel
|
||||
{
|
||||
public string Username { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
}
|
||||
}
|
||||
12
PlaylistShared.Pwa/Pages/Logout.razor
Normal file
12
PlaylistShared.Pwa/Pages/Logout.razor
Normal file
@@ -0,0 +1,12 @@
|
||||
@page "/logout"
|
||||
@using PlaylistShared.Pwa.Services
|
||||
@inject AuthStateProvider AuthProvider
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@code {
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await AuthProvider.MarkUserAsLoggedOut();
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
}
|
||||
125
PlaylistShared.Pwa/Pages/MyPlaylists.razor
Normal file
125
PlaylistShared.Pwa/Pages/MyPlaylists.razor
Normal file
@@ -0,0 +1,125 @@
|
||||
@page "/my-playlists"
|
||||
@attribute [Authorize]
|
||||
@using PlaylistShared.Shared.DTO
|
||||
@inject HttpClient Http
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Large" Class="mt-8">
|
||||
<MudCard>
|
||||
<MudCardHeader>
|
||||
<CardHeaderContent>
|
||||
<MudText Typo="Typo.h5">Мои плейлисты</MudText>
|
||||
</CardHeaderContent>
|
||||
<CardHeaderActions>
|
||||
<!-- Явно указываем T="bool" для MudSwitch -->
|
||||
<MudSwitch T="bool" @bind-Checked="_showOnlyShared" Color="Color.Primary" Label="Только расшаренные" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Refresh" OnClick="LoadPlaylists" />
|
||||
</CardHeaderActions>
|
||||
</MudCardHeader>
|
||||
<MudCardContent>
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate />
|
||||
}
|
||||
else if (_playlists == null || !_playlists.Any())
|
||||
{
|
||||
<MudText>Плейлисты не найдены. Убедитесь, что вы сохранили корректный токен Яндекс.Музыки.</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@FilteredPlaylists" Hover="true" Breakpoint="Breakpoint.Sm">
|
||||
<HeaderContent>
|
||||
<MudTh>Название</MudTh>
|
||||
<MudTh>Треков</MudTh>
|
||||
<MudTh>Статус</MudTh>
|
||||
<MudTh></MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd><MudText>@context.Title</MudText></MudTd>
|
||||
<MudTd>@context.TrackCount</MudTd>
|
||||
<MudTd>
|
||||
<!-- Явно указываем T="string" для MudChip -->
|
||||
@if (context.IsShared)
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Color="Color.Success">Расшарен</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Color="Color.Default">Не расшарен</MudChip>
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
@if (!context.IsShared)
|
||||
{
|
||||
<MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="() => SharePlaylist(context)">Поделиться</MudButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Text" Color="Color.Secondary" OnClick="() => GoToShared(context)">Управлять</MudButton>
|
||||
}
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
}
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private List<YandexPlaylistInfo> _playlists;
|
||||
private bool _loading = true;
|
||||
private bool _showOnlyShared = false;
|
||||
|
||||
private List<YandexPlaylistInfo> FilteredPlaylists => _showOnlyShared ? _playlists?.Where(p => p.IsShared).ToList() : _playlists;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await LoadPlaylists();
|
||||
}
|
||||
|
||||
private async Task LoadPlaylists()
|
||||
{
|
||||
_loading = true;
|
||||
try
|
||||
{
|
||||
var response = await Http.GetFromJsonAsync<ApiResponse<List<YandexPlaylistInfo>>>("/api/playlist/my");
|
||||
if (response?.Success == true)
|
||||
_playlists = response.Data;
|
||||
else
|
||||
Snackbar.Add("Ошибка загрузки плейлистов", Severity.Error);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Ошибка: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_loading = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SharePlaylist(YandexPlaylistInfo playlist)
|
||||
{
|
||||
var request = new SharePlaylistRequest { Kind = playlist.Kind, OwnerUid = playlist.OwnerUid };
|
||||
var response = await Http.PostAsJsonAsync("/api/playlist/share", request);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
Snackbar.Add("Плейлист расшарен", Severity.Success);
|
||||
await LoadPlaylists();
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Ошибка расшаривания", Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void GoToShared(YandexPlaylistInfo playlist)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(playlist.ShareToken))
|
||||
Navigation.NavigateTo($"/shared/{playlist.ShareToken}");
|
||||
else
|
||||
Snackbar.Add("Ошибка: токен расшаривания не найден", Severity.Error);
|
||||
}
|
||||
}
|
||||
9
PlaylistShared.Pwa/Pages/NotFound.razor
Normal file
9
PlaylistShared.Pwa/Pages/NotFound.razor
Normal file
@@ -0,0 +1,9 @@
|
||||
@page "/not-found"
|
||||
@layout MainLayout
|
||||
|
||||
<PageTitle>Not Found</PageTitle>
|
||||
|
||||
<MudText Typo="Typo.h3" GutterBottom="true">404 - Page Not Found</MudText>
|
||||
<MudText Class="mb-8">Sorry, the content you are looking for does not exist.</MudText>
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Href="/">Go to Home</MudButton>
|
||||
72
PlaylistShared.Pwa/Pages/Profile.razor
Normal file
72
PlaylistShared.Pwa/Pages/Profile.razor
Normal file
@@ -0,0 +1,72 @@
|
||||
@page "/profile"
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using PlaylistShared.Shared.DTO
|
||||
@attribute [Authorize]
|
||||
@inject HttpClient Http
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Small" Class="mt-8">
|
||||
<MudCard>
|
||||
<MudCardHeader>
|
||||
<CardHeaderContent>
|
||||
<MudText Typo="Typo.h5">Личный кабинет</MudText>
|
||||
</CardHeaderContent>
|
||||
</MudCardHeader>
|
||||
<MudCardContent>
|
||||
<MudText Typo="Typo.body2" Class="mb-4">Здесь вы можете указать токен доступа к Яндекс.Музыке.</MudText>
|
||||
<MudTextField @bind-Value="_token" Label="Токен Яндекс.Музыки" Variant="Variant.Outlined" FullWidth="true" />
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="SaveToken" Class="mt-4" FullWidth="true">Сохранить токен</MudButton>
|
||||
<MudText Class="mt-4" Typo="Typo.body2">Статус: @_statusText</MudText>
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private string _token = "";
|
||||
private string _statusText = "Загрузка...";
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await LoadStatus();
|
||||
}
|
||||
|
||||
private async Task LoadStatus()
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await Http.GetFromJsonAsync<ApiResponse<YandexTokenStatus>>("/api/yandextoken/status");
|
||||
if (response?.Success == true)
|
||||
{
|
||||
_statusText = response.Data.HasToken
|
||||
? $"Токен установлен{(response.Data.IsValid ? "" : " (просрочен)")}"
|
||||
: "Токен не установлен";
|
||||
}
|
||||
}
|
||||
catch { _statusText = "Не удалось загрузить статус"; }
|
||||
}
|
||||
|
||||
private async Task SaveToken()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_token))
|
||||
{
|
||||
Snackbar.Add("Введите токен", Severity.Warning);
|
||||
return;
|
||||
}
|
||||
|
||||
var request = new SetYandexTokenRequest { Token = _token };
|
||||
var response = await Http.PostAsJsonAsync("/api/yandextoken/set", request);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
Snackbar.Add("Токен сохранён", Severity.Success);
|
||||
await LoadStatus();
|
||||
_token = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Ошибка сохранения токена", Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
public class YandexTokenStatus { public bool HasToken { get; set; } public bool IsValid { get; set; } }
|
||||
public class SetYandexTokenRequest { public string Token { get; set; } }
|
||||
}
|
||||
67
PlaylistShared.Pwa/Pages/Register.razor
Normal file
67
PlaylistShared.Pwa/Pages/Register.razor
Normal file
@@ -0,0 +1,67 @@
|
||||
@page "/register"
|
||||
@inject HttpClient Http
|
||||
@inject AuthStateProvider AuthProvider
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Small" Class="mt-16">
|
||||
<MudCard>
|
||||
<MudCardContent Class="text-center">
|
||||
<MudText Typo="Typo.h5" Class="mb-4">Регистрация</MudText>
|
||||
|
||||
<MudTextField @bind-Value="_model.Username" Label="Имя пользователя" Variant="Variant.Outlined" FullWidth="true" Class="mb-3" />
|
||||
<MudTextField @bind-Value="_model.Email" Label="Email" Variant="Variant.Outlined" FullWidth="true" Class="mb-3" />
|
||||
<MudTextField @bind-Value="_model.Password" Label="Пароль" Variant="Variant.Outlined" FullWidth="true" Type="InputType.Password" />
|
||||
<MudTextField @bind-Value="_model.ConfirmPassword" Label="Подтверждение пароля" Variant="Variant.Outlined" FullWidth="true" Type="InputType.Password" />
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="OnRegister" FullWidth="true" Class="mt-4">
|
||||
Зарегистрироваться
|
||||
</MudButton>
|
||||
|
||||
<MudText Class="mt-4" Typo="Typo.body2">
|
||||
Уже есть аккаунт? <MudLink Href="/login">Войти</MudLink>
|
||||
</MudText>
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private RegisterModel _model = new();
|
||||
|
||||
private async Task OnRegister()
|
||||
{
|
||||
if (_model.Password != _model.ConfirmPassword)
|
||||
{
|
||||
Snackbar.Add("Пароли не совпадают", Severity.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
var response = await Http.PostAsJsonAsync("/api/account/register", _model);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadFromJsonAsync<ApiResponse<LoginResponse>>();
|
||||
if (result?.Success == true)
|
||||
{
|
||||
await AuthProvider.MarkUserAsAuthenticated(result.Data.Token, result.Data.RefreshToken);
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result?.Error?.Message ?? "Ошибка регистрации", Severity.Error);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var error = await response.Content.ReadFromJsonAsync<ApiResponse<object>>();
|
||||
Snackbar.Add(error?.Error?.Message ?? "Ошибка регистрации", Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
public class RegisterModel
|
||||
{
|
||||
public string Username { get; set; }
|
||||
public string Email { get; set; }
|
||||
public string Password { get; set; }
|
||||
public string ConfirmPassword { get; set; }
|
||||
}
|
||||
}
|
||||
163
PlaylistShared.Pwa/Pages/SharedPlaylistView.razor
Normal file
163
PlaylistShared.Pwa/Pages/SharedPlaylistView.razor
Normal file
@@ -0,0 +1,163 @@
|
||||
@page "/shared/{token}"
|
||||
@attribute [Authorize]
|
||||
@using PlaylistShared.Shared.DTO
|
||||
@using PlaylistShared.Shared.Enums
|
||||
@using PlaylistShared.Pwa.Services
|
||||
@using PlaylistShared.Shared.Models
|
||||
@inject HttpClient Http
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
@inject AuthenticationStateProvider AuthProvider
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Large" Class="mt-8">
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate />
|
||||
}
|
||||
else if (_playlist == null)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error">Плейлист не найден или у вас нет доступа</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudCard>
|
||||
<MudCardHeader>
|
||||
<CardHeaderContent>
|
||||
<MudText Typo="Typo.h5">@_playlist.Title</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Владелец: @_playlist.Creator?.UserName</MudText>
|
||||
</CardHeaderContent>
|
||||
</MudCardHeader>
|
||||
<MudCardContent>
|
||||
@if (_isCreator)
|
||||
{
|
||||
<MudPaper Class="pa-4 mb-4" Elevation="0" Style="background-color: rgba(0,0,0,0.05); border-radius: 8px;">
|
||||
<MudText Typo="Typo.h6" GutterBottom>Настройки доступа</MudText>
|
||||
<MudGrid>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudSelect T="ViewPermission" Label="Просмотр" @bind-Value="_editPermissions.ViewPermission" Variant="Variant.Outlined" FullWidth="true">
|
||||
<MudSelectItem Value="ViewPermission.Everyone">Все</MudSelectItem>
|
||||
<MudSelectItem Value="ViewPermission.AuthorizedOnly">Только авторизованные</MudSelectItem>
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudSelect T="EditPermission" Label="Добавление треков" @bind-Value="_editPermissions.AddPermission" Variant="Variant.Outlined" FullWidth="true">
|
||||
<MudSelectItem Value="EditPermission.Everyone">Все</MudSelectItem>
|
||||
<MudSelectItem Value="EditPermission.AuthorizedOnly">Только авторизованные</MudSelectItem>
|
||||
<MudSelectItem Value="EditPermission.AddedByUserOnly">Только добавивший</MudSelectItem>
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudSelect T="EditPermission" Label="Удаление треков" @bind-Value="_editPermissions.RemovePermission" Variant="Variant.Outlined" FullWidth="true">
|
||||
<MudSelectItem Value="EditPermission.Everyone">Все</MudSelectItem>
|
||||
<MudSelectItem Value="EditPermission.AuthorizedOnly">Только авторизованные</MudSelectItem>
|
||||
<MudSelectItem Value="EditPermission.AddedByUserOnly">Только добавивший</MudSelectItem>
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="SavePermissions" Disabled="_savingPermissions">
|
||||
@if (_savingPermissions)
|
||||
{
|
||||
<MudProgressCircular Size="Size.Small" Indeterminate />
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
<span>Сохранить</span>
|
||||
}
|
||||
</MudButton>
|
||||
</MudPaper>
|
||||
}
|
||||
|
||||
<!-- Здесь будет отображение треков и управление -->
|
||||
<MudText>Функционал управления треками в разработке</MudText>
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
}
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
[Parameter] public string Token { get; set; }
|
||||
|
||||
private SharedPlaylistDto? _playlist;
|
||||
private bool _loading = true;
|
||||
private bool _isCreator;
|
||||
private UpdatePermissionsDto _editPermissions = new();
|
||||
private bool _savingPermissions;
|
||||
private string? _currentUserId;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var authState = await AuthProvider.GetAuthenticationStateAsync();
|
||||
_currentUserId = authState.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
||||
await LoadPlaylist();
|
||||
}
|
||||
|
||||
private async Task LoadPlaylist()
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await Http.GetFromJsonAsync<ApiResponse<SharedPlaylistDto>>($"/api/sharedplaylist/{Token}");
|
||||
if (response?.Success == true)
|
||||
{
|
||||
_playlist = response.Data;
|
||||
_isCreator = _playlist.CreatorUserId.ToString() == _currentUserId;
|
||||
if (_isCreator)
|
||||
{
|
||||
_editPermissions = new UpdatePermissionsDto
|
||||
{
|
||||
ViewPermission = _playlist.ViewPermission,
|
||||
AddPermission = _playlist.AddPermission,
|
||||
RemovePermission = _playlist.RemovePermission
|
||||
};
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(response?.Error?.Message ?? "Не удалось загрузить плейлист", Severity.Error);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Ошибка: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_loading = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SavePermissions()
|
||||
{
|
||||
_savingPermissions = true;
|
||||
try
|
||||
{
|
||||
var response = await Http.PutAsJsonAsync($"/api/sharedplaylist/{Token}/permissions", _editPermissions);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadFromJsonAsync<ApiResponse<SharedPlaylistDto>>();
|
||||
if (result?.Success == true)
|
||||
{
|
||||
_playlist = result.Data;
|
||||
Snackbar.Add("Права доступа обновлены", Severity.Success);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result?.Error?.Message ?? "Ошибка обновления", Severity.Error);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Ошибка сохранения прав", Severity.Error);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Ошибка: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_savingPermissions = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
27
PlaylistShared.Pwa/PlaylistShared.Pwa.csproj
Normal file
27
PlaylistShared.Pwa/PlaylistShared.Pwa.csproj
Normal file
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<OverrideHtmlAssetPlaceholders>true</OverrideHtmlAssetPlaceholders>
|
||||
<ServiceWorkerAssetsManifest>service-worker-assets.js</ServiceWorkerAssetsManifest>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="10.*" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="10.*" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="10.*" />
|
||||
<PackageReference Include="MudBlazor" Version="9.*" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.17.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PlaylistShared.Shared\PlaylistShared.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ServiceWorker Include="wwwroot\\service-worker.js" PublishedContent="wwwroot\\service-worker.published.js" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
41
PlaylistShared.Pwa/Program.cs
Normal file
41
PlaylistShared.Pwa/Program.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
||||
using MudBlazor.Services;
|
||||
using PlaylistShared.Pwa;
|
||||
using PlaylistShared.Pwa.Services;
|
||||
|
||||
internal class Program
|
||||
{
|
||||
private static async global::System.Threading.Tasks.Task Main(string[] args)
|
||||
{
|
||||
var builder = WebAssemblyHostBuilder.CreateDefault(args);
|
||||
builder.RootComponents.Add<App>("#app");
|
||||
builder.RootComponents.Add<HeadOutlet>("head::after");
|
||||
|
||||
builder.Services.AddMudServices();
|
||||
builder.Services.AddScoped(sp =>
|
||||
{
|
||||
var apiUrl = builder.Configuration["ApiBaseUrl"] ?? builder.HostEnvironment.BaseAddress;
|
||||
return new HttpClient { BaseAddress = new Uri(apiUrl) };
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<TokenStorage>();
|
||||
builder.Services.AddScoped<AuthStateProvider>();
|
||||
builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<AuthStateProvider>());
|
||||
builder.Services.AddScoped<ApiClient>();
|
||||
|
||||
/*
|
||||
builder.Services.AddOidcAuthentication(options =>
|
||||
{
|
||||
// Configure your authentication provider options here.
|
||||
// For more information, see https://aka.ms/blazor-standalone-auth
|
||||
builder.Configuration.Bind("Local", options.ProviderOptions);
|
||||
});
|
||||
*/
|
||||
builder.Services.AddAuthorizationCore();
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
|
||||
await builder.Build().RunAsync();
|
||||
}
|
||||
}
|
||||
15
PlaylistShared.Pwa/Properties/launchSettings.json
Normal file
15
PlaylistShared.Pwa/Properties/launchSettings.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
|
||||
"applicationUrl": "https://localhost:7225;http://localhost:5181",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
19
PlaylistShared.Pwa/Services/ApiClient.cs
Normal file
19
PlaylistShared.Pwa/Services/ApiClient.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using PlaylistShared.Shared.DTO;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace PlaylistShared.Pwa.Services;
|
||||
|
||||
public class ApiClient
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
|
||||
public ApiClient(HttpClient http) => _http = http;
|
||||
|
||||
public async Task<LoginResponse?> RefreshTokenAsync(string? refreshToken)
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/account/refresh-token", new RefreshTokenRequest { RefreshToken = refreshToken });
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<LoginResponse>>();
|
||||
return apiResponse?.Data;
|
||||
}
|
||||
}
|
||||
101
PlaylistShared.Pwa/Services/AuthStateProvider.cs
Normal file
101
PlaylistShared.Pwa/Services/AuthStateProvider.cs
Normal file
@@ -0,0 +1,101 @@
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace PlaylistShared.Pwa.Services;
|
||||
|
||||
public class AuthStateProvider : AuthenticationStateProvider, IDisposable
|
||||
{
|
||||
private readonly TokenStorage _tokenStorage;
|
||||
private readonly ApiClient _apiClient;
|
||||
private readonly HttpClient _http;
|
||||
private Timer? _refreshTimer;
|
||||
private ClaimsPrincipal _currentUser = new(new ClaimsIdentity());
|
||||
|
||||
public AuthStateProvider(TokenStorage tokenStorage, ApiClient apiClient, HttpClient http)
|
||||
{
|
||||
_tokenStorage = tokenStorage;
|
||||
_apiClient = apiClient;
|
||||
_http = http;
|
||||
}
|
||||
|
||||
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
var (token, refreshToken) = await _tokenStorage.GetTokensAsync();
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return new AuthenticationState(_currentUser);
|
||||
|
||||
var principal = ParseToken(token);
|
||||
if (principal == null)
|
||||
return new AuthenticationState(_currentUser);
|
||||
|
||||
_currentUser = principal;
|
||||
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
ScheduleTokenRefresh(token, refreshToken);
|
||||
return new AuthenticationState(principal);
|
||||
}
|
||||
|
||||
public async Task MarkUserAsAuthenticated(string token, string refreshToken)
|
||||
{
|
||||
await _tokenStorage.SetTokensAsync(token, refreshToken);
|
||||
var principal = ParseToken(token);
|
||||
_currentUser = principal ?? new ClaimsPrincipal(new ClaimsIdentity());
|
||||
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
|
||||
public async Task MarkUserAsLoggedOut()
|
||||
{
|
||||
await _tokenStorage.ClearTokensAsync();
|
||||
_currentUser = new ClaimsPrincipal(new ClaimsIdentity());
|
||||
_http.DefaultRequestHeaders.Authorization = null;
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
|
||||
private ClaimsPrincipal? ParseToken(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwt = handler.ReadJwtToken(token);
|
||||
var identity = new ClaimsIdentity(jwt.Claims, "jwt");
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void ScheduleTokenRefresh(string token, string? refreshToken)
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwt = handler.ReadJwtToken(token);
|
||||
var expiresAt = jwt.ValidTo;
|
||||
var timeToExpiry = expiresAt - DateTime.UtcNow;
|
||||
var refreshTime = timeToExpiry - TimeSpan.FromMinutes(5);
|
||||
|
||||
if (refreshTime > TimeSpan.Zero && !string.IsNullOrEmpty(refreshToken))
|
||||
{
|
||||
_refreshTimer?.Dispose();
|
||||
_refreshTimer = new Timer(async _ =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var newToken = await _apiClient.RefreshTokenAsync(refreshToken);
|
||||
if (newToken != null)
|
||||
await MarkUserAsAuthenticated(newToken.Token, newToken.RefreshToken);
|
||||
else
|
||||
await MarkUserAsLoggedOut();
|
||||
}
|
||||
catch
|
||||
{
|
||||
await MarkUserAsLoggedOut();
|
||||
}
|
||||
}, null, (int)refreshTime.TotalMilliseconds, Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _refreshTimer?.Dispose();
|
||||
}
|
||||
31
PlaylistShared.Pwa/Services/TokenStorage.cs
Normal file
31
PlaylistShared.Pwa/Services/TokenStorage.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace PlaylistShared.Pwa.Services;
|
||||
|
||||
public class TokenStorage
|
||||
{
|
||||
private readonly IJSRuntime _js;
|
||||
private const string TokenKey = "jwt_token";
|
||||
private const string RefreshTokenKey = "refresh_token";
|
||||
|
||||
public TokenStorage(IJSRuntime js) => _js = js;
|
||||
|
||||
public async Task SetTokensAsync(string token, string refreshToken)
|
||||
{
|
||||
await _js.InvokeVoidAsync("localStorage.setItem", TokenKey, token);
|
||||
await _js.InvokeVoidAsync("localStorage.setItem", RefreshTokenKey, refreshToken);
|
||||
}
|
||||
|
||||
public async Task<(string? token, string? refreshToken)> GetTokensAsync()
|
||||
{
|
||||
var token = await _js.InvokeAsync<string>("localStorage.getItem", TokenKey);
|
||||
var refreshToken = await _js.InvokeAsync<string>("localStorage.getItem", RefreshTokenKey);
|
||||
return (token, refreshToken);
|
||||
}
|
||||
|
||||
public async Task ClearTokensAsync()
|
||||
{
|
||||
await _js.InvokeVoidAsync("localStorage.removeItem", TokenKey);
|
||||
await _js.InvokeVoidAsync("localStorage.removeItem", RefreshTokenKey);
|
||||
}
|
||||
}
|
||||
15
PlaylistShared.Pwa/_Imports.razor
Normal file
15
PlaylistShared.Pwa/_Imports.razor
Normal file
@@ -0,0 +1,15 @@
|
||||
@using System.Net.Http
|
||||
@using System.Net.Http.Json
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.AspNetCore.Components.Web.Virtualization
|
||||
@using Microsoft.AspNetCore.Components.WebAssembly.Http
|
||||
@using Microsoft.JSInterop
|
||||
@using PlaylistShared.Pwa
|
||||
@using PlaylistShared.Pwa.Layout
|
||||
@using PlaylistShared.Pwa.Services
|
||||
@using MudBlazor
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using PlaylistShared.Shared.DTO
|
||||
55
PlaylistShared.Pwa/nginx.conf
Normal file
55
PlaylistShared.Pwa/nginx.conf
Normal file
@@ -0,0 +1,55 @@
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
# Сжатие
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/wasm application/json;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Для Service Worker – запрещаем кэширование, чтобы он всегда был свежим
|
||||
location = /service-worker.js {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache";
|
||||
add_header Expires "0";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# Для файла манифеста Service Worker assets – тоже не кэшируем
|
||||
location = /service-worker-assets.js {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache";
|
||||
add_header Expires "0";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# Основной SPA fallback: все неизвестные пути отдаём через index.html
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html?$args;
|
||||
}
|
||||
|
||||
# Кэширование статических ресурсов (css, js, изображения, шрифты)
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Для .wasm файлов – правильный MIME‑тип и кэширование
|
||||
location ~* \.wasm$ {
|
||||
default_type application/wasm;
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
}
|
||||
}
|
||||
3
PlaylistShared.Pwa/wwwroot/appsettings.Development.json
Normal file
3
PlaylistShared.Pwa/wwwroot/appsettings.Development.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"ApiBaseUrl": "http://localhost:5053"
|
||||
}
|
||||
3
PlaylistShared.Pwa/wwwroot/appsettings.json
Normal file
3
PlaylistShared.Pwa/wwwroot/appsettings.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"ApiBaseUrl": ""
|
||||
}
|
||||
110
PlaylistShared.Pwa/wwwroot/css/app.css
Normal file
110
PlaylistShared.Pwa/wwwroot/css/app.css
Normal file
@@ -0,0 +1,110 @@
|
||||
html, body {
|
||||
font-family: 'Roboto', Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
#blazor-error-ui {
|
||||
color-scheme: light;
|
||||
background: rgba(30, 30, 45, 0.95);
|
||||
color: #f5f5f7;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
|
||||
backdrop-filter: blur(6px);
|
||||
box-sizing: border-box;
|
||||
display: none;
|
||||
left: 50%;
|
||||
right: auto;
|
||||
bottom: 1rem;
|
||||
width: min(52rem, calc(100vw - 2rem));
|
||||
transform: translateX(-50%);
|
||||
padding: 0.85rem 4rem 0.85rem 1rem;
|
||||
position: fixed;
|
||||
z-index: 2000;
|
||||
}
|
||||
|
||||
#blazor-error-ui .reload {
|
||||
color: #594AE2;
|
||||
font-weight: 600;
|
||||
margin-left: 0.5rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#blazor-error-ui .reload:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#blazor-error-ui .dismiss {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: 1rem;
|
||||
top: 0.55rem;
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
line-height: 1.65rem;
|
||||
text-align: center;
|
||||
border-radius: 999px;
|
||||
color: #d7d7df;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
#blazor-error-ui .dismiss:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.blazor-error-boundary {
|
||||
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121;
|
||||
padding: 1rem 1rem 1rem 3.7rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.blazor-error-boundary::after {
|
||||
content: "An error has occurred."
|
||||
}
|
||||
|
||||
.loading-progress {
|
||||
position: absolute;
|
||||
display: block;
|
||||
width: 8rem;
|
||||
height: 8rem;
|
||||
inset: 20vh 0 auto 0;
|
||||
margin: 0 auto 0 auto;
|
||||
}
|
||||
|
||||
.loading-progress circle {
|
||||
fill: none;
|
||||
stroke: #e0e0e0;
|
||||
stroke-width: 0.6rem;
|
||||
transform-origin: 50% 50%;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.loading-progress circle:last-child {
|
||||
stroke: #594AE2;
|
||||
stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%;
|
||||
transition: stroke-dasharray 0.05s ease-in-out;
|
||||
}
|
||||
|
||||
.loading-progress-text {
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
inset: calc(20vh + 3.25rem) 0 auto 0.2rem;
|
||||
}
|
||||
|
||||
.loading-progress-text:after {
|
||||
content: var(--blazor-load-percentage-text, "Loading");
|
||||
}
|
||||
|
||||
code {
|
||||
color: #c02d76;
|
||||
}
|
||||
|
||||
.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder {
|
||||
color: var(--bs-secondary-color);
|
||||
text-align: end;
|
||||
}
|
||||
|
||||
.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder {
|
||||
text-align: start;
|
||||
}
|
||||
BIN
PlaylistShared.Pwa/wwwroot/favicon.png
Normal file
BIN
PlaylistShared.Pwa/wwwroot/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.5 KiB |
BIN
PlaylistShared.Pwa/wwwroot/icon-192.png
Normal file
BIN
PlaylistShared.Pwa/wwwroot/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
BIN
PlaylistShared.Pwa/wwwroot/icon-512.png
Normal file
BIN
PlaylistShared.Pwa/wwwroot/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
41
PlaylistShared.Pwa/wwwroot/index.html
Normal file
41
PlaylistShared.Pwa/wwwroot/index.html
Normal file
@@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>PlaylistShared.Pwa</title>
|
||||
<base href="/" />
|
||||
<link rel="preload" id="webassembly" />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="_content/MudBlazor/MudBlazor.min.css" />
|
||||
<link rel="stylesheet" href="css/app.css" />
|
||||
<link rel="icon" type="image/png" href="favicon.png" />
|
||||
<link href="PlaylistShared.Pwa.styles.css" rel="stylesheet" />
|
||||
<link href="manifest.webmanifest" rel="manifest" />
|
||||
<link rel="apple-touch-icon" sizes="512x512" href="icon-512.png" />
|
||||
<link rel="apple-touch-icon" sizes="192x192" href="icon-192.png" />
|
||||
<script type="importmap"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app">
|
||||
<svg class="loading-progress">
|
||||
<circle r="40%" cx="50%" cy="50%" />
|
||||
<circle r="40%" cx="50%" cy="50%" />
|
||||
</svg>
|
||||
<div class="loading-progress-text"></div>
|
||||
</div>
|
||||
|
||||
<div id="blazor-error-ui">
|
||||
An unhandled error has occurred.
|
||||
<a href="." class="reload">Reload</a>
|
||||
<span class="dismiss">🗙</span>
|
||||
</div>
|
||||
<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
|
||||
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
|
||||
<script src="_framework/blazor.webassembly#[.{fingerprint}].js"></script>
|
||||
<script>navigator.serviceWorker.register('service-worker.js', { updateViaCache: 'none' });</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
22
PlaylistShared.Pwa/wwwroot/manifest.webmanifest
Normal file
22
PlaylistShared.Pwa/wwwroot/manifest.webmanifest
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "PlaylistShared.Pwa",
|
||||
"short_name": "PlaylistShared.Pwa",
|
||||
"id": "./",
|
||||
"start_url": "./",
|
||||
"display": "standalone",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#03173d",
|
||||
"prefer_related_applications": false,
|
||||
"icons": [
|
||||
{
|
||||
"src": "icon-512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
},
|
||||
{
|
||||
"src": "icon-192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
}
|
||||
]
|
||||
}
|
||||
4
PlaylistShared.Pwa/wwwroot/service-worker.js
Normal file
4
PlaylistShared.Pwa/wwwroot/service-worker.js
Normal file
@@ -0,0 +1,4 @@
|
||||
// In development, always fetch from the network and do not enable offline support.
|
||||
// This is because caching would make development more difficult (changes would not
|
||||
// be reflected on the first load after each change).
|
||||
self.addEventListener('fetch', () => { });
|
||||
55
PlaylistShared.Pwa/wwwroot/service-worker.published.js
Normal file
55
PlaylistShared.Pwa/wwwroot/service-worker.published.js
Normal file
@@ -0,0 +1,55 @@
|
||||
// Caution! Be sure you understand the caveats before publishing an application with
|
||||
// offline support. See https://aka.ms/blazor-offline-considerations
|
||||
|
||||
self.importScripts('./service-worker-assets.js');
|
||||
self.addEventListener('install', event => event.waitUntil(onInstall(event)));
|
||||
self.addEventListener('activate', event => event.waitUntil(onActivate(event)));
|
||||
self.addEventListener('fetch', event => event.respondWith(onFetch(event)));
|
||||
|
||||
const cacheNamePrefix = 'offline-cache-';
|
||||
const cacheName = `${cacheNamePrefix}${self.assetsManifest.version}`;
|
||||
const offlineAssetsInclude = [ /\.dll$/, /\.pdb$/, /\.wasm/, /\.html/, /\.js$/, /\.json$/, /\.css$/, /\.woff$/, /\.png$/, /\.jpe?g$/, /\.gif$/, /\.ico$/, /\.blat$/, /\.dat$/, /\.webmanifest$/ ];
|
||||
const offlineAssetsExclude = [ /^service-worker\.js$/ ];
|
||||
|
||||
// Replace with your base path if you are hosting on a subfolder. Ensure there is a trailing '/'.
|
||||
const base = "/";
|
||||
const baseUrl = new URL(base, self.origin);
|
||||
const manifestUrlList = self.assetsManifest.assets.map(asset => new URL(asset.url, baseUrl).href);
|
||||
|
||||
async function onInstall(event) {
|
||||
console.info('Service worker: Install');
|
||||
|
||||
// Fetch and cache all matching items from the assets manifest
|
||||
const assetsRequests = self.assetsManifest.assets
|
||||
.filter(asset => offlineAssetsInclude.some(pattern => pattern.test(asset.url)))
|
||||
.filter(asset => !offlineAssetsExclude.some(pattern => pattern.test(asset.url)))
|
||||
.map(asset => new Request(asset.url, { integrity: asset.hash, cache: 'no-cache' }));
|
||||
await caches.open(cacheName).then(cache => cache.addAll(assetsRequests));
|
||||
}
|
||||
|
||||
async function onActivate(event) {
|
||||
console.info('Service worker: Activate');
|
||||
|
||||
// Delete unused caches
|
||||
const cacheKeys = await caches.keys();
|
||||
await Promise.all(cacheKeys
|
||||
.filter(key => key.startsWith(cacheNamePrefix) && key !== cacheName)
|
||||
.map(key => caches.delete(key)));
|
||||
}
|
||||
|
||||
async function onFetch(event) {
|
||||
let cachedResponse = null;
|
||||
if (event.request.method === 'GET') {
|
||||
// For all navigation requests, try to serve index.html from cache,
|
||||
// unless that request is for an offline resource.
|
||||
// If you need some URLs to be server-rendered, edit the following check to exclude those URLs
|
||||
const shouldServeIndexHtml = event.request.mode === 'navigate'
|
||||
&& !manifestUrlList.some(url => url === event.request.url);
|
||||
|
||||
const request = shouldServeIndexHtml ? 'index.html' : event.request;
|
||||
const cache = await caches.open(cacheName);
|
||||
cachedResponse = await cache.match(request);
|
||||
}
|
||||
|
||||
return cachedResponse || fetch(event.request);
|
||||
}
|
||||
12
PlaylistShared.Shared/DTO/AddTrackRequest.cs
Normal file
12
PlaylistShared.Shared/DTO/AddTrackRequest.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PlaylistShared.Shared.DTO;
|
||||
|
||||
public class AddTrackRequest
|
||||
{
|
||||
[JsonPropertyName("sharedPlaylistToken")]
|
||||
public string SharedPlaylistToken { get; set; } = null!;
|
||||
|
||||
[JsonPropertyName("trackIds")]
|
||||
public List<string> TrackIds { get; set; } = new();
|
||||
}
|
||||
32
PlaylistShared.Shared/DTO/ApiResponse.cs
Normal file
32
PlaylistShared.Shared/DTO/ApiResponse.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PlaylistShared.Shared.DTO;
|
||||
|
||||
/// <summary>Универсальный контейнер ответа API.</summary>
|
||||
/// <typeparam name="T">Тип данных ответа.</typeparam>
|
||||
public class ApiResponse<T>
|
||||
{
|
||||
/// <summary>Успешен ли запрос.</summary>
|
||||
[JsonPropertyName("success")]
|
||||
public bool Success { get; set; }
|
||||
|
||||
/// <summary>Данные ответа (при успехе).</summary>
|
||||
[JsonPropertyName("data")]
|
||||
public T? Data { get; set; }
|
||||
|
||||
/// <summary>Сообщение (опционально).</summary>
|
||||
[JsonPropertyName("message")]
|
||||
public string? Message { get; set; }
|
||||
|
||||
/// <summary>Ошибка (при неудаче).</summary>
|
||||
[JsonPropertyName("error")]
|
||||
public ErrorResponse? Error { get; set; }
|
||||
|
||||
/// <summary>Создаёт успешный ответ.</summary>
|
||||
public static ApiResponse<T> Ok(T data, string? message = null) =>
|
||||
new() { Success = true, Data = data, Message = message };
|
||||
|
||||
/// <summary>Создаёт ответ с ошибкой.</summary>
|
||||
public static ApiResponse<T> Fail(ErrorResponse error) =>
|
||||
new() { Success = false, Error = error };
|
||||
}
|
||||
19
PlaylistShared.Shared/DTO/ErrorResponse.cs
Normal file
19
PlaylistShared.Shared/DTO/ErrorResponse.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PlaylistShared.Shared.DTO;
|
||||
|
||||
/// <summary>Стандартный ответ сервера при ошибке.</summary>
|
||||
public class ErrorResponse
|
||||
{
|
||||
/// <summary>HTTP статус-код.</summary>
|
||||
[JsonPropertyName("statusCode")]
|
||||
public int StatusCode { get; set; }
|
||||
|
||||
/// <summary>Сообщение об ошибке.</summary>
|
||||
[JsonPropertyName("message")]
|
||||
public string Message { get; set; } = null!;
|
||||
|
||||
/// <summary>Дополнительные детали (опционально).</summary>
|
||||
[JsonPropertyName("details")]
|
||||
public string? Details { get; set; }
|
||||
}
|
||||
12
PlaylistShared.Shared/DTO/ExternalLoginCallbackRequest.cs
Normal file
12
PlaylistShared.Shared/DTO/ExternalLoginCallbackRequest.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PlaylistShared.Shared.DTO;
|
||||
|
||||
public class ExternalLoginCallbackRequest
|
||||
{
|
||||
[JsonPropertyName("code")]
|
||||
public string Code { get; set; } = null!;
|
||||
|
||||
[JsonPropertyName("state")]
|
||||
public string State { get; set; } = null!;
|
||||
}
|
||||
19
PlaylistShared.Shared/DTO/LoginRequest.cs
Normal file
19
PlaylistShared.Shared/DTO/LoginRequest.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PlaylistShared.Shared.DTO;
|
||||
|
||||
/// <summary>Запрос на вход по паролю.</summary>
|
||||
public class LoginRequest
|
||||
{
|
||||
/// <summary>Имя пользователя (логин).</summary>
|
||||
[JsonPropertyName("username")]
|
||||
public string Username { get; set; } = null!;
|
||||
|
||||
/// <summary>Пароль.</summary>
|
||||
[JsonPropertyName("password")]
|
||||
public string Password { get; set; } = null!;
|
||||
|
||||
/// <summary>Запомнить пользователя (продлить сессию).</summary>
|
||||
[JsonPropertyName("rememberMe")]
|
||||
public bool RememberMe { get; set; }
|
||||
}
|
||||
19
PlaylistShared.Shared/DTO/LoginResponse.cs
Normal file
19
PlaylistShared.Shared/DTO/LoginResponse.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PlaylistShared.Shared.DTO;
|
||||
|
||||
/// <summary>Ответ после успешного входа.</summary>
|
||||
public class LoginResponse
|
||||
{
|
||||
/// <summary>JWT токен доступа.</summary>
|
||||
[JsonPropertyName("token")]
|
||||
public string Token { get; set; } = null!;
|
||||
|
||||
/// <summary>Refresh токен для обновления сессии.</summary>
|
||||
[JsonPropertyName("refreshToken")]
|
||||
public string RefreshToken { get; set; } = null!;
|
||||
|
||||
/// <summary>Время истечения токена (UTC).</summary>
|
||||
[JsonPropertyName("expiration")]
|
||||
public DateTime Expiration { get; set; }
|
||||
}
|
||||
11
PlaylistShared.Shared/DTO/RefreshTokenRequest.cs
Normal file
11
PlaylistShared.Shared/DTO/RefreshTokenRequest.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PlaylistShared.Shared.DTO;
|
||||
|
||||
/// <summary>Запрос на обновление JWT токена.</summary>
|
||||
public class RefreshTokenRequest
|
||||
{
|
||||
/// <summary>Refresh токен, полученный при входе.</summary>
|
||||
[JsonPropertyName("refreshToken")]
|
||||
public string RefreshToken { get; set; } = null!;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user