Compare commits

..

5 Commits

Author SHA1 Message Date
d8aee3c32c Merge remote-tracking branch 'origin/nugetmanager' into nugetmanager 2024-07-08 14:09:52 +08:00
3ca55b2c03 拼写检查 2024-07-08 14:09:36 +08:00
4c99666b75 Revert "添加在线用户管理,同一账号只允许一台设备登陆。"
This reverts commit a777e04e83e233e332d164c59b60649264d7c467.
2024-07-08 14:08:02 +08:00
a777e04e83 添加在线用户管理,同一账号只允许一台设备登陆。
后期可限制登陆用户人数等功能
2024-07-08 14:06:57 +08:00
6f38757a3f 添加在线用户管理,同一账号只允许一台设备登陆。
后期可限制登陆用户人数等功能
2024-06-27 00:51:33 +08:00
11 changed files with 192 additions and 10 deletions

View File

@ -3,11 +3,15 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks;
using System.Web; using System.Web;
using HHWMS.Web.Support;
using HHWMS.Web.ViewModels.HomeVMs;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -153,6 +157,18 @@ namespace HHWMS.Web.Controllers
return JsonMore("No Data"); return JsonMore("No Data");
} }
[Public]
public IActionResult CheckLogin()
{
return Ok();
}
[Public]
public IActionResult BeforeLogin(LoginVM vm)
{
return JsonMore(UserSessionManager.AllSignined().ToList());
}
//[AllowAnonymous] //[AllowAnonymous]
//public github GetGithubInfo() //public github GetGithubInfo()
//{ //{

View File

