LoginController.cs 6.87 KB
using HHECS.Application.Enums;
using HHECS.Application.Service;
using HHECS.BllModel;
using HHECS.Model.ClassComparer;
using HHECS.Model.Entities;
using HHECS.Model.ViewEntity;
using HHECS.WebCommon.Config;
using HHECS.WebCommon.Port;
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;
using HHECS.Infrastructure.Json;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Net;
using HHECS.Dal.Repository;

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.Year + "-" + new CompanyRepository().Where(t => true).ToOne()?.Name;
            return View();
        }

        /// <summary>
        /// 登入
        /// </summary>
        [HttpPost]
        public string Login(string username, string password)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            var response = new Response();
            try
            {
                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();
                //写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) return response.ResponseError(bllResult.Msg).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) });

                #region 记录登录日志

                string url = $"{HttpContext.Request.Host}{HttpContext.Request.Path}{HttpContext.Request.QueryString}";
                var actionArguments = JsonConvert.SerializeObject(username);
                _logService.AddWebOperationLog(url,
                                               "登录",
                                               HttpContext.Request.Method.ToUpper(),
                                               HttpContext.Request.Headers[HeaderNames.UserAgent].ToString(),
                                               actionArguments,
                                               response.ToJson(),
                                               stopwatch.Elapsed.TotalSeconds,
                                               user,
                                               ips,
                                               response.Status,
                                               "登录日志");

                #endregion

                return response.ToJson();
            }
            catch (Exception ex)
            {
                return response.ResponseError(ex.Message).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();
        }
    }
}