用户在线管理,一个账号只准在一台设备上登陆,其他设备登陆后,此设备自动退出。

This commit is contained in:
Mac mini git server 2024-07-08 15:58:37 +08:00
parent 12e16e0c6c
commit 209e88a905
9 changed files with 182 additions and 15 deletions

View File

@ -4,6 +4,8 @@ using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using HHWMS.Web.Support;
using HHWMS.Web.ViewModels.HomeVMs;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
@ -153,6 +155,17 @@ namespace HHWMS.Web.Controllers
return JsonMore("No Data");
}
[Public]
public IActionResult CheckLogin()
{
return Ok();
}
[Public]
public IActionResult BeforeLogin(LoginVM vm)
{
return JsonMore(UserSessionManager.AllSignined().ToList());
}
//[AllowAnonymous]
//public github GetGithubInfo()
//{

View File

@ -14,6 +14,7 @@ using WalkingTec.Mvvm.Mvc.Admin.ViewModels.FrameworkUserVms;
using HHWMS.Web.ViewModels.HomeVMs;
using System.Collections.Generic;
using System.Linq;
using HHWMS.Web.Support;
namespace HHWMS.Web.Controllers
{
@ -48,13 +49,19 @@ namespace HHWMS.Web.Controllers
}
}*/
var user = Wtm.DoLogin(vm.ITCode, vm.Password, vm.Tenant);
if (user == null)
if (user == null)
{
vm.MSD.AddModelError("", Localizer["Sys.LoginFailed"]);
return View(vm);
}
else
{
var signined = UserSessionManager.IsUserSignined(user.Name);
if (signined)
{
// 踢人下线
await KickUser(user.Name);
}
//其他属性可以通过user.Attributes["aaa"] = "bbb"方式赋值
Wtm.LoginUserInfo = user;
string url = string.Empty;
@ -77,7 +84,9 @@ namespace HHWMS.Web.Controllers
};
}
var principal = user.CreatePrincipal();
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
UserSessionManager.AddUserSession(user.Name,principal.Claims.First(c => c.Type == "SessionId").Value);
return Redirect(HttpUtility.UrlDecode(url));
}
}
@ -133,6 +142,14 @@ namespace HHWMS.Web.Controllers
}
}
[AllRights]
public async Task<IActionResult> KickUser(string ITcode)
{
UserSessionManager.KickUser(ITcode);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
[AllRights]
[ActionDescription("ChangePassword")]
public ActionResult ChangePassword()

View File

@ -71,9 +71,9 @@
<PackageReference Include="System.ServiceModel.Http" Version="4.10.*" />
<PackageReference Include="System.ServiceModel.NetTcp" Version="4.10.*" />
<PackageReference Include="System.ServiceModel.Security" Version="4.10.*" />
<PackageReference Include="WalkingTec.Mvvm.Core" Version="6.3.9-alpha" />
<PackageReference Include="WalkingTec.Mvvm.Mvc" Version="6.3.9-alpha" />
<PackageReference Include="WalkingTec.Mvvm.TagHelpers.LayUI" Version="6.3.9-alpha" />
<PackageReference Include="WalkingTec.Mvvm.Core" Version="6.4.1-alpha" />
<PackageReference Include="WalkingTec.Mvvm.Mvc" Version="6.4.1-alpha" />
<PackageReference Include="WalkingTec.Mvvm.TagHelpers.LayUI" Version="6.4.1-alpha" />
<PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="6.102.1.1" />
</ItemGroup>

View File

@ -82,6 +82,7 @@ app.UseSession();
app.UseWtmSwagger(false);
app.UseSwaggerExt();
app.UseWtm();
app.UseMiddleware<SessionValidationMiddleware>();
app.AddQuartzJobs();
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>
// 检查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">
<h1>WMS</h1>
<br />
<form action="/Login/Login" method="post">
<form id="login" action="/Login/Login" method="post">
<input type="hidden" name="Redirect" value="@Model.Redirect">
<ul class="loginForm">
<li>
@ -75,7 +75,36 @@
margin-bottom: 1%;
">© 2022 华恒工程技术中心有限公司</p>*@
</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>

View File

@ -22,17 +22,17 @@
},
"Connections": [
//{
// "Key": "default",
// "Value": "Server=127.0.0.1;Port=3306;Database=WMS;Uid=root;Password=abc123*;Character Set=utf8mb4;",
// "DBType": "mysql"
//},
{
"Key": "default",
"Value": "Data Source=.;Initial Catalog=WMS;User=sa;Password=abc123*;Persist Security Info=True",
"DbContext": "DataContext",
"DBType": "sqlserver" //DataBase, you can choose mysql,sqlserver,pgsql,sqlite,oracle
}
"Value": "Server=127.0.0.1;Port=3306;Database=WMS;Uid=root;Password=abc123*;Character Set=utf8mb4;",
"DBType": "mysql"
},
// {
// "Key": "default",
// "Value": "Data Source=.;Initial Catalog=WMS;User=sa;Password=abc123*;Persist Security Info=True",
// "DbContext": "DataContext",
// "DBType": "sqlserver" //DataBase, you can choose mysql,sqlserver,pgsql,sqlite,oracle
// }
//{
// "Key": "default",
// "Value": "Data Source=10.18.106.4;Initial Catalog=8357wms;User=wms;Password=abc123*;Persist Security Info=True",