Toolhub / Controllers /AdminController.cs
unifare
Initial commit: ToolHub ASP.NET Core app
5fc700d
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<IActionResult> 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<Claim>
{
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<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Index()
{
// 统计数据
ViewBag.TotalTools = await _freeSql.Select<Tool>().Where(t => t.IsActive).CountAsync();
ViewBag.TotalCategories = await _freeSql.Select<Category>().Where(c => c.IsActive).CountAsync();
ViewBag.TotalUsers = await _freeSql.Select<User>().Where(u => u.IsActive).CountAsync();
ViewBag.TotalViews = await _freeSql.Select<Tool>().SumAsync(t => t.ViewCount);
// 最新工具
ViewBag.RecentTools = await _freeSql.Select<Tool>()
.Include(t => t.Category)
.Where(t => t.IsActive)
.OrderByDescending(t => t.CreatedAt)
.Take(5)
.ToListAsync();
return View();
}
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Users(int page = 1)
{
var users = await _freeSql.Select<User>()
.Where(u => u.IsActive)
.OrderByDescending(u => u.CreatedAt)
.Page(page, 20)
.ToListAsync();
return View(users);
}
}