65 lines
1.7 KiB
C#
65 lines
1.7 KiB
C#
using FreeSql;
|
|
using MAX.Core.Cryptography;
|
|
using MAX.Core.DependencyInjection;
|
|
using Store.Framework.Models;
|
|
using Store.Framework.Repositorys;
|
|
using StoreHub.Services.Dtos;
|
|
using StoreHub.Services.Mappers;
|
|
|
|
namespace StoreHub.Services;
|
|
|
|
/// <summary>
|
|
/// 用户业务服务:登录校验、用户查询等用例。
|
|
/// </summary>
|
|
public interface IUserService
|
|
{
|
|
/// <summary>
|
|
/// 校验用户名/密码,成功返回用户 DTO,失败返回 null。
|
|
/// </summary>
|
|
Task<UserDto?> LoginAsync(string userName, string password);
|
|
|
|
/// <summary>
|
|
/// 根据用户ID获取用户 DTO,不存在返回 null。
|
|
/// </summary>
|
|
Task<UserDto?> GetByIdAsync(int id);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 用户业务服务实现(<see cref="IScopedDependency"/>,由 AddStoreHub 自动注册)。
|
|
/// </summary>
|
|
public class UserService : IUserService, IScopedDependency
|
|
{
|
|
private readonly IUserRepository _userRepository;
|
|
|
|
public UserService(IUserRepository userRepository)
|
|
{
|
|
_userRepository = userRepository;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<UserDto?> LoginAsync(string userName, string password)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
|
|
{
|
|
return null;
|
|
}
|
|
var sql = _userRepository.Where(u => u.UserName == userName).ToSql();
|
|
User? user = await _userRepository.Where(u => u.UserName == userName).FirstAsync();
|
|
string pwd = MD5Helper.Md5_32(password);
|
|
if (user is null || !string.Equals(user.Password, pwd, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return UserMapper.ToDto(user);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<UserDto?> GetByIdAsync(int id)
|
|
{
|
|
User? user = await _userRepository.Where(u => u.Id == id).FirstAsync();
|
|
return user is null ? null : UserMapper.ToDto(user);
|
|
}
|
|
}
|
|
|