Toolhub / Services /UserService.cs
unifare
Initial commit: ToolHub ASP.NET Core app
5fc700d
using ToolHub.Models;
using System.Security.Cryptography;
using System.Text;
namespace ToolHub.Services;
public class UserService : IUserService
{
private readonly IFreeSql _freeSql;
public UserService(IFreeSql freeSql)
{
_freeSql = freeSql;
}
public async Task<User?> GetUserByIdAsync(int id)
{
return await _freeSql.Select<User>()
.Where(u => u.Id == id && u.IsActive)
.FirstAsync();
}
public async Task<User?> GetUserByEmailAsync(string email)
{
return await _freeSql.Select<User>()
.Where(u => u.Email == email && u.IsActive)
.FirstAsync();
}
public async Task<bool> CreateUserAsync(User user)
{
try
{
user.PasswordHash = HashPassword(user.PasswordHash);
await _freeSql.Insert(user).ExecuteAffrowsAsync();
return true;
}
catch
{
return false;
}
}
public async Task<bool> UpdateUserAsync(User user)
{
try
{
user.UpdatedAt = DateTime.Now;
await _freeSql.Update<User>()
.SetSource(user)
.ExecuteAffrowsAsync();
return true;
}
catch
{
return false;
}
}
public async Task<bool> VerifyPasswordAsync(string email, string password)
{
var user = await GetUserByEmailAsync(email);
if (user == null) return false;
return VerifyPassword(password, user.PasswordHash);
}
public async Task<List<Tool>> GetUserFavoritesAsync(int userId)
{
var favorites = await _freeSql.Select<UserFavorite>()
.Include(uf => uf.Tool.Category)
.Where(uf => uf.UserId == userId)
.OrderByDescending(uf => uf.CreatedAt)
.ToListAsync();
return favorites.Select(uf => uf.Tool).ToList();
}
public async Task<bool> AddFavoriteAsync(int userId, int toolId)
{
try
{
var existing = await _freeSql.Select<UserFavorite>()
.Where(uf => uf.UserId == userId && uf.ToolId == toolId)
.FirstAsync();
if (existing != null) return true;
await _freeSql.Insert(new UserFavorite
{
UserId = userId,
ToolId = toolId
}).ExecuteAffrowsAsync();
// 更新工具收藏数
await _freeSql.Update<Tool>()
.Where(t => t.Id == toolId)
.Set(t => t.FavoriteCount + 1)
.ExecuteAffrowsAsync();
return true;
}
catch
{
return false;
}
}
public async Task<bool> RemoveFavoriteAsync(int userId, int toolId)
{
try
{
await _freeSql.Delete<UserFavorite>()
.Where(uf => uf.UserId == userId && uf.ToolId == toolId)
.ExecuteAffrowsAsync();
// 更新工具收藏数
await _freeSql.Update<Tool>()
.Where(t => t.Id == toolId)
.Set(t => t.FavoriteCount - 1)
.ExecuteAffrowsAsync();
return true;
}
catch
{
return false;
}
}
public async Task<bool> IsFavoriteAsync(int userId, int toolId)
{
var favorite = await _freeSql.Select<UserFavorite>()
.Where(uf => uf.UserId == userId && uf.ToolId == toolId)
.FirstAsync();
return favorite != null;
}
private string HashPassword(string password)
{
using var sha256 = SHA256.Create();
var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password + "ToolHub_Salt"));
return Convert.ToBase64String(hashedBytes);
}
private bool VerifyPassword(string password, string hash)
{
var computedHash = HashPassword(password);
return computedHash == hash;
}
}