You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
3.3 KiB
92 lines
3.3 KiB
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<User> _userRepo;
|
|
|
|
public AccountController(IEncryptionService encryptionService,IRepository<User> 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<Claim> { new Claim(ClaimTypes.Name, model.UserName) }, DateTime.Now.AddYears(100)),
|
|
RefreshToken = Request.HttpContext.CreateJwtToken(new List<Claim> { new Claim(ClaimTypes.Name, model.UserName) }, DateTime.Now.AddYears(100)),
|
|
});
|
|
}
|
|
}
|
|
else
|
|
{
|
|
ModelState.AddModelError(nameof(model.Password), "密码错误");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
ModelState.AddModelError(nameof(model.UserName), "用户不存在");
|
|
}
|
|
}
|
|
return Result<LoginModel>(model);
|
|
}
|
|
|
|
public IActionResult Logout()
|
|
{
|
|
Request.HttpContext.JwtSignOut();
|
|
return RedirectToAction("Index", "Home");
|
|
}
|
|
protected IActionResult Result<TEditModel>(object model)
|
|
{
|
|
if (this.IsJsonRequest())
|
|
{
|
|
return Json(new
|
|
{
|
|
schema = this.GetJsonSchema<TEditModel>(),
|
|
model,
|
|
errors = ModelState.Where(o => o.Value.ValidationState == ModelValidationState.Invalid),
|
|
data = ViewData
|
|
}, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
|
|
}
|
|
return View(model);
|
|
}
|
|
}
|
|
}
|