Files
WMSlite/WmsLite.Api/Services/AuthService.cs
T
zhougfandCursor fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

66 lines
2.2 KiB
C#

using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Auth;
using WmsLite.Api.Infrastructure.Auth;
using WmsLite.Api.Repositories.Interfaces;
using WmsLite.Api.Services.Interfaces;
namespace WmsLite.Api.Services;
public class AuthService : IAuthService
{
private readonly ISysUserRepository _userRepository;
private readonly IJwtTokenService _jwtTokenService;
public AuthService(ISysUserRepository userRepository, IJwtTokenService jwtTokenService)
{
_userRepository = userRepository;
_jwtTokenService = jwtTokenService;
}
public async Task<LoginResponseDto> LoginAsync(LoginRequest request)
{
var tenantId = string.IsNullOrWhiteSpace(request.TenantId) ? "default" : request.TenantId.Trim();
var ownerCode = string.IsNullOrWhiteSpace(request.OwnerCode) ? "default" : request.OwnerCode.Trim();
var username = request.Username?.Trim() ?? string.Empty;
var password = request.Password ?? string.Empty;
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
throw new BusinessException("用户名或密码不能为空。");
}
var user = await _userRepository.GetByUsernameAsync(tenantId, ownerCode, username);
if (user is null || !user.IsEnabled)
{
throw new BusinessException("用户名或密码错误。");
}
if (!BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
{
throw new BusinessException("用户名或密码错误。");
}
var (token, expiresAt) = _jwtTokenService.CreateToken(user);
return new LoginResponseDto
{
Token = token,
ExpiresAt = expiresAt,
UserId = user.Id.ToString(),
TenantId = user.TenantId,
OwnerCode = user.OwnerCode,
DisplayName = user.DisplayName ?? user.Username,
};
}
public MeResponseDto GetCurrentUser(ICurrentUserContext userContext)
{
return new MeResponseDto
{
UserId = userContext.UserId,
TenantId = userContext.TenantId,
OwnerCode = userContext.OwnerCode,
DisplayName = userContext.DisplayName ?? userContext.UserId,
};
}
}