@ -14,6 +14,11 @@ using WalkingTec.Mvvm.Mvc.Admin.ViewModels.FrameworkUserVms;
using HHWMS.Web.ViewModels.HomeVMs; using HHWMS.Web.ViewModels.HomeVMs;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using HHWMS.Web.Support;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Distributed;
using WalkingTec.Mvvm.Core.Support.Quartz;
namespace HHWMS.Web.Controllers namespace HHWMS.Web.Controllers
{ {
@ -47,7 +52,9 @@ namespace HHWMS.Web.Controllers
return View(vm); return View(vm);
} }
}*/ }*/
var user = Wtm.DoLogin(vm.ITCode, vm.Password, vm.Tenant); var user = Wtm.DoLogin(vm.ITCode, vm.Password, vm.Tenant);
if (user == null) if (user == null)
{ {
vm.MSD.AddModelError("", Localizer["Sys.LoginFailed"]); vm.MSD.AddModelError("", Localizer["Sys.LoginFailed"]);
@ -55,6 +62,13 @@ namespace HHWMS.Web.Controllers
} }
else else
{ {
var bb = UserSessionManager.IsUserSignined(user.Name);
if (bb)
{
// 踢人下线
await KickUser(user.Name);
}
//其他属性可以通过user.Attributes["aaa"] = "bbb"方式赋值 //其他属性可以通过user.Attributes["aaa"] = "bbb"方式赋值
Wtm.LoginUserInfo = user; Wtm.LoginUserInfo = user;
string url = string.Empty; string url = string.Empty;
@ -77,7 +91,9 @@ namespace HHWMS.Web.Controllers
}; };
} }
var principal = user.CreatePrincipal(); var principal = user.CreatePrincipal();
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
UserSessionManager.AddUserSession(user.Name,principal.Claims.First(c => c.Type == "SessionId").Value);
return Redirect(HttpUtility.UrlDecode(url)); return Redirect(HttpUtility.UrlDecode(url));
} }
} }
@ -120,6 +136,7 @@ namespace HHWMS.Web.Controllers
[ActionDescription("Logout")] [ActionDescription("Logout")]
public async Task Logout() public async Task Logout()
{ {
UserSessionManager.RemoveUserSession(Wtm.LoginUserInfo.Name);
HttpContext.Session.Clear(); HttpContext.Session.Clear();
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (ConfigInfo.HasMainHost == false || Wtm.LoginUserInfo?.CurrentTenant != null) if (ConfigInfo.HasMainHost == false || Wtm.LoginUserInfo?.CurrentTenant != null)
@ -133,6 +150,14 @@ namespace HHWMS.Web.Controllers
} }
} }
[AllRights]
public async Task<IActionResult> KickUser(string ITcode)
{
UserSessionManager.KickUser(ITcode);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
[AllRights] [AllRights]
[ActionDescription("ChangePassword")] [ActionDescription("ChangePassword")]
public ActionResult ChangePassword() public ActionResult ChangePassword()

View File

@ -76,6 +76,7 @@ app.UseSession();
app.UseWtmSwagger(false); app.UseWtmSwagger(false);
app.UseSwaggerExt(); app.UseSwaggerExt();
app.UseWtm(); app.UseWtm();
app.UseMiddleware<SessionValidationMiddleware>();
app.AddQuartzJobs(); app.AddQuartzJobs();
app.UseEndpoints(endpoints => { app.UseEndpoints(endpoints => {

View File

@ -0,0 +1,38 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Support.Quartz;
namespace HHWMS.Web.Support;
public class SessionValidationMiddleware
{
private readonly RequestDelegate _next;
public SessionValidationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.User.Identity.IsAuthenticated)
{
var userId = context.User.Identity.Name;
var sessionId = context.User.Claims.FirstOrDefault(c => c.Type == "SessionId")?.Value;
if (!UserSessionManager.IsUserSessionValid(userId, sessionId))
{
// UserSessionManager.RemoveUserSession(userId);
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
context.Response.Redirect(new Configs().CookieOptions.LogoutPath);
return;
}
}
await _next(context);
}
}

View File

@ -0,0 +1,42 @@
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WalkingTec.Mvvm.Core;
namespace HHWMS.Web.Support;
using System.Collections.Concurrent;
public class UserSessionManager
{
private static ConcurrentDictionary<string, string> userSessions = new ConcurrentDictionary<string, string>();
public static void AddUserSession(string userId, string sessionId)
{
userSessions[userId.ToLower()] = sessionId;
}
public static void RemoveUserSession(string userId)
{
userSessions.TryRemove(userId, out _);
}
public static bool IsUserSessionValid(string userId, string sessionId)
{
return userSessions.TryGetValue(userId.ToLower(), out var storedSessionId) && storedSessionId == sessionId;
}
public static bool IsUserSignined(string userId)
{
return userSessions.ContainsKey(userId);
}
public static void KickUser(string userId)
{
userSessions.TryRemove(userId, out _);
}
public static ConcurrentDictionary<string, string> AllSignined()
{
return userSessions;
}
}

View File

@ -1 +1,28 @@
<script>layui.use('index')</script> <script>layui.use('index')</script>
<script>
// 检查Token是否过期的函数
function isTokenExpired() {
$.ajax({
url: 'Home/CheckLogin/',
statusCode: {
// 处理200 OK状态码
200: function(data) {
if (data.indexOf('Login') !== -1) {
clearInterval(timerId);
alert("您的账号已在其他地方登陆,若继续使用,请重新登录!");
location.reload();
}
},
},
});
}
// 存储定时器ID
var timerId = setInterval(function() {
// 你的代码逻辑
isTokenExpired();
}, 10000); // 每10000毫秒执行一次
</script>

View File

@ -36,7 +36,7 @@
<div class="login-form"> <div class="login-form">
<h1>WMS</h1> <h1>WMS</h1>
<br /> <br />
<form action="/Login/Login" method="post"> <form id="login" action="/Login/Login" method="post">
<input type="hidden" name="Redirect" value="@Model.Redirect"> <input type="hidden" name="Redirect" value="@Model.Redirect">
<ul class="loginForm"> <ul class="loginForm">
<li> <li>
@ -75,7 +75,36 @@
margin-bottom: 1%; margin-bottom: 1%;
">© 2022 华恒工程技术中心有限公司</p>*@ ">© 2022 华恒工程技术中心有限公司</p>*@
</div> </div>
<script>
var loginData = [];
$.post('/Home/BeforeLogin/',{},function (data){
loginData = data.Data;
});
// 给表单添加 onsubmit 事件处理器
document.getElementById('login').onsubmit = function() {
var usernameValue = $('input[name="ITCode"]').val();
var issigned;
// 从loginData查找 itcode
loginData.forEach(function(item) {
if (item.Key === usernameValue) {
var isConfirmed = confirm("您的账号已在其他地方登陆,确定在此设备重新登录吗?\n(此设备登陆后,其他设备的账号将自动退出!)");
// 如果用户点击“取消”,返回 false 以阻断表单提交
if (!isConfirmed) {
issigned = false;
}
else{
issigned = true;
}
}
})
return issigned;
}
</script>
</body> </body>

View File

@ -41,9 +41,9 @@
//} //}
], ],
"CookiePre": "HHWMS", //cookie前缀 "CookiePre": "HHWMS", //cookie前缀
"IsQuickDebug": true, //是否启用debug模式 "IsQuickDebug": false, //是否启用debug模式
"EnableTenant": false, //是否启动多租户 "EnableTenant": false, //是否启动多租户
"SyncDb": true, //是否自动同步数据库 "SyncDb": false, //是否自动同步数据库
"EncryptKey": "", //加密密钥 "EncryptKey": "", //加密密钥
"PageMode": "Tab", //页面显示模式,Single或者Tab "PageMode": "Tab", //页面显示模式,Single或者Tab
"TabMode": "Simple", //Tab页显示方式,Default或者Simple "TabMode": "Simple", //Tab页显示方式,Default或者Simple

View File

@ -15,7 +15,11 @@ namespace WalkingTec.Mvvm.Core.Extensions
public static ClaimsPrincipal CreatePrincipal(this LoginUserInfo self) public static ClaimsPrincipal CreatePrincipal(this LoginUserInfo self)
{ {
if (string.IsNullOrEmpty(self.ITCode)) throw new ArgumentException("Id is mandatory", nameof(self.ITCode)); if (string.IsNullOrEmpty(self.ITCode)) throw new ArgumentException("Id is mandatory", nameof(self.ITCode));
var claims = new List<Claim> { new Claim(AuthConstants.JwtClaimTypes.Subject, self.ITCode) }; var claims = new List<Claim>
{
new Claim(AuthConstants.JwtClaimTypes.Subject, self.ITCode) ,
new Claim("SessionId", Guid.NewGuid().ToString())
};
if (!string.IsNullOrEmpty(self.Name)) if (!string.IsNullOrEmpty(self.Name))
{ {

View File

@ -12,11 +12,11 @@ namespace $namespace$
[ActionDescription("$des$")] [ActionDescription("$des$")]
public partial class $modelname$Controller : BaseController public partial class $modelname$Controller : BaseController
{ {
private readonly IUnitWork _unitwork; private readonly IUnitWork _unitWork;
public $modelname$Controller(IUnitWork unitwork) public $modelname$Controller(IUnitWork unitWork)
{ {
_unitwork = unitwork; _unitWork = unitWork;
} }
#region Search #region Search

View File

@ -1,6 +1,6 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<VersionPrefix>6.3.7</VersionPrefix> <VersionPrefix>6.4.0</VersionPrefix>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">