/
Extrap
/
Network_technologies_Project
Обзор
Документация
Войти
/
Extrap
/
Network_technologies_Project
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Project/Controllers/ProfileController.cs
115 строк
4 KB
Extrap
Решил трабл с отправкой тренировки
20 дек 2025, 18:48
20 дек 2025, 18:48
77f5498
Код
Авторство
О чём код?
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Project.Interfaces; using Project.Models; using Project.Models.DTOs; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; namespace Project.Controllers { [ApiController] [Route("api/[controller]")] [Authorize] public class ProfileController : ControllerBase { private readonly IUserRepository _userRepository; public ProfileController(IUserRepository userRepository) { _userRepository = userRepository; } [HttpGet] public async Task<IActionResult> GetProfile() { // Безопасное получение ID пользователя из токена var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier) ?? User.FindFirst(JwtRegisteredClaimNames.Sub) ?? User.FindFirst("sub"); if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value)) { return Unauthorized("User ID not found in token"); } if (!Guid.TryParse(userIdClaim.Value, out Guid userId)) { return BadRequest("Invalid user ID format in token"); } try { var user = await _userRepository.GetByIdAsync(userId); return Ok(new { user.Id, user.Email, user.FirstName, user.SecondName, user.Age, user.CreatedAt }); } catch (KeyNotFoundException) { return NotFound("User not found"); } } [HttpPut] public async Task<IActionResult> UpdateProfile([FromBody] RegisterRequest request) { var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier) ?? User.FindFirst(JwtRegisteredClaimNames.Sub) ?? User.FindFirst("sub"); if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value)) { return Unauthorized("User ID not found in token"); } if (!Guid.TryParse(userIdClaim.Value, out Guid userId)) { return BadRequest("Invalid user ID format in token"); } var user = await _userRepository.GetByIdAsync(userId); user.FirstName = request.FirstName; user.SecondName = request.SecondName; user.Age = request.Age; await _userRepository.UpdateAsync(user); return Ok(new { message = "Profile updated successfully" }); } [HttpDelete] public async Task<IActionResult> DeleteProfile() { var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier) ?? User.FindFirst(JwtRegisteredClaimNames.Sub) ?? User.FindFirst("sub"); if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value)) { return Unauthorized("User ID not found in token"); } if (!Guid.TryParse(userIdClaim.Value, out Guid userId)) { return BadRequest("Invalid user ID format in token"); } await _userRepository.DeleteAsync(userId); return Ok(new { message = "Profile deleted successfully" }); } [HttpPost("logout")] public IActionResult Logout() { return Ok(new { message = "Successfully logged out" }); } } }