/// <summary> /// 记录日志 /// </summary> /// <param name="folderName">文件夹名字</param> /// <param name="message">日志内容</param> /// <param name="path">日志存放磁盘路径</param> public static void WriteLog(string folderName, string message, string path = "") { try { PrincipalUser principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; var strPath = string.IsNullOrEmpty(path) ? LogPath : path; strPath = strPath + folderName + "\\" + DateTime.Now.ToString("yyyy-MM-dd"); lock (Lock) { var strFilename = strPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd HH") + ".txt"; if (!Directory.Exists(strPath)) { Directory.CreateDirectory(strPath); } } } catch { throw new Exception("日志记录失败"); } }
/// <summary> /// Action开始执行触发 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { _operationLogHandler = new OperationLogHandler(filterContext.HttpContext.Request); CurrentUser = AuthenticationExtension.Current(); if (CurrentUser != null) { _operationLogHandler.log.CreateUserCode = CurrentUser.Code; _operationLogHandler.log.CreateUserName = CurrentUser.Name; } //获取Action特性 var descriptionAttribute = filterContext.ActionDescriptor.EndpointMetadata.Where(a => a is DescriptionAttribute).ToList();; if (descriptionAttribute.Any()) { var info = descriptionAttribute[0] as DescriptionAttribute; if (info != null) { var description = info.Description; _operationLogHandler.log.ControllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)filterContext.ActionDescriptor).ControllerName; _operationLogHandler.log.ActionName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)filterContext.ActionDescriptor).ActionName; _operationLogHandler.log.Describe = description; } } base.OnActionExecuting(filterContext); }
public async Task <JsonResult> Submit(UserLoginInput model) { model.Password = _3DESEncrypt.Encrypt(model.Password); var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(model); if (info.Data != null) { var prin = new PrincipalUser() { UserId = Guid.Parse(info.Data.UserId), Code = info.Data.Code, Name = info.Data.Name, IsAdmin = info.Data.IsAdmin, RoleName = info.Data.RoleName, ImgUrl = info.Data.ImgUrl }; if (prin.Code == "admin") { prin.RoleName = "超级管理员"; } //写入Cookie信息 AuthenticationExtension.SetAuthCookie(prin); //写入日志 var logHandler = new LoginLogHandler(info.Data.UserId, info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录); logHandler.WriteLog(); } return(Json(info)); }
/// <summary> /// /// </summary> /// <param name="organizationLogic"></param> /// <param name="httpContextAccessor"></param> /// <param name="permissionLogic"></param> public OrganizationController(ISystemOrganizationLogic organizationLogic, IHttpContextAccessor httpContextAccessor, ISystemPermissionLogic permissionLogic) { _currentUser = httpContextAccessor.CurrentUser(); _organizationLogic = organizationLogic; _permissionLogic = permissionLogic; }
/// <summary> /// /// </summary> /// <param name="groupLogic"></param> /// <param name="userInfoLogic"></param> /// <param name="organizationLogic"></param> /// <param name="httpContextAccessor"></param> public GroupController(ISystemGroupLogic groupLogic, ISystemUserInfoLogic userInfoLogic, ISystemOrganizationLogic organizationLogic, IHttpContextAccessor httpContextAccessor) { _currentUser = httpContextAccessor.CurrentUser(); _groupLogic = groupLogic; _userInfoLogic = userInfoLogic; _organizationLogic = organizationLogic; }
/// <summary> /// /// </summary> /// <param name="permissionLogic"></param> /// <param name="httpContextAccessor"></param> /// <param name="userInfoLogic"></param> public HomeController(ISystemPermissionLogic permissionLogic, IHttpContextAccessor httpContextAccessor, ISystemUserInfoLogic userInfoLogic) { _currentUser = httpContextAccessor.CurrentUser(); _permissionLogic = permissionLogic; _userInfoLogic = userInfoLogic; }
public async Task CacheDataTest() { var n = 10000; var services = new ServiceCollection(); services.AddSingleton <IMemoryCache, MemoryCache>(x => new MemoryCache(new MemoryCacheOptions())); var serviceProvider = services.BuildServiceProvider(); for (var i = 1; i <= n; i++) { await Task.Run(() => { var principal = PrincipalUser.Personate(i, null, serviceProvider); principal.Cache().GetOrAdd("Test", _ => new Result { Ok = false, Message = Crypto.SHA256(i.ToString()) }); if (i % 11 == 0) { principal.AbandonCache(); } else if (i % 5 == 0) { PrincipalUser.Personate(1, null, serviceProvider).Cache().TryGetValue("Test", out var val); var data = (Result)val; data.Ok = true; data.Message = "Changed" + i; } }); } for (var i = 1; i <= n; i++) { var principal = PrincipalUser.Personate(i, null, serviceProvider); var found = principal.Cache().TryGetValue("Test", out var val); if (i % 11 == 0) { Assert.IsFalse(found); } else { Assert.IsTrue(found); var data = (Result)val; if (i != 1) { Assert.AreEqual(false, data.Ok); Assert.AreEqual(Crypto.SHA256(i.ToString()), data.Message); } else { Assert.AreEqual(true, data.Ok); Assert.AreEqual("Changed" + n, data.Message); } } } }
public ExceptionFilter(ILoggerFactory loggerFactory, IHostingEnvironment env, IHttpContextAccessor accessor) { _loggerFactory = loggerFactory; _env = env; _accessor = accessor; _currentUser = accessor.CurrentUser(); }
/// <summary> /// /// </summary> /// <param name="roleLogic"></param> /// <param name="permissionUserLogic"></param> /// <param name="organizationLogic"></param> /// <param name="httpContextAccessor"></param> public RoleController(ISystemRoleLogic roleLogic, ISystemPermissionUserLogic permissionUserLogic, ISystemOrganizationLogic organizationLogic, IHttpContextAccessor httpContextAccessor) { _currentUser = httpContextAccessor.CurrentUser(); _roleLogic = roleLogic; _permissionUserLogic = permissionUserLogic; _organizationLogic = organizationLogic; }
/// <summary> /// 重写验证 /// </summary> /// <param name="httpContext"></param> /// <returns>是否验证成功</returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { PrincipalUser principalUser = FormAuthenticationExtension.Current(HttpContext.Current.Request); if (principalUser != null) { HttpContext.Current.User = principalUser; return(true); } return(false); }
public async Task SendCodeThroughEmailTest() { Crypto.SecretToken = Crypto.RandomString(); var smtp = new MailSmtpProvider { Id = Guid.NewGuid(), Host = "smtp.live.com", Port = 25, Ssl = false, SenderDisplayName = "Weixing Chen", SenderMailAddress = "*****@*****.**", CredentialName = "*****@*****.**", Password = "", IsInUse = true }; //Config CredentialName & Password before running this test if (string.IsNullOrEmpty(smtp.CredentialName) || string.IsNullOrEmpty(smtp.Password)) { return; } using var mailDb = new DbContextOptionsBuilder <MailDbContext>().UseInMemoryDatabase("UnitTest").CreateDbContext(); using var twoFactorDb = new DbContextOptionsBuilder <TwoFactorDbContext>().UseInMemoryDatabase("UnitTest").CreateDbContext(); mailDb.Add(smtp); mailDb.SaveChanges(); var sendTo = "*****@*****.**"; var principal = PrincipalUser.Personate(1, "TestUser", null); var mailSender = new MailSender(mailDb); var twoFactorManager = new TwoFactorManager(twoFactorDb, principal, null, mailSender); var sentResult = await twoFactorManager.SendCodeThroughEmailAsync(sendTo); var row = twoFactorDb.TwoFactorCodes.FirstOrDefault(); Assert.IsTrue(sentResult.Ok); Assert.IsNotNull(row); Assert.AreEqual(sendTo, row.SentTo); Assert.IsFalse(row.IsUsed); var verifyResult = await twoFactorManager.VerifyCodeAsync(sendTo, row.Code, true); row = twoFactorDb.TwoFactorCodes.FirstOrDefault(); Assert.IsTrue(verifyResult.Ok); Assert.AreEqual(sendTo, row.SentTo); Assert.IsTrue(row.IsUsed); mailDb.Database.EnsureDeleted(); twoFactorDb.Database.EnsureDeleted(); }
/// <summary> /// 构造函数 /// </summary> /// <param name="exception"></param> public ExceptionLogHandler(Exception exception) : base("ExceptionLogToDatabase") { PrincipalUser principalUser = new PrincipalUser(); var current = HttpContexts.Current; if (current != null) { principalUser = AuthenticationExtension.Current(); } if (principalUser == null) { principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; } log = new ExceptionLog() { ExceptionLogId = CombUtil.NewComb().ToString(), CreateUserCode = principalUser.Code, CreateUserId = principalUser.UserId.ToString(), CreateUserName = principalUser.Name, ServerHost = String.Format("{0}【{1}】", IpBrowserUtil.GetServerHost(), IpBrowserUtil.GetServerHostIp()), ClientHost = String.Format("{0}", IpBrowserUtil.GetClientIp()), Runtime = "Web", CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Message = exception.Message, StackTrace = exception.StackTrace, ExceptionType = exception.GetType().FullName, ClientAddress = IpBrowserUtil.GetAddressByApi() }; //获取服务器信息 var request = HttpContexts.Current.Request; log.RequestUrl = string.Format("{0} ", request.Path); log.HttpMethod = request.Method; log.UserAgent = request.Headers["user-agent"]; log.InnerException = exception.InnerException != null?GetExceptionFullMessage(exception.InnerException) : ""; if (request?.HasFormContentType ?? request.HasFormContentType) { log.RequestData = request?.Form?.ToJson(); } else { if (request.Body.CanSeek) { log.RequestData = HttpUtility.UrlDecode(new StreamReader(request?.Body).ReadToEnd()); } } }
public async Task <IActionResult> Login(UserLoginInput model) { model.Password = _3DESEncrypt.Encrypt(model.Password); var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(model); if (info.Data != null) { var prin = new PrincipalUser() { UserId = info.Data.Id, Code = info.Data.Code, Name = info.Data.Name, IsAdmin = info.Data.IsAdmin, //TODO先注释 //RoleName = info.Data.RoleName, ImgUrl = info.Data.ImgUrl }; if (prin.Code == "admin") { prin.RoleName = "超级管理员"; } //写入Cookie信息 AuthenticationExtension.SetAuthCookie(prin); //写入日志 var logHandler = new LoginLogHandler(info.Data.Id.ToString(), info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录); logHandler.WriteLog(); } if (info.ResultSign == ResultSign.Successful) { if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } else { ModelState.AddModelError(string.Empty, info.Message); } return(View()); }
public async Task VerifyCodeTest() { using var testDb = new DbContextOptionsBuilder <TwoFactorDbContext>().UseInMemoryDatabase("UnitTest").CreateDbContext(); var principal = PrincipalUser.Personate(1, "TestUser", null); var row = new TwoFactorCode { Code = "123456", UserId = principal.Id, SentTo = "17751283521" }; testDb.Add(row); testDb.SaveChanges(); Result verifyResult = null; var twoFactorManager = new TwoFactorManager(testDb, principal, new AliyunSmsSender(new AliyunSmsOptions()), null); for (var i = 0; i < 12; i++) { verifyResult = await twoFactorManager.VerifyCodeAsync(row.SentTo, "WRONG!", true); Assert.IsFalse(verifyResult.Ok); } row = testDb.TwoFactorCodes.First(); Assert.IsFalse(row.IsUsed); Assert.IsTrue(row.ErrorTimes > 10); //it still fails even the code is correct this time, because it has already failed for more than 10 times verifyResult = await twoFactorManager.VerifyCodeAsync(row.SentTo, row.Code, true); Assert.IsFalse(verifyResult.Ok); //reset then try a good one row.ErrorTimes = 0; testDb.SaveChanges(); verifyResult = await twoFactorManager.VerifyCodeAsync(row.SentTo, row.Code, true); row = testDb.TwoFactorCodes.First(); Assert.IsTrue(verifyResult.Ok); Assert.IsTrue(row.IsUsed); //if try one more time, it should fail because the code is used verifyResult = await twoFactorManager.VerifyCodeAsync(row.SentTo, row.Code, true); Assert.IsFalse(verifyResult.Ok); testDb.Database.EnsureDeleted(); }
/// <summary> /// 日志记录 /// </summary> /// <param name="folderName">文件夹名字</param> /// <param name="message">内容</param> /// <param name="fileName">文件名(不带后缀)</param> /// <param name="path">保存文件地址</param> public static void WriteLog(string folderName, string message, string fileName, string path) { try { PrincipalUser principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; var current = HttpContext.Current; if (current != null) { principalUser = FormAuthenticationExtension.Current(HttpContext.Current.Request); } if (principalUser == null) { principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; } var strPath = string.IsNullOrEmpty(path) ? LogPath : path; strPath = strPath + folderName + "\\" + DateTime.Now.ToString("yyyy-MM-dd"); lock (Lock) { var strFilename = strPath + "\\" + fileName + ".txt"; if (!Directory.Exists(strPath)) { Directory.CreateDirectory(strPath); } var layout = new PatternLayout("%m%n"); var appender = new FileAppender(layout, strFilename, true); BasicConfigurator.Configure(appender); var log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); log.Info( "</br>----------------------------------------------</br>\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + principalUser.Name + "(" + principalUser.UserId + ")" + "</br>\r\n" + message); log4net.LogManager.Shutdown(); } } catch { throw new Exception("日志记录失败"); } }
public async Task <JsonResult> Submit(UserLoginInput input) { var operateStatus = new OperateStatus(); try { //获取生成验证码的结果值 var verifyCode = VerifyCodeUtil.GetVerifyCode(); //判断录入验证码和生成的验证码值是否相等 if (input.Verify != verifyCode) { operateStatus.ResultSign = ResultSign.Error; operateStatus.Message = "验证码错误"; return(Json(operateStatus)); } //验证数据库信息 var info = await _userInfoLogic.CheckUserByCodeAndPwd(input); if (info.Data != null) { var principalUser = new PrincipalUser { UserId = info.Data.UserId, Code = info.Data.Code, Name = info.Data.Name, OrganizationId = info.Data.OrganizationId, OrganizationName = info.Data.OrganizationName }; principalUser.LoginId = Guid.NewGuid(); //写入Cookie信息 FormAuthenticationExtension.SetAuthCookie(principalUser.UserId.ToString(), principalUser, input.Remberme); //是否具有返回路径 if (Url.IsLocalUrl(input.ReturnUrl) && input.ReturnUrl.Length > 1 && input.ReturnUrl.StartsWith("/") && !input.ReturnUrl.StartsWith("//") && !input.ReturnUrl.StartsWith("/\\")) { info.ResultSign = ResultSign.Successful; info.Message = input.ReturnUrl; } //写入日志 WriteLoginLog(principalUser.LoginId); } return(Json(info)); } catch (Exception ex) { operateStatus.Message = ex.Message; return(Json(operateStatus)); } }
/// <summary> /// 构造函数 /// </summary> /// <param name="principalUser">登录用户</param> /// <param name="loginLogId">登录用户</param> /// <param name="accessor">登录用户</param> public LoginLogHandler(PrincipalUser principalUser, IHttpContextAccessor accessor, Guid loginLogId) : base("SystemLoginLog") { Log = new LoginLog { LoginLogId = loginLogId, RemoteIp = IpBrowserUtil.GetRemoteIp(accessor), RemoteIpAddress = IpBrowserUtil.GetRemoteIpAddress(accessor), CreateUserId = principalUser.UserId, CreateUserName = principalUser.Name, CreateTime = DateTime.Now, CreateUserCode = principalUser.Code, LoginTime = DateTime.Now }; }
/// <summary> /// 构造函数 /// </summary> /// <param name="exception">错误信息</param> public ExceptionLogHandler(Exception exception) : base("ExceptionLogToDatabase") { PrincipalUser principalUser = new PrincipalUser { Name = "匿名用户", UserId = Guid.Empty }; var current = HttpContext.Current; if (current != null) { principalUser = FormAuthenticationExtension.Current(HttpContext.Current.Request); } if (principalUser == null) { principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; } log = new ExceptionLog { CreateTime = DateTime.Now, Message = exception.Message, StackTrace = exception.StackTrace, ExceptionType = exception.GetType().FullName, CreateUserCode = principalUser.Code, CreateUserName = principalUser.Name, ServerHost = String.Format("{0}【{1}】", IpBrowserUtil.GetServerHost(), IpBrowserUtil.GetServerHostIp()), ClientHost = String.Format("{0}", IpBrowserUtil.GetClientIp()), Runtime = "Web" }; //获取服务器信息 var request = HttpContext.Current.Request; log.RequestUrl = string.Format("{0} ", request.Url); log.HttpMethod = request.HttpMethod; log.UserAgent = request.UserAgent; var inputStream = request.InputStream; var streamReader = new StreamReader(inputStream); var requestData = HttpUtility.UrlDecode(streamReader.ReadToEnd()); log.RequestData = requestData; log.InnerException = exception.InnerException != null?GetExceptionFullMessage(exception.InnerException) : ""; }
/// <summary> /// 操作日志 /// </summary> public OperationLogHandler(IHttpContextAccessor accessor, HttpRequest request, PrincipalUser principalUser) : base("SystemOperationLog") { Log = new OperateLog { OperationLogId = Guid.NewGuid(), CreateTime = DateTime.Now, RemoteIp = IpBrowserUtil.GetRemoteIp(accessor), RequestContentLength = request.ContentLength, RequestType = request.Method, RequestData = RequestData(request), Url = request.Path.Value, CreateUserName = principalUser.Name, CreateUserCode = principalUser.Code, CreateUserId = principalUser.UserId, }; }
public async Task LogOperationAsyncTestAsync() { var serviceProvider = BuildServiceProvider(); var db = serviceProvider.GetRequiredService <IDiagnosticsDbContext>(); var http = serviceProvider.GetRequiredService <IHttpContextAccessor>(); var principal = PrincipalUser.Personate(1, "Someone", serviceProvider); var logger = new DiagnosticsLogger(db, http, principal); //log an operation await logger.LogOperationAsync(LogLevel.Trace, "UnitTest"); Assert.AreEqual(1, db.OperationLogs.Count()); var findRow = db.OperationLogs.FirstOrDefault(x => x.Message == "UnitTest"); var rowId = findRow.Id; Assert.IsNotNull(findRow); Assert.AreEqual(1, findRow.Repeated); Assert.AreEqual(LogLevel.Trace, findRow.LogLevel); Assert.AreEqual(principal.Id, findRow.UserId); Assert.AreEqual(principal.AnonymousId, findRow.AnonymousId); Assert.AreEqual(principal.DisplayName, findRow.UserName); //log the same message one more time, should be still only 1 row await logger.LogOperationAsync(LogLevel.Trace, "UnitTest"); Assert.AreEqual(1, db.OperationLogs.Count()); //find back the row, the Repeated value should be 2 now findRow = db.OperationLogs.Find(rowId); Assert.AreEqual(2, findRow.Repeated); //log some different operations await logger.LogOperationAsync(LogLevel.Warning, "Make a difference"); await logger.LogOperationAsync(LogLevel.Warning, "Again"); await logger.LogOperationAsync(LogLevel.Warning, "One more time"); Assert.AreEqual(4, db.OperationLogs.Count()); db.Normalize().Database.EnsureDeleted(); }
public PrincipalUser FillData(PrincipalUser principalUser) { string storedProcedure = "Negocio_GetData_Principal_User"; Connection connection = new Connection(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = storedProcedure; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Connection = connection.connectionString; SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); SqlParameter paramIdUsuario = new SqlParameter(); paramIdUsuario.SqlDbType = SqlDbType.NVarChar; paramIdUsuario.ParameterName = "@IdUsuario"; paramIdUsuario.Value = principalUser.IdUsuario; sqlCommand.Parameters.Add(paramIdUsuario); SqlParameter paramIdCategoria = new SqlParameter(); paramIdCategoria.SqlDbType = SqlDbType.SmallInt; paramIdCategoria.ParameterName = "@IdCategoria"; paramIdCategoria.Value = principalUser.IdCategoria; sqlCommand.Parameters.Add(paramIdCategoria); connection.Connect(); using (SqlDataReader reader = sqlCommand.ExecuteReader()) { while (reader.Read()) { principalUser.Nombres = reader["Nombres"].ToString(); principalUser.Apellidos = reader["Apellidos"].ToString(); principalUser.NombreCategoria = reader["NombreCategoria"].ToString(); principalUser.NombreNivel = reader["NombreNivel"].ToString(); principalUser.IdNivel = Convert.ToInt16(reader["IdNivel"].ToString()); principalUser.Cantidad = Convert.ToInt16(reader["Cantidad"].ToString()); } } connection.Disconnect(); return(principalUser); }
/// <summary> /// 获取当前用户 /// </summary> /// <returns></returns> public static PrincipalUser GetCurrentUser() { PrincipalUser principalUser; //通过Cookie获取当前登陆名 string loginName = GetCurrentUserLoginName(); var currentUser = RedisHelper.Get <UserBackFullInfo>("GGNCenterUser_" + loginName); //if (string.IsNullOrEmpty(loginName)) if (currentUser == null) { principalUser = (PrincipalUser)null; HttpContext.Current.Session[loginName] = null; } else { var orgslist = RedisHelper.Get <List <Org_Organization> >("GGNCenterOrgs"); if (orgslist == null) { //看该如何处理吧 } //把全部员工数据放入缓存,如果取不到值(没有设置或者过期) var allorguserdata = RedisHelper.Get <List <View_UserOrgInfo> >("GGNCenterOrgAllPersons"); if (allorguserdata == null || allorguserdata.Count == 0) { //看该如何处理吧 } principalUser = new PrincipalUser(); principalUser.Id = currentUser.BaseInfo.Id; principalUser.LoginName = currentUser.BaseInfo.LoginName; principalUser.UserName = currentUser.BaseInfo.UserName; principalUser.UserCode = currentUser.BaseInfo.Code; principalUser.IsOutSide = currentUser.BaseInfo.IsOutSide; principalUser.IsManager = currentUser.BaseInfo.IsSuperMgr; //Session已有 if (HttpContext.Current.Session[principalUser.LoginName] == null) { //设置Session对象 HttpContext.Current.Session[principalUser.LoginName] = currentUser; } } return(principalUser); }
/// <summary> /// 获取当前登录人员信息 /// </summary> /// <param name="httpContextAccessor"></param> /// <returns></returns> public static PrincipalUser CurrentUser(this IHttpContextAccessor httpContextAccessor) { var user = httpContextAccessor?.HttpContext?.User; PrincipalUser currentUser = new PrincipalUser(); if (user != null && user.Identity.IsAuthenticated) { currentUser.UserId = Guid.Parse(user.FindFirst(JwtRegisteredClaimNames.Jti)?.Value); currentUser.Name = user.FindFirst("Name")?.Value; currentUser.Code = user.FindFirst("Code")?.Value; currentUser.OrganizationId = user.FindFirst("OrganizationId")?.Value == "" ? Guid.Empty : Guid.Parse(user?.FindFirst("OrganizationId")?.Value); currentUser.OrganizationName = user.FindFirst("OrganizationName")?.Value; currentUser.LoginId = Guid.Parse(user.FindFirst("LoginId")?.Value); } else { currentUser.UserId = Guid.Empty; currentUser.Name = "匿名用户"; } return(currentUser); }
/// <summary> /// 构造函数 /// </summary> /// <param name="loginLogId">登录Id</param> public LoginLogHandler(Guid loginLogId) : base("LoginLogToDatabase") { PrincipalUser principalUser = new PrincipalUser { Name = "匿名用户", UserId = Guid.Empty }; var current = HttpContext.Current; if (current != null) { principalUser = FormAuthenticationExtension.Current(HttpContext.Current.Request); } if (principalUser == null) { principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; } var request = HttpContext.Current.Request; log = new LoginLog { LoginLogId = loginLogId, CreateUserId = principalUser.UserId, CreateUserCode = principalUser.Code ?? "", CreateUserName = principalUser.Name, ServerHost = String.Format("{0}【{1}】", IpBrowserUtil.GetServerHost(), IpBrowserUtil.GetServerHostIp()), ClientHost = String.Format("{0}", IpBrowserUtil.GetClientIp()), UserAgent = request.Browser.Browser + "【" + request.Browser.Version + "】", OsVersion = IpBrowserUtil.GetOsVersion(), LoginTime = DateTime.Now, IpAddressName = IpBrowserUtil.GetAddressByApi() }; //根据提供的api接口获取登录物理地址:http://whois.pconline.com.cn/ }
public SqlLogHandler(string operateSql, DateTime endDateTime, double elapsedTime, string parameter ) : base("SqlLogToDatabase") { PrincipalUser principalUser = new PrincipalUser { Name = "匿名用户", UserId = Guid.Empty }; var current = HttpContexts.Current; if (current != null) { principalUser = AuthenticationExtension.Current(); } if (principalUser == null) { principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; } log = new SqlLog { SqlLogId = CombUtil.NewComb(), CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CreateUserId = principalUser.UserId.ToString(), CreateUserCode = principalUser.Code, CreateUserName = principalUser.Name, OperateSql = operateSql, ElapsedTime = elapsedTime, EndDateTime = endDateTime.ToString("yyyy-MM-dd HH:mm:ss"), Parameter = parameter }; }
/// <summary> /// 构造函数 /// </summary> /// <param name="exception">错误信息</param> /// <param name="accessor">Ip信息</param> /// <param name="principalUser"></param> public ExceptionLogHandler( Exception exception, IHttpContextAccessor accessor, PrincipalUser principalUser) : base("SystemExceptionLog") { //获取服务器信息 var request = accessor.HttpContext.Request; Log = new ExceptionLog { CreateTime = DateTime.Now, Message = exception.Message, StackTrace = exception.StackTrace, RemoteIp = IpBrowserUtil.GetRemoteIp(accessor), RemoteIpAddress = IpBrowserUtil.GetRemoteIpAddress(accessor), CreateUserCode = principalUser.Code, CreateUserName = principalUser.Name, RequestUrl = request.Path.Value, HttpMethod = request.Method, RequestData = RequestData(request), InnerException = exception.InnerException != null?GetExceptionFullMessage(exception.InnerException) : "" }; }
/// <summary> /// 构造函数 /// </summary> public DataLogHandler(byte operateType, string operateTable, string operateData = null, string operateAfterData = null) : base("DataLogToDatabase") { PrincipalUser principalUser = new PrincipalUser { Name = "匿名用户", UserId = Guid.Empty }; var current = HttpContext.Current; if (current != null) { principalUser = FormAuthenticationExtension.Current(HttpContext.Current.Request); } if (principalUser == null) { principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; } log = new DataLog() { OperateType = operateType, OperateTable = operateTable, OperateData = operateData, OperateAfterData = operateAfterData, CreateTime = DateTime.Now, CreateUserId = principalUser.UserId, CreateUserCode = principalUser.Code, CreateUserName = principalUser.Name, DataLogId = CombUtil.NewComb() }; }
/// <summary> /// 人脸识别登录 /// </summary> /// <returns></returns> public async Task <JsonResult> LoginFaceSubmit(string facebase) { OperateStatus <UserLoginOutput> operateStatus = new OperateStatus <UserLoginOutput>(); var results = new FaceUtil().SearchFace(facebase); if (results.error_msg == "SUCCESS") { var infobase = await _systemUserLogic.GetById(results.result.user_id.Replace('M', '-')); var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(new UserLoginInput { Code = infobase.Code, Password = infobase.Password }); if (info != null) { var prin = new PrincipalUser() { UserId = Guid.Parse(info.Data.UserId), Code = info.Data.Code, Name = info.Data.Name, IsAdmin = info.Data.IsAdmin, RoleName = info.Data.RoleName, ImgUrl = info.Data.ImgUrl }; //写入Cookie信息 AuthenticationExtension.SetAuthCookie(prin); //写入日志 var logHandler = new LoginLogHandler(info.Data.UserId, info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录); logHandler.WriteLog(); } } else { operateStatus.ResultSign = Core.Entities.ResultSign.Error; operateStatus.Message = "识别失败!"; goto End; } End: return(Json(operateStatus)); }
public async Task SendCodeThroughAliyunSmsTest() { var settings = new AliyunSmsOptions { DefaultSignName = "星翼软件", DefaultTemplateCode = "SMS_170155854", AccessKeyId = "", AccessKeySecret = "" }; if (string.IsNullOrEmpty(settings.AccessKeySecret)) { return; } using var testDb = new DbContextOptionsBuilder <TwoFactorDbContext>().UseInMemoryDatabase("UnitTest").CreateDbContext(); var principal = PrincipalUser.Personate(1, "TestUser", null); var smsSender = new AliyunSmsSender(settings); var twoFactorManager = new TwoFactorManager(testDb, principal, smsSender, null); var sendTo = "17751283521"; var sentResult = await twoFactorManager.SendCodeThroughSmsAsync(sendTo); var row = testDb.TwoFactorCodes.FirstOrDefault(); Assert.IsTrue(sentResult.Ok); Assert.IsNotNull(row); Assert.AreEqual(sendTo, row.SentTo); Assert.IsFalse(row.IsUsed); var verifyResult = await twoFactorManager.VerifyCodeAsync(sendTo, row.Code, true); row = testDb.TwoFactorCodes.FirstOrDefault(); Assert.IsTrue(verifyResult.Ok); Assert.AreEqual(sendTo, row.SentTo); Assert.IsTrue(row.IsUsed); testDb.Database.EnsureDeleted(); }
/// <summary> /// 日志记录 /// </summary> /// <param name="folderName">文件夹名字</param> /// <param name="message">内容</param> /// <param name="fileName">文件名(不带后缀)</param> /// <param name="path">保存文件地址</param> public static void WriteLog(string folderName, string message, string fileName, string path) { try { PrincipalUser principalUser = new PrincipalUser() { Name = "匿名用户", UserId = Guid.Empty }; var strPath = string.IsNullOrEmpty(path) ? LogPath : path; strPath = strPath + folderName + "\\" + DateTime.Now.ToString("yyyy-MM-dd"); lock (Lock) { } } catch { throw new Exception("日志记录失败"); } }