LoginController.cs 6.04 KB
using HHECS.Application.Enums;
using HHECS.Application.Service;
using HHECS.BllModel;
using HHECS.Model.ClassComparer;
using HHECS.Model.Entities;
using HHECS.WebCommon.Config;
using HHECS.WebCommon.Http;
using HHECS.WebCommon.Json;
using HHECS.WebCommon.Port;
using HHECS.WebCommon.SystemHelp.Log;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace HHECS.Web.Controllers
{

    /// <summary>
    /// 登录控制器
    /// </summary>
    [AllowAnonymous]
    public class LoginController : Controller
    {

        private readonly PermissionService _permissionService;

        private readonly LogService _logService;

        public LoginController(PermissionService permissionService, LogService logService)
        {
            _permissionService = permissionService;
            _logService = logService;
        }

        [HttpGet]
        public IActionResult Index()
        {
            //var company = sysCompanyService.GetSysCompanyOne();
            //var sysFile = sysCompanyService.GetSysFile(company.companyId);
            //ViewBag.filePath = sysAppService.Download();
            //ViewBag.ver = company.ver;
            //ViewBag.Url = sysFile.FirstOrDefault(x => x.position == "home")?.url;
            ViewBag.copyright = "Copyright © " + DateTime.Now.ToString("yyyy ") + AppSettings.GetAppSeting("copyright");

            return View();
        }

        /// <summary>
        /// 登入
        /// </summary>
        [HttpPost]
        public string Login(string username, string password, string webcam, string idcard)
        {
            return ExceptionsHelp.Instance.Execute(() =>
             {
                 var response = new Response();
                 var result = _permissionService.GetUserWithRoles(username, password);
                 if (!result.Success) return response.ResponseError(result.Msg).ToJson();

                 var user = result.Data;
                 var permissions = user.Roles.SelectMany(t => t.Permissions).Distinct(new PermissionComparer()).ToList();
                 var ips = ComputerHelp.GetAddressIP();
                 _logService.LogOperation(Title.Login, ModuleConst.Login, $"用户{user.UserCode}登录成功.来自IP:{ips}", result.Code.ToString(), user.UserCode);
                 //写cookies
                 //https://www.cnblogs.com/land/archive/2009/04/10/1433074.html
                 var token = Guid.NewGuid().ToString("N");
                 response.Token = token;
                 Response.Cookies.Append("Token", token);
                 user.Token = token;
                 var bllResult = _permissionService.UserUpdate(user);
                 if (!bllResult.Success)
                 {
                     response.Message = bllResult.Msg;
                     response.Status = false;
                     response.Code = 500;
                     return response.ToJson();
                 }
                 var currentSession = new
                 {
                     Account = user.UserCode,
                     Name = user.UserName,
                     Sex = "",
                     Idcard = "",
                     Token = token,
                     Organizations = string.Join(",", permissions.Select(u => u.PermissionName).ToList()),
                     CreateTime = DateTime.Now,
                 };

                 response.Result = currentSession;

                 var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);     // 指定身份认证类型
                 identity.AddClaim(new Claim(ClaimTypes.Sid, result.Data.UserCode));  // 用户Id
                 identity.AddClaim(new Claim("Password", result.Data.Password));       // 用户名称
                 identity.AddClaim(new Claim(ClaimTypes.Name, result.Data.UserName));

                 //创建身份证这个证件的携带者:我们叫这个证件携带者为“证件当事人”
                 var principal = new ClaimsPrincipal(identity);
                 HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = false, AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(40) });

                 return response.ToJson();
             });
        }

        [HttpPost]
        public async Task<BllResult> LoginIn(User user)
        {
            //写入Session
            //HttpContext.Session.SetString("q", userName);
            //登录Cookie
            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);     // 指定身份认证类型
            identity.AddClaim(new Claim(ClaimTypes.Sid, user.UserCode));  // 用户Id
            identity.AddClaim(new Claim("Password", user.Password));       // 用户名称
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));


            //创建身份证这个证件的携带者:我们叫这个证件携带者为“证件当事人”
            var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = false, AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(40) });

            return BllResultFactory.Success();
        }

        [HttpGet]
        public async Task<BllResult> LoginOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return BllResultFactory.Success();
        }

        /// <summary>
        /// 退出
        /// </summary>
        [HttpGet]
        public async Task<BllResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            Response.Cookies.Append("Token", "");
            //return RedirectToAction("Index", "Login");
            return BllResultFactory.Success();
        }
    }
}