using AgriculturalPlatform.Api.Data; using AgriculturalPlatform.Api.Dtos; using AgriculturalPlatform.Api.Models; using AgriculturalPlatform.Api.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace AgriculturalPlatform.Api.Controllers; [ApiController] [Route("api/[controller]")] public class AuthController(AppDbContext db, JwtService jwt, CurrentUserService currentUser) : ControllerBase { /// 登录 [HttpPost("login")] [AllowAnonymous] public async Task> Login(LoginRequest req) { var user = await db.Users.Include(u => u.Org) .FirstOrDefaultAsync(u => u.Username == req.Username); if (user is null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash)) return Unauthorized(new { message = "用户名或密码错误" }); if (!user.IsActive) return Unauthorized(new { message = "账号已被停用,请联系管理员" }); user.LastLoginAt = DateTime.Now; await db.SaveChangesAsync(); var token = jwt.Generate(user); return Ok(new LoginResult(token, BuildInfo(user))); } /// 当前登录用户信息 [HttpGet("me")] [Authorize] public async Task> Me() { var cu = currentUser.Get()!; var user = await db.Users.Include(u => u.Org).Include(u => u.SysRole).FirstAsync(u => u.Id == cu.Id); return Ok(BuildInfo(user)); } /// 修改密码 [HttpPut("password")] [Authorize] public async Task ChangePassword(ChangePasswordRequest req) { var cu = currentUser.Get()!; var user = await db.Users.FindAsync(cu.Id); if (user is null) return NotFound(); if (!BCrypt.Net.BCrypt.Verify(req.OldPassword, user.PasswordHash)) return BadRequest(new { message = "原密码不正确" }); user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(req.NewPassword); await db.SaveChangesAsync(); return Ok(new { message = "密码修改成功" }); } private static UserInfoDto BuildInfo(User user) => new( user.Id, user.Username, user.RealName, user.Phone, user.Role.ToString(), user.RoleId, user.SysRole?.Name, user.OrgId, user.Org?.Name, user.Org?.Type.ToString(), user.IsActive); }