You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
211 lines
7.8 KiB
211 lines
7.8 KiB
using AX.WebDrillServer.Data; |
|
using AX.WebDrillServer.Middlewares.Jwts; |
|
using AX.WebDrillServer.Models; |
|
using Microsoft.AspNetCore.Authorization; |
|
using Microsoft.AspNetCore.Mvc; |
|
using Microsoft.AspNetCore.Mvc.ModelBinding; |
|
using Microsoft.EntityFrameworkCore; |
|
using Microsoft.Extensions.Caching.Memory; |
|
using Microsoft.Extensions.Options; |
|
using System.Security.Authentication; |
|
using System.Security.Claims; |
|
using static BCrypt.Net.BCrypt; |
|
|
|
namespace AX.WebDrillServer.Controllers |
|
{ |
|
/// <summary> |
|
/// 账号控制器 |
|
/// </summary> |
|
[ApiController] |
|
[Authorize] |
|
[Produces("application/json")] |
|
[Route("api/[controller]")] |
|
public class AccountsController : ControllerBase |
|
{ |
|
private readonly ApplicationDbContext _context; |
|
private readonly DbSet<User> _users; |
|
|
|
private readonly IMemoryCache _memoryCache; |
|
private readonly IOptionsMonitor<JwtOptions> _jwtOptions; |
|
private readonly IJwtService _jwtService; |
|
|
|
public AccountsController( |
|
ApplicationDbContext context, |
|
IMemoryCache memoryCache, |
|
IOptionsMonitor<JwtOptions> jwtOptions, |
|
IJwtService jwtService) |
|
{ |
|
_context = context; |
|
_users = context.Users; |
|
|
|
_memoryCache = memoryCache; |
|
_jwtOptions = jwtOptions; |
|
_jwtService = jwtService; |
|
} |
|
|
|
// #region APIs |
|
|
|
// /// <summary> |
|
// /// 登录 |
|
// /// </summary> |
|
// /// <param name="dto"></param> |
|
// /// <returns></returns> |
|
// [AllowAnonymous] |
|
// [ProducesResponseType(StatusCodes.Status200OK)] |
|
// [ProducesResponseType(StatusCodes.Status400BadRequest)] |
|
// [ProducesResponseType(StatusCodes.Status401Unauthorized)] |
|
// [HttpPost("[action]")] |
|
// public async Task<ActionResult<IdentityDto>> SignIn([FromBody] SignInDto dto) |
|
// { |
|
// var user = await _users.Include(u => u.Organization) |
|
// .SingleOrDefaultAsync(u => u.Username == dto.Username); |
|
// if (user == null) |
|
// return Problem("用户名或密码错误!"); |
|
// if (!Verify(dto.Password, user.Password)) |
|
// return Problem("用户名或密码错误!"); |
|
|
|
// await _context.SaveChangesAsync(); |
|
// var claims = new List<Claim> |
|
// { |
|
// new Claim(JwtClaimTypes.Subject, user.Id), |
|
// new Claim(JwtClaimTypes.Name, user.Name ?? string.Empty), |
|
// new Claim(JwtClaimTypes.OrganizationId, user.OrganizationId ?? string.Empty), |
|
// new Claim(JwtClaimTypes.OrganizationCode, user.Organization?.Code ?? string.Empty), |
|
// }; |
|
// if (!string.IsNullOrWhiteSpace(user.OrganizationId)) |
|
// claims.Add(new Claim(JwtClaimTypes.OrganizationId, user.OrganizationId)); |
|
// if (user.Organization != null && !string.IsNullOrWhiteSpace(user.Organization.Code)) |
|
// claims.Add(new Claim(JwtClaimTypes.OrganizationCode, user.Organization.Code)); |
|
|
|
// var identity = new ClaimsIdentity(claims); |
|
// var token = _jwtService.Create(identity); |
|
// var refreshToken = Guid.NewGuid().ToString("N"); |
|
// var jwtOptions = _jwtOptions.CurrentValue; |
|
|
|
// _memoryCache.Set(refreshToken, dto.Username, DateTimeOffset.Now.AddMinutes(jwtOptions.RefreshExpires)); |
|
|
|
// var result = user.ToDto(token, refreshToken, jwtOptions.Expires); |
|
|
|
// return Ok(result); |
|
// } |
|
|
|
// /// <summary> |
|
// /// 刷新令牌。 |
|
// /// </summary> |
|
// [AllowAnonymous] |
|
// [ProducesResponseType(StatusCodes.Status200OK)] |
|
// [ProducesResponseType(StatusCodes.Status400BadRequest)] |
|
// [ProducesResponseType(StatusCodes.Status401Unauthorized)] |
|
// [HttpPost("[action]")] |
|
// public ActionResult<IdentityDto> RefreshToken([FromBody] RefreshTokenDto dto) |
|
// { |
|
// if (string.IsNullOrEmpty(dto.RefreshToken) || |
|
// string.IsNullOrEmpty(dto.Token)) |
|
// return BadRequest(); |
|
|
|
//#if RELEASE |
|
// //校验缓存中是否有该刷新令牌 |
|
// if (!_memoryCache.TryGetValue<string>(dto.RefreshToken, out _)) |
|
// return Unauthorized(); |
|
//#endif |
|
|
|
// //校验令牌是否有效 |
|
// if (!_jwtService.Validate(dto.Token, out var principal)) |
|
// return Unauthorized(); |
|
|
|
// var jwtOptions = _jwtOptions.CurrentValue; |
|
// if (principal.Identity is not ClaimsIdentity identity) |
|
// return Unauthorized(); |
|
|
|
// var newToken = _jwtService.Create(identity); |
|
|
|
// var result = new IdentityDto() |
|
// { |
|
// Token = newToken, |
|
// RefreshToken = dto.RefreshToken, |
|
// Expires = jwtOptions.Expires |
|
// }; |
|
|
|
// return Ok(result); |
|
|
|
// } |
|
|
|
// /// <summary> |
|
// /// 修改密码 |
|
// /// </summary> |
|
// /// <param name="dto"></param> |
|
// /// <returns></returns> |
|
// [Authorize] |
|
// [ProducesResponseType(StatusCodes.Status204NoContent)] |
|
// [ProducesResponseType(StatusCodes.Status400BadRequest)] |
|
// [ProducesResponseType(StatusCodes.Status401Unauthorized)] |
|
// [HttpPatch("[action]")] |
|
// public async Task<ActionResult> ChangePassword([FromBody, BindRequired] ChangePasswordDto dto) |
|
// { |
|
// try |
|
// { |
|
// await ChangePasswordAsync(dto); |
|
// return NoContent(); |
|
// } |
|
// catch (AuthenticationException e) |
|
// { |
|
// return Unauthorized(e.Message); |
|
// } |
|
// catch (Exception e) |
|
// { |
|
// return Problem(e.Message); |
|
// } |
|
// } |
|
|
|
// /// <summary> |
|
// /// 获取当前用户信息 |
|
// /// </summary> |
|
// /// <returns></returns> |
|
// [Authorize] |
|
// [ProducesResponseType(StatusCodes.Status204NoContent)] |
|
// [ProducesResponseType(StatusCodes.Status400BadRequest)] |
|
// [ProducesResponseType(StatusCodes.Status401Unauthorized)] |
|
// [ProducesResponseType(StatusCodes.Status404NotFound)] |
|
// [ProducesResponseType(StatusCodes.Status403Forbidden)] |
|
// [HttpGet("Profile")] |
|
// public async Task<ActionResult<ProfileDto>> GetProfile() |
|
// { |
|
// var currUserId = this.GetIdOfCurrentUser(); |
|
// var currUser = await _users.AsNoTracking() |
|
// .Include(e => e.Organization) |
|
// .Include(e => e.Roles!).ThenInclude(e => e.Permissions) |
|
// .Include(e => e.Roles!).ThenInclude(e => e.Pages) |
|
// .SingleOrDefaultAsync(e => e.Id == currUserId); |
|
|
|
// if (currUser is null) return NotFound(); |
|
// if (!currUser.Enabled) return Forbid(); |
|
|
|
// var result = currUser.ToProfileDto(); |
|
|
|
// return Ok(result); |
|
// } |
|
|
|
// #endregion APIs |
|
|
|
// #region Local Methods |
|
|
|
// private async ValueTask ChangePasswordAsync(ChangePasswordDto dto) |
|
// { |
|
// var userId = HttpContext.User.FindFirstValue(JwtClaimTypes.Subject); |
|
|
|
// await using var transaction = _context.Database.BeginTransaction(); |
|
|
|
// var user = await _users.SingleOrDefaultAsync(e => e.Id == userId); |
|
// if (user == default || !Verify(dto.OldPassword, user.Password)) |
|
// throw new AuthenticationException("旧密码认证失败;"); |
|
|
|
// user.Password = HashPassword(dto.NewPassword); |
|
// user.LastModificationTime = DateTime.UtcNow; |
|
|
|
// await _context.SaveChangesAsync(); |
|
// await transaction.CommitAsync(); |
|
// } |
|
|
|
// #endregion Local Methods |
|
} |
|
} |