using Infrastructure.Data; using Infrastructure.Extensions; using Infrastructure.Security; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using TeacherExt.Entities; using TeacherExt.Models; namespace TeacherExt.Controllers { public class AccountController : Controller { private readonly IEncryptionService _encryptionService; private readonly IRepository _userRepo; public AccountController(IEncryptionService encryptionService,IRepository userRepo) { this._encryptionService = encryptionService; this._userRepo = userRepo; } [HttpGet] public IActionResult Login() { return View(); } [HttpPost] public IActionResult Login(LoginModel model) { if (ModelState.IsValid) { var user = this._userRepo.ReadOnlyTable().FirstOrDefault(o => o.UserName == model.UserName); if (user!=null) { if (user.PasswordHash == this._encryptionService.CreatePasswordHash(user.PasswordSalt, model.Password)) { Request.HttpContext.JwtSignIn(model.UserName, model.RememberMe); if(!Request.IsAjax()) { return RedirectToAction("Index", "Home"); } else { return Json(new { AccessToken = Request.HttpContext.CreateJwtToken(new List { new Claim(ClaimTypes.Name, model.UserName) }, DateTime.Now.AddYears(100)), RefreshToken = Request.HttpContext.CreateJwtToken(new List { new Claim(ClaimTypes.Name, model.UserName) }, DateTime.Now.AddYears(100)), }); } } else { ModelState.AddModelError(nameof(model.Password), "密码错误"); } } else { ModelState.AddModelError(nameof(model.UserName), "用户不存在"); } } return Result(model); } public IActionResult Logout() { Request.HttpContext.JwtSignOut(); return RedirectToAction("Index", "Home"); } protected IActionResult Result(object model) { if (this.IsJsonRequest()) { return Json(new { schema = this.GetJsonSchema(), model, errors = ModelState.Where(o => o.Value.ValidationState == ModelValidationState.Invalid), data = ViewData }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); } return View(model); } } }