using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using System.Security.Claims; using ToolHub.Models; using ToolHub.Services; namespace ToolHub.Controllers; public class AdminController : Controller { private readonly IUserService _userService; private readonly IToolService _toolService; private readonly IFreeSql _freeSql; public AdminController(IUserService userService, IToolService toolService, IFreeSql freeSql) { _userService = userService; _toolService = toolService; _freeSql = freeSql; } [HttpGet] public IActionResult Login() { if (User.Identity?.IsAuthenticated == true) { return RedirectToAction("Index"); } return View(); } [HttpPost] public async Task Login(string email, string password, bool rememberMe = false) { if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { ViewBag.Error = "请输入邮箱和密码"; return View(); } var user = await _userService.GetUserByEmailAsync(email); if (user == null || user.Role != "Admin" || !await _userService.VerifyPasswordAsync(email, password)) { ViewBag.Error = "邮箱或密码错误,或您不是管理员"; return View(); } var claims = new List { new(ClaimTypes.NameIdentifier, user.Id.ToString()), new(ClaimTypes.Name, user.UserName), new(ClaimTypes.Email, user.Email), new(ClaimTypes.Role, user.Role) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { IsPersistent = rememberMe, ExpiresUtc = rememberMe ? DateTimeOffset.UtcNow.AddDays(7) : DateTimeOffset.UtcNow.AddHours(1) }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return RedirectToAction("Index"); } [HttpPost] [Authorize(Roles = "Admin")] public async Task Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return RedirectToAction("Login"); } [Authorize(Roles = "Admin")] public async Task Index() { // 统计数据 ViewBag.TotalTools = await _freeSql.Select().Where(t => t.IsActive).CountAsync(); ViewBag.TotalCategories = await _freeSql.Select().Where(c => c.IsActive).CountAsync(); ViewBag.TotalUsers = await _freeSql.Select().Where(u => u.IsActive).CountAsync(); ViewBag.TotalViews = await _freeSql.Select().SumAsync(t => t.ViewCount); // 最新工具 ViewBag.RecentTools = await _freeSql.Select() .Include(t => t.Category) .Where(t => t.IsActive) .OrderByDescending(t => t.CreatedAt) .Take(5) .ToListAsync(); return View(); } [Authorize(Roles = "Admin")] public async Task Users(int page = 1) { var users = await _freeSql.Select() .Where(u => u.IsActive) .OrderByDescending(u => u.CreatedAt) .Page(page, 20) .ToListAsync(); return View(users); } }