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 GetUserByIdAsync(int id) { return await _freeSql.Select() .Where(u => u.Id == id && u.IsActive) .FirstAsync(); } public async Task GetUserByEmailAsync(string email) { return await _freeSql.Select() .Where(u => u.Email == email && u.IsActive) .FirstAsync(); } public async Task CreateUserAsync(User user) { try { user.PasswordHash = HashPassword(user.PasswordHash); await _freeSql.Insert(user).ExecuteAffrowsAsync(); return true; } catch { return false; } } public async Task UpdateUserAsync(User user) { try { user.UpdatedAt = DateTime.Now; await _freeSql.Update() .SetSource(user) .ExecuteAffrowsAsync(); return true; } catch { return false; } } public async Task VerifyPasswordAsync(string email, string password) { var user = await GetUserByEmailAsync(email); if (user == null) return false; return VerifyPassword(password, user.PasswordHash); } public async Task> GetUserFavoritesAsync(int userId) { var favorites = await _freeSql.Select() .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 AddFavoriteAsync(int userId, int toolId) { try { var existing = await _freeSql.Select() .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() .Where(t => t.Id == toolId) .Set(t => t.FavoriteCount + 1) .ExecuteAffrowsAsync(); return true; } catch { return false; } } public async Task RemoveFavoriteAsync(int userId, int toolId) { try { await _freeSql.Delete() .Where(uf => uf.UserId == userId && uf.ToolId == toolId) .ExecuteAffrowsAsync(); // 更新工具收藏数 await _freeSql.Update() .Where(t => t.Id == toolId) .Set(t => t.FavoriteCount - 1) .ExecuteAffrowsAsync(); return true; } catch { return false; } } public async Task IsFavoriteAsync(int userId, int toolId) { var favorite = await _freeSql.Select() .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; } }