123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251 |
- using AutoMapper;
- using CacheManager.Core;
- using Hangfire;
- using Masuit.MyBlogs.Core.Configs;
- using Masuit.MyBlogs.Core.Extensions.Firewall;
- using Masuit.MyBlogs.Core.Extensions.Hangfire;
- using Masuit.Tools.Mime;
- using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
- using Masuit.Tools.Logging;
- using Microsoft.AspNetCore.Mvc;
- using System.Net;
- using System.Web;
- namespace Masuit.MyBlogs.Core.Controllers;
- /// <summary>
- /// 登录授权
- /// </summary>
- [ApiExplorerSettings(IgnoreApi = true), ServiceFilter(typeof(FirewallAttribute))]
- public sealed class PassportController : Controller
- {
- /// <summary>
- /// 用户
- /// </summary>
- public IUserInfoService UserInfoService { get; set; }
- public IFirewallRepoter FirewallRepoter { get; set; }
- public IMapper Mapper { get; set; }
- /// <summary>
- /// 客户端的真实IP
- /// </summary>
- public string ClientIP => HttpContext.Connection.RemoteIpAddress.ToString();
- /// <summary>
- ///
- /// </summary>
- /// <param name="data"></param>
- /// <param name="isTrue"></param>
- /// <param name="message"></param>
- /// <returns></returns>
- private ActionResult ResultData(object data, bool isTrue = true, string message = "")
- {
- return Json(new
- {
- Success = isTrue,
- Message = message,
- Data = data
- });
- }
- /// <summary>
- /// 登录页
- /// </summary>
- /// <returns></returns>
- public ActionResult Login()
- {
- var keys = RsaCrypt.GenerateRsaKeys(RsaKeyType.PKCS1);
- Response.Cookies.Append(nameof(keys.PublicKey), keys.PublicKey, new CookieOptions()
- {
- SameSite = SameSiteMode.Lax
- });
- HttpContext.Session.Set(nameof(keys.PrivateKey), keys.PrivateKey);
- string from = Request.Query["from"];
- if (!string.IsNullOrEmpty(from))
- {
- from = HttpUtility.UrlDecode(from);
- Response.Cookies.Append("refer", from, new CookieOptions()
- {
- SameSite = SameSiteMode.Lax
- });
- }
- if (HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) != null)
- {
- if (string.IsNullOrEmpty(from))
- {
- return RedirectToAction("Index", "Home");
- }
- return LocalRedirect(from);
- }
- if (Request.Cookies.Count > 2)
- {
- string name = Request.Cookies["username"];
- string pwd = Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK);
- var userInfo = UserInfoService.Login(name, pwd);
- if (userInfo != null)
- {
- Response.Cookies.Append("username", name, new CookieOptions()
- {
- Expires = DateTime.Now.AddYears(1),
- SameSite = SameSiteMode.Lax
- });
- Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions()
- {
- Expires = DateTime.Now.AddYears(1),
- SameSite = SameSiteMode.Lax
- });
- HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
- BackgroundJob.Enqueue<IHangfireBackJob>(job => job.LoginRecord(userInfo, ClientIP, LoginType.Default));
- if (string.IsNullOrEmpty(from))
- {
- return RedirectToAction("Index", "Home");
- }
- return LocalRedirect(from);
- }
- }
- return View();
- }
- /// <summary>
- /// 登陆检查
- /// </summary>
- /// <param name="username"></param>
- /// <param name="password"></param>
- /// <param name="valid"></param>
- /// <param name="remem"></param>
- /// <returns></returns>
- [HttpPost, ValidateAntiForgeryToken]
- public ActionResult Login([FromServices] ICacheManager<int> cacheManager, string username, string password, string valid, string remem)
- {
- string validSession = HttpContext.Session.Get<string>("valid") ?? string.Empty; //将验证码从Session中取出来,用于登录验证比较
- if (string.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase))
- {
- return ResultData(null, false, "验证码错误");
- }
- HttpContext.Session.Remove("valid"); //验证成功就销毁验证码Session,非常重要
- if (string.IsNullOrEmpty(username.Trim()) || string.IsNullOrEmpty(password.Trim()))
- {
- return ResultData(null, false, "用户名或密码不能为空");
- }
- try
- {
- var privateKey = HttpContext.Session.Get<string>(nameof(RsaKey.PrivateKey));
- password = password.RSADecrypt(privateKey);
- }
- catch (Exception)
- {
- LogManager.Info("登录失败,私钥:" + HttpContext.Session.Get<string>(nameof(RsaKey.PrivateKey)));
- throw;
- }
- var userInfo = UserInfoService.Login(username, password);
- if (userInfo == null)
- {
- var times = cacheManager.AddOrUpdate("LoginError:" + ClientIP, 1, i => i + 1, 5);
- if (times > 30)
- {
- FirewallRepoter.ReportAsync(IPAddress.Parse(ClientIP)).ContinueWith(_ => LogManager.Info($"多次登录用户名或密码错误,疑似爆破行为,已上报IP{ClientIP}至:" + FirewallRepoter.ReporterName));
- }
- return ResultData(null, false, "用户名或密码错误");
- }
- HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
- if (remem.Trim().Contains(new[] { "on", "true" })) //是否记住登录
- {
- Response.Cookies.Append("username", HttpUtility.UrlEncode(username.Trim()), new CookieOptions()
- {
- Expires = DateTime.Now.AddYears(1),
- SameSite = SameSiteMode.Lax
- });
- Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions()
- {
- Expires = DateTime.Now.AddYears(1),
- SameSite = SameSiteMode.Lax
- });
- }
- BackgroundJob.Enqueue<IHangfireBackJob>(job => job.LoginRecord(userInfo, ClientIP, LoginType.Default));
- string refer = Request.Cookies["refer"];
- Response.Cookies.Delete(nameof(RsaKey.PublicKey), new CookieOptions()
- {
- SameSite = SameSiteMode.Lax
- });
- Response.Cookies.Delete("refer", new CookieOptions()
- {
- SameSite = SameSiteMode.Lax
- });
- HttpContext.Session.Remove(nameof(RsaKey.PrivateKey));
- return ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer);
- }
- /// <summary>
- /// 生成验证码
- /// </summary>
- /// <returns></returns>
- public ActionResult ValidateCode()
- {
- string code = Tools.Strings.ValidateCode.CreateValidateCode(6);
- HttpContext.Session.Set("valid", code); //将验证码生成到Session中
- using var buffer = code.CreateValidateGraphic();
- return this.ResumeFile(buffer, ContentType.Jpeg, "验证码.jpg");
- }
- /// <summary>
- /// 检查验证码
- /// </summary>
- /// <param name="code"></param>
- /// <returns></returns>
- [HttpPost]
- public ActionResult CheckValidateCode(string code)
- {
- string validSession = HttpContext.Session.Get<string>("valid");
- if (string.IsNullOrEmpty(validSession) || !code.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase))
- {
- return ResultData(null, false, "验证码错误");
- }
- return ResultData(null, false, "验证码正确");
- }
- /// <summary>
- /// 获取用户信息
- /// </summary>
- /// <returns></returns>
- public ActionResult GetUserInfo()
- {
- var user = HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo);
- #if DEBUG
- user = Mapper.Map<UserInfoDto>(UserInfoService.GetByUsername("masuit"));
- #endif
- return ResultData(user);
- }
- /// <summary>
- /// 注销登录
- /// </summary>
- /// <returns></returns>
- public ActionResult Logout()
- {
- HttpContext.Session.Remove(SessionKey.UserInfo);
- Response.Cookies.Delete("username", new CookieOptions()
- {
- SameSite = SameSiteMode.Lax
- });
- Response.Cookies.Delete("password", new CookieOptions()
- {
- SameSite = SameSiteMode.Lax
- });
- HttpContext.Session.Clear();
- return Request.Method.Equals(HttpMethods.Get) ? RedirectToAction("Index", "Home") : ResultData(null, message: "注销成功!");
- }
- }
|