using Application.Domain.Entities; using Application.Models; using Infrastructure.Data; using Infrastructure.Extensions; using Infrastructure.Security; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Linq; namespace UserCenter.Controllers { [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]/[action]")] [ApiController] public class UserController : ControllerBase { private readonly IRepository _userRepo; private readonly IEncryptionService _encryptionService; public UserController(IRepository userRepo, IEncryptionService encryptionService) { this._userRepo = userRepo; this._encryptionService = encryptionService; } [HttpGet] [Authorize] public ActionResult GetUserInfo() { try { if (!User.Identity.IsAuthenticated) { ModelState.AddModelError("", "未登录"); return Unauthorized(ModelState); } var userName = User.Identity.Name; var model = this._userRepo.ReadOnlyTable() .Include(o => o.UserRoles) .ThenInclude(o => o.Role) .Where(o => o.UserName == userName) .ToList() .Select(o => new { o.UserName, o.RealName, o.IdCardNumber, o.NickName, o.Avatar, o.Sex, o.Birthday, o.Email, o.PhoneNumber, Roles = o.UserRoles.Select(o => o.Role.Name) }) .FirstOrDefault(); if (model == null) { return BadRequest(ModelState.AddModelError("用户不存在")); } return Ok(model); } catch (Exception ex) { ex.PrintStack(); return Problem(ex.Message); } } [HttpPost] [Authorize] public ActionResult ChangePassword([FromBody]ChangePasswordModel model) { try { var userName = User.Identity.Name; var user = this._userRepo.ReadOnlyTable().FirstOrDefault(o => o.UserName == userName); if (user == null) { return BadRequest(ModelState.AddModelError("用户不存在")); } if (this._encryptionService.CreatePasswordHash(model.OldPassword, user.SecurityStamp) != user.PasswordHash) { return BadRequest(ModelState.AddModelError(o => model.OldPassword, "当前密码输入错误", 1)); } if (model.OldPassword != model.ConfirmNewPassword) { return BadRequest(ModelState.AddModelError(o => model.OldPassword, "新密码确认输入错误", 2)); } user.PasswordHash = this._encryptionService.CreatePasswordHash(model.NewPassword, user.SecurityStamp); _userRepo.SaveChanges(); return Ok("密码修改成功"); } catch (Exception ex) { ex.PrintStack(); return Problem(ex.Message); } } } }