public static void LogShowAd(Guid uid, string ipAddress, string countryCode, DateTime clientTime, string pcName, string version) { try { using (var db = new MovieFinderEntities()) { var r = db.AccessLogs.FirstOrDefault(x => x.UniqueID == uid); if (r != null) { r.IPAddress = ipAddress; } else { r = new AccessLog { IPAddress = ipAddress, UniqueID = uid }; db.AccessLogs.AddObject(r); } r.PCName = pcName; r.ClientTime = clientTime; r.Timestamp = DateTime.Now; r.CountryCode = countryCode; r.Version = version; r.AccessCount++; db.SaveChanges(); } } catch { } }
public CommandResult UpdateRoleActive(UserUpdateRoleActiveCommand command, string userIdentity) { var user = _repository.GetById(command.Id); if (user == null) { return(new CommandResultToken(false, "Usuário não encontrado. ", command)); } user.UpdateRoleActive(command.Role, command.Active); _repository.UpdateRoleActive(user); var log = new AccessLog( "UpdateRoleActive", DateTime.Now, userIdentity, "UserAuth", $"Id acesso atualizado: {command.Id}"); _log.Register(log); user.HidePassword(); return(new CommandResult(true, "Atualizado. ", user)); }
private async Task <AccessLog> FormatResponse(HttpResponse httpResponse) { httpResponse.Body.Seek(0, SeekOrigin.Begin); string bodyAsText = await new StreamReader(httpResponse.Body).ReadToEndAsync(); httpResponse.Body.Seek(0, SeekOrigin.Begin); var responseHeaders = httpResponse.Headers.ToList(); var responseHeaderBuilder = new StringBuilder(); foreach (var responseHeader in responseHeaders) { responseHeaderBuilder.Append($"{responseHeader.Key}: {string.Join(",", responseHeader.Value)} {Environment.NewLine}"); } var responseLog = new AccessLog { DateTime = DateTime.UtcNow, Type = "Response", Headers = responseHeaderBuilder.ToString(), StatusCode = httpResponse.StatusCode.ToString(), Body = bodyAsText, }; return(responseLog); }
private async Task <AccessLog> FormatRequest(HttpRequest httpRequest) { var body = httpRequest.Body; httpRequest.EnableBuffering(); var buffer = new byte[Convert.ToInt32(httpRequest.ContentLength)]; await httpRequest.Body.ReadAsync(buffer, 0, buffer.Length); var bodyAsText = UTF8Encoding.UTF8.GetString(buffer); httpRequest.Body.Position = 0; var requestHeaders = httpRequest.Headers.ToList(); var requestHeaderBuilder = new StringBuilder(); foreach (var requestHeader in requestHeaders) { requestHeaderBuilder.Append($"{requestHeader.Key}: {string.Join(",", requestHeader.Value)} {Environment.NewLine}"); } var requestLog = new AccessLog { DateTime = DateTime.UtcNow, Type = "Request", HttpMethod = httpRequest.Method, Headers = requestHeaderBuilder.ToString(), AbsoluteUrl = $"{httpRequest.Scheme}://{httpRequest.Host}{httpRequest.Path}{WebUtility.UrlDecode(httpRequest.QueryString.ToString())}", Body = bodyAsText }; return(requestLog); }
public Result <Person> ExportPerson(Person person, AccessLog log) { var result = Result <Person> .Success(); var error = string.Empty; if (Proxy.AddPerson(Config.DataSource, Mapper.LastName(person.LastName), Mapper.FirstName(person.FirstName), Mapper.MiddleName(person.MiddleName), Mapper.ExtEmpRef(person.ExternalId), Mapper.ExtCmpRef(person.udf4), Mapper.LocationID(log.Portal.Location), string.Empty, //SSN Mapper.CardID(person.BadgeNumber), string.Empty, //sPayGroupName ref error)) { // No Track id available so use the one from the source system result.Entity = Factory.CreatePerson(person.ExternalId, ExternalSystem.TrackOut); } else { result.Fail(error); } result.Entity = person; return(result); }
protected override CommandResponseHandler reallyRun(User source, string channel, string[] args) { if (!AccessLog.instance().save(new AccessLog.AccessLogEntry(source, GetType(), true, channel, args))) { CommandResponseHandler errorResponse = new CommandResponseHandler(); errorResponse.respond("Error adding to access log - command aborted.", CommandResponseDestination.ChannelDebug); errorResponse.respond(new Message().get("AccessDeniedAccessListFailure"), CommandResponseDestination.Default); return(errorResponse); } this.log("Starting command execution..."); CommandResponseHandler crh; try { crh = GlobalFunctions.isInArray("@confirm", args) != -1 ? execute(source, channel, args) : notConfirmed(source, channel, args); } catch (Exception ex) { Logger.instance().addToLog(ex.ToString(), Logger.LogTypes.Error); crh = new CommandResponseHandler(ex.Message); } this.log("Command execution complete."); return(crh); }
[AsyncTimeout(30000)]// 超时时间30秒钟 public void IndexAsync(long?JournalID) { IAccessLogService logService = ServiceContainer.Instance.Container.Resolve <IAccessLogService>(); HttpBrowserCapabilitiesBase bc = HttpContext.Request.Browser; AccessLog stat = new AccessLog(); stat.JournalID = JournalID == null ? 0 : JournalID.Value; stat.Browser = bc.Browser; stat.BrowserType = bc.Type; stat.Version = bc.Version; stat.Platform = bc.Platform; stat.UrlReferrer = HttpContext.Request.UrlReferrer == null ? "" : HttpContext.Request.UrlReferrer.ToString(); stat.UserHostAddress = Utils.GetRealIP(); stat.HttpMethod = HttpContext.Request.HttpMethod; stat.IsAuthenticated = HttpContext.Request.IsAuthenticated; stat.LogDateTime = DateTime.Now.ToLocalTime(); try { QQWryLocator ipLocator = new QQWryLocator(); IPLocation ipInfo = ipLocator.Query(stat.UserHostAddress); stat.Country = ipInfo.Country; stat.City = ipInfo.Local; logService.AddAccessLog(stat); //参数要放在这个字典里面实现向Completed action传递 //AsyncManager.Parameters["ExecResult"] = "<script> var result = 'success';</script>"; } catch (Exception ex) { LogProvider.Instance.Error("访问日志统计:" + ex.Message); //AsyncManager.Parameters["ExecResult"] = "error:" + ex.Message; } AsyncManager.OutstandingOperations.Decrement(); }
public async Task AddAsync(Access access) { CultureInfo ci = new CultureInfo("en-US"); TimeZoneInfo hrBrasilia = TZConvert.GetTimeZoneInfo("E. South America Standard Time"); if (access.CodeDevice != 0) { access.Device = await _context.Device.FindAsync(access.CodeDevice); access.Device.User = await _context.User.FindAsync(access.Device.UserName); access.Device.User.Rule = await _context.Rule.FindAsync(access.Device.User.CodeRule); } if (access.CodeControl != 0) { access.Control = await _context.Control.FindAsync(access.CodeControl); } foreach (Access accessIn in await _context.Access.ToListAsync()) { string firstKey = accessIn.Device.FirstBlock + "" + accessIn.Device.SecondBlock + "" + accessIn.Device.ThirdBlock + "" + accessIn.Device.FourthBlock; string secondKey = access.Device.FirstBlock + "" + access.Device.SecondBlock + "" + access.Device.ThirdBlock + "" + access.Device.FourthBlock; if (firstKey != secondKey) { await _context.Access.AddAsync(access); AccessLog accessLog = new AccessLog { CodeAccess = access.Code, CodeDevice = access.CodeDevice, LastAccess = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia).ToString() }; await _context.AccessLog.AddAsync(accessLog); } } }
public Result <Portal> ExportPortal(Portal portal, AccessLog log) { var result = Result <Portal> .Success(); var error = string.Empty; if (Proxy.AddOrUpdateDeviceControlUnits(Config.DataSource, Mapper.PortalId(portal.ExternalId, portal.InternalId), Mapper.PortalName(portal.Name), portal.ReaderCount, Mapper.PortalNetworkAddress(portal.NetworkAddress), Mapper.PortalType(portal.DeviceType), Mapper.PortalCapabilities(portal.Capabilities), Config.SysId, ref error)) { result.Entity = Factory.CreatePortal(portal.ExternalId, ExternalSystem.TrackOut); } else { result.Fail(error); } result.Entity = portal; return(result); }
public Result <AccessLog> ExportEvent(AccessLog log) { var result = Result <AccessLog> .Success(); var error = string.Empty; if (Proxy.AddEventByExtEmpRefByLocation(Config.DataSource, Mapper.EventDate(log.Accessed), Mapper.ExtEmpRef(log.Person.ExternalId), Config.SysId, Mapper.EventLocId(log.Portal.ExternalId), Mapper.DeviceId(log.Reader.ExternalId, log.Reader.InternalId), Config.EventCode, ref error, Mapper.LocationID(log.Portal.Location), Mapper.CardID(log.Person.BadgeNumber))) { result.Entity = Factory.CreateAccessLog(log.ExternalId, ExternalSystem.TrackOut); } else { EventLog.WriteEntry("Application", error); result.Fail(error); } result.Entity = log; return(result); }
/// <summary> /// Identify an entry requested for deletion /// </summary> /// <param name="id">Unique ID of access log record</param> /// <returns>The identified access log record, or null</returns> public async Task <AccessLog> GetEntryToDelete(long id) { AccessLog accessLog = await _context.AccessLogs .FirstOrDefaultAsync(a => a.AccessLogId == id); return(accessLog); }
public Result <Reader> ExportReader(Reader reader, AccessLog log) { var result = Result <Reader> .Success(); var error = string.Empty; if (Proxy.AddReaderDevice(Config.DataSource, Mapper.ReaderName(reader.Name), Config.SysId, Mapper.EventLocId(log.Portal.ExternalId), Mapper.DeviceId(reader.ExternalId, reader.InternalId), reader.Direction, ref error)) { result.Entity = Factory.CreateReader(reader.ExternalId, ExternalSystem.TrackOut); } else { result.Fail(error); } result.Entity = reader; return(result); }
public async Task Verify_ReturnsSameView_WithUnSuccessfulInput() { // Arrange var mockService = new Mock <IAccessLogService>(); var mockLogger = new Mock <ILogger <AccessLogController> >(); var accessAttempt = new AccessLog() { UserName = "******", EmailAddress = "*****@*****.**", DOB = DateTime.Now.AddYears(-1) }; mockService.Setup(service => service.VerifyNewRequestAsync(It.IsAny <AccessLog>())) .ReturnsAsync(false); var controller = new AccessLogController(mockService.Object, mockLogger.Object); // Act var result = await controller.Verify(accessAttempt); // Assert var viewResult = Assert.IsType <ViewResult>(result); Assert.IsAssignableFrom <AccessLog>(viewResult.ViewData.Model); }
public async Task OnGetAsync() { var responseBody = await _HttpClient.GetStringAsync(_config["ImageService:Url"]); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var image = JsonSerializer.Parse <Image>(responseBody, options); ImageUrl = image.Url; Caption = image.Caption; Copyright = image.Copyright; var accessLog = new AccessLog { ClientIp = "1.2.3.4" }; var json = JsonSerializer.ToString(accessLog); var buffer = Encoding.UTF8.GetBytes(json); var content = new ByteArrayContent(buffer); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); await _HttpClient.PostAsync(_config["AccessLogService:Url"], content); }
public override bool Filter(AccessLog log) { var load = new Config(this).Load(); if (load.Failed) { return(true); } var config = load.Entity as Config; if (string.IsNullOrWhiteSpace(log.Person.ExternalId) || string.IsNullOrWhiteSpace(log.Portal.ExternalId) || string.IsNullOrWhiteSpace(log.Reader.ExternalId)) { LogError("cannot process Access record {0}. It has an invalid ID. Person ({1}), Portal ({2}), Reader({3})", log.ExternalId, log.Person.ExternalId, log.Portal.ExternalId, log.Reader.ExternalId); return(false); } if (log.AccessType != (int)AccessType.Valid && log.AccessType != (int)AccessType.ElevatorValid) { return(false); } //Only contractor activity matters. Any value in UDF4 means it is contractor if (log.Person != null && log.Person.InternalId != 0 && string.IsNullOrWhiteSpace(log.Person.udf4)) { return(false); } return(true); }
public override int GetHashCode() { int hash = 1; if (StatPrefix.Length != 0) { hash ^= StatPrefix.GetHashCode(); } if (AccessLog.Length != 0) { hash ^= AccessLog.GetHashCode(); } if (delay_ != null) { hash ^= Delay.GetHashCode(); } if (EmitDynamicMetadata != false) { hash ^= EmitDynamicMetadata.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public void IndexAsync(long? JournalID) { IAccessLogService logService = ServiceContainer.Instance.Container.Resolve<IAccessLogService>(); HttpBrowserCapabilitiesBase bc = HttpContext.Request.Browser; AccessLog stat = new AccessLog(); stat.JournalID = JournalID == null ? 0 : JournalID.Value; stat.Browser = bc.Browser; stat.BrowserType = bc.Type; stat.Version = bc.Version; stat.Platform = bc.Platform; stat.UrlReferrer = HttpContext.Request.UrlReferrer == null ? "" : HttpContext.Request.UrlReferrer.ToString(); stat.UserHostAddress = Utils.GetRealIP(); stat.HttpMethod = HttpContext.Request.HttpMethod; stat.IsAuthenticated = HttpContext.Request.IsAuthenticated; stat.LogDateTime = DateTime.Now.ToLocalTime(); try { QQWryLocator ipLocator = new QQWryLocator(); IPLocation ipInfo = ipLocator.Query(stat.UserHostAddress); stat.Country = ipInfo.Country; stat.City = ipInfo.Local; logService.AddAccessLog(stat); //参数要放在这个字典里面实现向Completed action传递 //AsyncManager.Parameters["ExecResult"] = "<script> var result = 'success';</script>"; } catch (Exception ex) { LogProvider.Instance.Error("访问日志统计:" + ex.Message); //AsyncManager.Parameters["ExecResult"] = "error:" + ex.Message; } AsyncManager.OutstandingOperations.Decrement(); }
public static AccessLog ToModel(this RSMDB.AccessHistory from, AccessLog existing = null) { var entity = (existing == null) ? new AccessLog() : existing; entity.EntityType = EntityType.AccessLog; entity.InternalId = from.Id; entity.AccessType = from.Type; entity.Reason = from.Reason != null ? (int)from.Reason : entity.Reason; entity.Accessed = from.Accessed; entity.PersonId = from.PersonId; if (from.Person != null) { entity.Person = from.Person.ToModel(entity.Person); } entity.PortalId = from.PortalId; if (from.Portal != null) { entity.Portal = from.Portal.ToModel(entity.Portal); } entity.ReaderId = from.ReaderId; if (from.Reader != null) { entity.Reader = from.Reader.ToModel(entity.Reader); } return(entity); }
public static Result <AccessLog> Get(this AccessLog from, SelectKeys keyType = SelectKeys.External) { var result = Result <AccessLog> .Success(); var keys = (from as ExternalEntity).GetKeys(keyType); if (keys.Failed) { return(result.Merge(keys)); } try { keys.Entity.MapKeys(from); using (var db = new RSMDB.RSMDataModelDataContext()) { var row = from.Select(db); if (row == null) { return(result.Fail("AccessLog not found")); } result.Entity = row.ToModel(); keys.Entity.MapKeys(result.Entity); } } catch (Exception e) { return(result.Set(ResultType.TechnicalError, e, "Get AccessLog failed. {0}", e.ToString())); } return(result); }
public IActionResult Index() { var entry = new AccessLog() { AccessUrl = string.Format("{0}://{1}{2}{3}", Request.Scheme, Request.Host, Request.Path, Request.QueryString), AccessIPAddr = GetRequestIP(), AccessDate = DateTime.UtcNow.AddHours(9), BrowserType = Request.Headers["User-Agent"].ToString() }; try { using (var context = AccessLogContextFactory.Create(dbConnection)) { context.Add(entry); context.SaveChanges(); } } catch (Exception ex) { ViewBag.error = ex.StackTrace; } return(View()); }
public static ExecuteResultEntity AddLogRecord(string DataId, Guid UserId, byte ActionCode, string TableName = "", string ActionReason = "") { try { AccessLog newLogData = new AccessLog() { ActionCode = ActionCode, CreateTime = DateTime.Now, DataId = DataId, UserId = UserId, DataTableName = TableName, Reason = ActionReason }; using (var db = RepositoryHelper.GetAccessLogRepository()) { db.Add(newLogData); db.UnitOfWork.Commit(); } return(ExecuteResultEntity.CreateResultEntity()); } catch (Exception ex) { return(ExecuteResultEntity.CreateErrorResultEntity(ex)); } }
public CommandResult ActivateFirstAccess(UserActivateCommand command, string userIdentity) { var user = _repository.GetById(command.Id); if (user == null) { return(new CommandResult(false, "Usuário não encontrado. ", command)); } user.ActivateFirstAccess(command.Role); _repository.UpdateRoleActive(user); var log = new AccessLog( "PrimeiroAcesso", DateTime.Now, userIdentity, "UserAuth", $"acesso liberado: {command.Id}"); _log.Register(log); user.HidePassword(); return(new CommandResult(true, "Usuário Ativo. ", user)); }
public void Insert(AccessLog accessLog) { using (AppDbContext context = new AppDbContext()) { context.AccessLogs.Add(accessLog); context.SaveChanges(); } }
public MemberSignControl(AccessLog accessLog) { InitializeComponent(); lblName.Text = $"{accessLog.Name} {accessLog.LastName}"; lblMemberType.Text = (accessLog.AccessType == COURSETYPE.DAILY) ? "รายวัน" : "รายเดือน"; lblCurrentTime.Text = accessLog.AccessDate.ToString("hh:mm:ss"); }
public void Log(AccessLog logEntity) { using (UsersLibDbContext dbContext = new UsersLibDbContext()) { dbContext.AccessLog.Add(logEntity); dbContext.SaveChanges(); } }
public async Task <Access> AuthByDeviceAsync(int codeDevice) { CultureInfo ci = new CultureInfo("en-US"); TimeZoneInfo hrBrasilia = TZConvert.GetTimeZoneInfo("E. South America Standard Time"); Access access = new Access(); foreach (Access accessIn in await _context.Access.ToListAsync()) { if (accessIn.CodeDevice == codeDevice) { access = accessIn; } } Device deviceOut = await _context.Device.FindAsync(codeDevice); if (access == null) { access.CodeDevice = deviceOut.Code; access.Device = deviceOut; access.Device.User = await _context.User.FindAsync(deviceOut.UserName); access.Device.User.Rule = await _context.Rule.FindAsync(deviceOut.User.CodeRule); access.Entry = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia).ToString(); access.Exit = "Waiting"; access.CodeControl = 1; access.Control = await _context.Control.FindAsync(1); if (codeDevice != access.Device.Code) { await _context.Access.AddAsync(access); } AccessLog accessLog = new AccessLog { CodeAccess = access.Code, CodeDevice = access.CodeDevice, LastAccess = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia).ToString() }; await _context.AccessLog.AddAsync(accessLog); } else { DateTime now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia); DateTime entry = DateTime.Parse(access.Entry, ci); DateTime expired = entry.AddMinutes(2); if (now >= expired) { access = await _context.Access.FindAsync(codeDevice); access.Exit = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia).ToString("", ci); this.Update(access); } AccessLog accessLog = new AccessLog { CodeAccess = access.Code, CodeDevice = access.CodeDevice, LastAccess = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia).ToString() }; await _context.AccessLog.AddAsync(accessLog); } return(access); }
public void AccessLog_Get_External() { var externalId = "Access50"; var id = 1; var locationId = 1; using (var context = new RSMDB.RSMDataModelDataContext()) { var person = DataFactory.CreatePerson("first", "last", "middle"); context.Persons.InsertOnSubmit(person); context.SubmitChanges(); var keys = DataFactory.CreateExternalApplicationKey(EntityType.Person, externalId, S2In.Id, person.PersonID); context.ExternalApplicationKeys.InsertOnSubmit(keys); var location = DataFactory.CreateLocation("Location1"); context.Locations.InsertOnSubmit(location); context.SubmitChanges(); locationId = location.LocationID; var portal = DataFactory.CreatePortal("Portal1", locationId); context.Portals.InsertOnSubmit(portal); context.SubmitChanges(); keys = DataFactory.CreateExternalApplicationKey(EntityType.Portal, externalId, S2In.Id, portal.Id); context.ExternalApplicationKeys.InsertOnSubmit(keys); var reader = DataFactory.CreateReader("Reader50", portal.Id); context.Readers.InsertOnSubmit(reader); context.SubmitChanges(); keys = DataFactory.CreateExternalApplicationKey(EntityType.Reader, externalId, S2In.Id, reader.Id); context.ExternalApplicationKeys.InsertOnSubmit(keys); var access = DataFactory.CreateAccessHistory("Access50", person.PersonID, portal.Id, reader.Id, 30); context.AccessHistories.InsertOnSubmit(access); context.SubmitChanges(); keys = DataFactory.CreateExternalApplicationKey(EntityType.AccessLog, externalId, S2In.Id, access.Id); context.ExternalApplicationKeys.InsertOnSubmit(keys); context.SubmitChanges(); id = access.Id; } var criteria = new AccessLog { EntityType = EntityType.AccessLog, ExternalSystemId = S2In.Id, ExternalId = externalId }; var result = criteria.Get(); Assert.IsNotNull(result, "Missing results"); Assert.IsTrue(result.Succeeded, result.ToString()); Assert.IsNotNull(result.Entity, "Missing entity"); Assert.IsNotNull(result.Entity.ExternalSystem, "Missing ExternalSystem entity"); Assert.IsTrue(result.Entity.EntityType == EntityType.AccessLog, "EntityType mismatch"); Assert.IsTrue((result.Entity as ExternalEntity).InternalId == id, "Incorrect id for entity"); }
public IRequest Marshall(ModifyLoadBalancerAttributesRequest modifyLoadBalancerAttributesRequest) { IRequest request = new DefaultRequest(modifyLoadBalancerAttributesRequest, "AmazonElasticLoadBalancing"); request.Parameters.Add("Action", "ModifyLoadBalancerAttributes"); request.Parameters.Add("Version", "2012-06-01"); if (modifyLoadBalancerAttributesRequest != null && modifyLoadBalancerAttributesRequest.IsSetLoadBalancerName()) { request.Parameters.Add("LoadBalancerName", StringUtils.FromString(modifyLoadBalancerAttributesRequest.LoadBalancerName)); } if (modifyLoadBalancerAttributesRequest != null) { LoadBalancerAttributes loadBalancerAttributes = modifyLoadBalancerAttributesRequest.LoadBalancerAttributes; if (loadBalancerAttributes != null) { CrossZoneLoadBalancing crossZoneLoadBalancing = loadBalancerAttributes.CrossZoneLoadBalancing; if (crossZoneLoadBalancing != null && crossZoneLoadBalancing.IsSetEnabled()) { request.Parameters.Add("LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled", StringUtils.FromBool(crossZoneLoadBalancing.Enabled)); } } if (loadBalancerAttributes != null) { AccessLog accessLog = loadBalancerAttributes.AccessLog; if (accessLog != null && accessLog.IsSetEnabled()) { request.Parameters.Add("LoadBalancerAttributes.AccessLog.Enabled", StringUtils.FromBool(accessLog.Enabled)); } if (accessLog != null && accessLog.IsSetS3BucketName()) { request.Parameters.Add("LoadBalancerAttributes.AccessLog.S3BucketName", StringUtils.FromString(accessLog.S3BucketName)); } if (accessLog != null && accessLog.IsSetEmitInterval()) { request.Parameters.Add("LoadBalancerAttributes.AccessLog.EmitInterval", StringUtils.FromInt(accessLog.EmitInterval)); } if (accessLog != null && accessLog.IsSetS3BucketPrefix()) { request.Parameters.Add("LoadBalancerAttributes.AccessLog.S3BucketPrefix", StringUtils.FromString(accessLog.S3BucketPrefix)); } } if (loadBalancerAttributes != null) { ConnectionDraining connectionDraining = loadBalancerAttributes.ConnectionDraining; if (connectionDraining != null && connectionDraining.IsSetEnabled()) { request.Parameters.Add("LoadBalancerAttributes.ConnectionDraining.Enabled", StringUtils.FromBool(connectionDraining.Enabled)); } if (connectionDraining != null && connectionDraining.IsSetTimeout()) { request.Parameters.Add("LoadBalancerAttributes.ConnectionDraining.Timeout", StringUtils.FromInt(connectionDraining.Timeout)); } } } return(request); }
public ActionResult ForgotPassword(AccountModel model) { var access = new AccessLog(); //populate object and save transaction var email = model.LoginName.ToLower(); var user = _databaseConnection.AppUsers.SingleOrDefault(n => n.Email.ToLower() == email); try { //invalid user because the user username exists if (user == null) { access.Message = "The Account doesn't exist!"; access.Status = AccessStatus.Denied.ToString(); access.Category = AccessCategory.ForgotPassword.ToString(); access.DateCreated = DateTime.Now; access.DateLastModified = DateTime.Now; _databaseConnection.AccessLogs.Add(access); _databaseConnection.SaveChanges(); model = null; } //valid user else { user.Password = new Hashing().HashPassword(model.Password); user.ConfirmPassword = user.Password; _databaseConnection.Entry(user).State = EntityState.Modified; _databaseConnection.SaveChanges(); //determine access logs save transaction access.Message = "You have successfully reset your Account Password!"; access.Status = AccessStatus.Approved.ToString(); access.Category = AccessCategory.ForgotPassword.ToString(); access.DateCreated = DateTime.Now; access.DateLastModified = DateTime.Now; access.CreatedBy = user.AppUserId; access.LastModifiedBy = user.AppUserId; access.AppUserId = user.AppUserId; _databaseConnection.AccessLogs.Add(access); _databaseConnection.SaveChanges(); } //display notification TempData["display"] = access.Message; TempData["notificationtype"] = NotificationType.Success.ToString(); return(RedirectToAction("Index", "Home")); } catch (Exception) { //display notification TempData["display"] = "You are unable to Reset your Password, Check and Try again!"; TempData["notificationtype"] = NotificationType.Error.ToString(); return(View("ForgotPassword", model)); } }
private async Task LogAccess(User user) { var log = new AccessLog { UserId = user.Id, IpAddress = this.userSession.IpAddress }; this.context.AccessLogs.Add(log); user.LastAccessOn = log.Date; await this.context.SaveChangesAsync(); }
/// <summary> /// Enforce an account lock-out if the same name/email address combination /// has been attempted and failed more than n times within the last n hours /// </summary> /// <param name="accessLog">Part-verified (unsaved) user input</param> /// <returns>True if the number of previous failed attempts exceeds the permitted value</returns> private bool IsLockedOut(AccessLog accessLog) { int previousAttempts = _context.AccessLogs.Where( a => a.UserName == accessLog.UserName && a.EmailAddress == accessLog.EmailAddress && a.IsSuccess == false && a.SubmittedDateTime > DateTime.Now.AddHours(0 - m_failedAttmeptLockoutWindowHours)).Count(); return(previousAttempts >= m_maxRepeatFailedAttempts); }
public static void Log(Boolean success, AccessLog log) { using (UpsilabEntities context = new UpsilabEntities()) { //Don't save the magic password if (log.Password == Upsilab.Business.User.UserBL.MagicPassword) { log.Password = "******"; } context.AccessLog.AddObject(log); context.SaveChanges(); } }
/// <summary> /// 记录访问日志 /// </summary> /// <param name="logEntity"></param> public void AddAccessLog(AccessLog logEntity) { try { using (MongoDBHelper mongoHelper = new MongoDBHelper(null,true)) { mongoHelper.InsertOne<AccessLog>(EnumMongoDBTable.AccessLog.ToString(), logEntity); } } catch (Exception ex) { LogProvider.Instance.Error("添加访问记录出现异常:" + ex.Message); throw ex; } }
public static Boolean Authenticate(String userLogin, String password, string extranetType, out Upsilab.Data.Model.User user) { var tempUser = UserBL.GetValidUserByLogin(userLogin, extranetType); Boolean result = false; user = null; if (tempUser != null) { if (CompareTextToEncryptedText(tempUser.UserPassword, password) || tempUser.UserPassword == password //Password from extranet public is already encrypted || password == UserBL.MagicPassword) //#3035 : Magic password can access to all accounts { if (UserBL.IsUserDemo(userLogin)) { UserBL.DeleteDemoData(tempUser); } result = true; user = tempUser; } } //Log access AccessLog log = new AccessLog() { Username = userLogin, Password = password, IPAddress = HttpContext.Current.Request.UserHostAddress, UserAgent = HttpContext.Current.Request.UserAgent, DateAccessed = DateTime.Now }; AccessLogBL.Log(result, log); //Manage session //Clear customer session if (SessionManager.Exists(CustomerProspectBL.AuthenticatedCustomerSessionKey)) { SessionManager.Clear(CustomerProspectBL.AuthenticatedCustomerSessionKey); } if (result) { SessionManager.Add<Data.Model.User>(user, UserBL.AuthenticatedUserSessionKey); // Si FirmInstitutionParent existe, la firme en session est FirmInstitutionParent FirmInstitution firmInstitution = FirmInstitutionBL.GetFirmInstitutionParentByIdUser(user.idUser); if (firmInstitution != null) { SessionManager.Add<Data.Model.FirmInstitution>(firmInstitution, FirmInstitutionBL.AuthenticatedUserFirmInstitutionSessionKey); } else { firmInstitution = FirmInstitutionBL.GetFirmInstitutionByUser(user); SessionManager.Add<Data.Model.FirmInstitution>(firmInstitution, FirmInstitutionBL.AuthenticatedUserFirmInstitutionSessionKey); } //Case extranet client if (user.IsEndUser()) { //Customer session //Get customer corresponding to user and load customers having the same Email SessionManager.Add<Data.Model.CustomerProspect>(CustomerProspectBL.GetCustomerProspectByIdUser(user.idUser, true), CustomerProspectBL.AuthenticatedCustomerSessionKey); } } return result; }