AccountController.cs 6.04 KB
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using HHECS.DAQWebClient.ViewModel;
using HHECS.DAQWebClient.Models;
using HHECS.DAQWebClient.Dtos;

namespace HHECS.DAQWebClient.Controllers
{
    public class AccountController : Controller
    {
        private readonly ILogger<AccountController> _logger;
        private readonly IFreeSql _freeSql;

        public AccountController(IFreeSql freeSql, ILogger<AccountController> logger)
        {
            _freeSql = freeSql;
            _logger = logger;
        }

        public IActionResult Login()
        {
            var returnUrl = HttpContext.Request.Query.Where(x => x.Key == "ReturnUrl").Select(x => x.Value).FirstOrDefault();
            return View(new LoginModel
            {
                ReturnUrl = returnUrl,
            });
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> LoginAsync(LoginModel model)
        {
            try
            {
                var user = _freeSql.Queryable<User>().Where(x => x.Account == model.UserName).First();
                if (user == null)
                {
                    ModelState.AddModelError(nameof(model.UserName), $"用户“{model.UserName}”不存在!");
                    return View(model);
                }
                //实例化一个md5对像
                // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
                byte[] bytes = MD5.HashData(Encoding.UTF8.GetBytes(model.Password));
                var pwd = Convert.ToBase64String(bytes);

                if (pwd != user.Password)
                {
                    ModelState.AddModelError(nameof(model.Password), "密码错误");
                    return View(model);
                }

                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaims(new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, model.UserName),
                    new Claim(ClaimTypes.Role, user.Role.ToString()),
                    new Claim(ClaimTypes.System, "DataAcquisition")
                });

                var principal = new ClaimsPrincipal(identity);

                // 登录
                var properties = new AuthenticationProperties
                {
                    IsPersistent = model.RememberMe,
                    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30),
                    AllowRefresh = true
                };
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
                _logger.LogInformation($"用户{model.UserName}登录成功");
                if (Url.IsLocalUrl(model.ReturnUrl))
                {
                    return Redirect(model.ReturnUrl);
                }

                return Redirect("/");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(nameof(model.UserName), $"程序异常:{ex.Message}");
                return View(model);
            }
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            var userName = HttpContext.User.Identity?.Name;
            await HttpContext.SignOutAsync();
            _logger.LogInformation($"用户{userName}退出登录");
            return Redirect("/");
        }

        [Authorize]
        public async Task<IActionResult> UpdatePassword(SettingPasswordModel model)
        {
            try
            {
                if (model.NewPassword != model.ConfirmNewPassword)
                {
                    return Ok(new ResultDto
                    {
                        Code = 500,
                        Msg = "“新密码”与“确认密码”不一致"
                    });
                }
                var account = HttpContext.User.Identity?.Name ?? string.Empty;
                var user = await _freeSql.Queryable<User>().Where(x => x.Account == account).FirstAsync();
                if (user == null)
                {
                    return Ok(new ResultDto
                    {
                        Code = 500,
                        Msg = "获取用户信息失败"
                    });
                }

                byte[] bytes = MD5.HashData(Encoding.UTF8.GetBytes(model.CurrentPassword));
                var pwd = Convert.ToBase64String(bytes);
                if (user.Password != pwd)
                {
                    return Ok(new ResultDto
                    {
                        Code = 500,
                        Msg = "原密码不正确"
                    });
                }

                byte[] bytes2 = MD5.HashData(Encoding.UTF8.GetBytes(model.NewPassword));
                var newPwd = Convert.ToBase64String(bytes2);
                await _freeSql.Update<User>(user.Id).Set(x => new User
                {
                    Password = newPwd,
                    Updated = DateTime.Now,
                    UpdatedBy = user.Account
                }).ExecuteAffrowsAsync();
                var msg = "修改密码成功";
                _logger.LogInformation(msg);
                return Ok(new ResultDto
                {
                    Code = 0,
                    Msg = msg
                });
            }
            catch (Exception ex)
            {
                var msg = $"修改密码失败:{ex.Message}";
                return Ok(new ResultDto
                {
                    Code = 0,
                    Msg = msg
                });
            }
        }
    }
}