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.
iot/projects/IoTNode/Controllers/AccountController.cs

78 lines
2.5 KiB

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<IoTGateway> _gatewayRepo;
public AccountController(TokenValidationParameters parameters, IRepository<IoTGateway> 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<Claim> {
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");
}
}
}