using Application.Domain.Entities; using Infrastructure.Data; using Infrastructure.Extensions; using Infrastructure.Web; using IoTNode.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace IoTNode.Controllers { [Authorize] public class AccountController : BaseController { private readonly TokenValidationParameters _parameters; private readonly IRepository _gatewayRepo; public AccountController(TokenValidationParameters parameters, IRepository userRepo) { this._parameters = parameters; this._gatewayRepo = userRepo; } [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(new LoginModel()); } [AllowAnonymous] [HttpPost] public IActionResult LoginAsync(LoginModel model, string returnUrl = null) { if (ModelState.IsValid) { try { var gateway = this._gatewayRepo.Table().FirstOrDefault(); if (model.UserName == "admin" && gateway.Password == model.Password) { var claims = new List { new Claim(this._parameters.NameClaimType, model.UserName), }; this.HttpContext.JwtSignIn(claims, model.RememberMe); if (string.IsNullOrEmpty(returnUrl)) { returnUrl = Url.Action("Index", "Home"); } return Redirect(returnUrl); } else { ModelState.AddModelError(nameof(model.Password), "用户名或密码错误"); } } catch (Exception ex) { ex.PrintStack(); ModelState.AddModelError("", ex.Message); } } ViewData["ReturnUrl"] = returnUrl; return View(model); } public IActionResult Logout() { this.HttpContext.JwtSignOut(); return RedirectToAction("Login"); } } }