public async Task Insert(AccessLogEntry entity) { const string query = @" INSERT INTO [log].[Access] ([Action] ,[Method] ,[ClientIp] ,[ProcessedAt] ,[StatusCode] ,[UserAgent] ,[UserId] ,[Referer] ,[ProcessingTime] ,[AcceptLanguage]) VALUES (@Action ,@Method ,@ClientIp ,@ProcessedAt ,@StatusCode ,@UserAgent ,@UserId ,@Referer ,@ProcessingTime ,@AcceptLanguage) "; using (var con = _connectionProvider.Connection) { await con.ExecuteAsync(query, entity); _logger.Debug($"{entity.Action} | {entity.ClientIp} | {entity.ProcessingTime}"); } }
private void PersistEntry(SqliteConnection connection, AccessLogEntry entry) { if (!entry.Time.HasValue) { return; } // get the user agent ID long id; using (var command = connection.CreateCommand()) { command.CommandText = "SELECT id FROM user_agents_latest WHERE user_agent = @user_agent"; command.Parameters.Add("@user_agent", SqliteType.Text).Value = entry.UserAgent; using (var commandReader = command.ExecuteReader()) { if (commandReader.Read()) { id = commandReader.GetInt64(0); } else { id = -1; } } } // persist the user agent if it does not exist yet if (id == -1) { using (var command = connection.CreateCommand()) { command.CommandText = "INSERT INTO user_agents_latest (user_agent) VALUES (@user_agent); SELECT last_insert_rowid();"; command.Parameters.Add("@user_agent", SqliteType.Text).Value = entry.UserAgent; using (var commandReader = command.ExecuteReader()) { commandReader.Read(); id = commandReader.GetInt64(0); } } } // persist the user agent time using (var command = connection.CreateCommand()) { command.CommandText = "INSERT INTO user_agent_times_latest (user_agent_id, date_time) VALUES (@user_agent_id, @date_time)"; command.Parameters.Add("@user_agent_id", SqliteType.Integer).Value = id; command.Parameters.Add("@date_time", SqliteType.Integer).Value = entry.Time.Value.UtcTicks; command.ExecuteNonQuery(); } }
public async Task Insert(AccessLogEntry entity) { const string query = @" insert into log.""Access"" (""Action"", ""Method"", ""ClientIp"", ""ProcessedAt"", ""StatusCode"", ""UserAgent"", ""UserId"", ""Referer"", ""ProcessingTime"", ""AcceptLanguage"") values (@Action, @Method, @ClientIp, @ProcessedAt, @StatusCode, @UserAgent, @UserId, @Referer, @ProcessingTime, @AcceptLanguage) "; using (var con = _connectionProvider.Connection) { await con.ExecuteScalarAsync <long>(query, entity); _logger.Debug($"{entity.Action} | {entity.ClientIp} | {entity.ProcessingTime}"); } }
public async Task WriteToAccessLog_ShouldntThrow() { var logs = _container.Resolve <IAccessLogRepository>(); var log = new AccessLogEntry { Action = "drop_database", ClientIp = "1.1.1.1", Method = "GET", ProcessedAt = DateTime.UtcNow, ProcessingTime = 999, Referer = "boss", StatusCode = 200, UserAgent = "me", UserId = "1", AcceptLanguage = "ru", }; await logs.Insert(log); }
/// <summary> /// Saves the specified log entry. /// </summary> /// <param name="logEntry"> /// The log entry. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool Save(AccessLogEntry logEntry) { var insertCommand = new MySqlCommand( "INSERT INTO accesslog (al_nuh, al_accesslevel, al_reqaccesslevel, al_class," + " al_allowed, al_channel, al_args) VALUES (@nuh, @accesslevel, " + "@reqaccesslevel, @class, @allowed, @channel, @args);"); insertCommand.Parameters.AddWithValue("@nuh", logEntry.User.ToString()); insertCommand.Parameters.AddWithValue("@accesslevel", logEntry.User.AccessLevel.ToString()); insertCommand.Parameters.AddWithValue("@reqaccesslevel", logEntry.RequiredAccessLevel.ToString()); insertCommand.Parameters.AddWithValue("@class", logEntry.Class.ToString()); insertCommand.Parameters.AddWithValue("@allowed", logEntry.Allowed); insertCommand.Parameters.AddWithValue("@channel", logEntry.Channel); insertCommand.Parameters.AddWithValue("@args", logEntry.Parameters); this.legacyDatabase.ExecuteCommand(insertCommand); return true; }
/// <summary> /// Adds an entry to the Access Log. /// </summary> public async Task LogAsync(AccessPoint accessPoint, AccessEvent accessEvent, Identity identity, string message) { using (var scope = serviceScopeFactory.CreateScope()) { var dataContext = scope.ServiceProvider.GetService <AccessControlContext>(); var logEntry = new AccessLogEntry() { AccessPoint = accessPoint != null ? await dataContext.AccessPoints.FindAsync(accessPoint.Id) : null, Event = accessEvent, Timestamp = DateTime.UtcNow, Identity = identity != null ? await dataContext.Identitiets.FindAsync(identity.Id) : null, Message = message, AccessLog = null }; await dataContext.AccessLogEntries.AddAsync(logEntry); await dataContext.SaveChangesAsync(); await _accessLogNotifier.NotifyLogAppendedAsync(logEntry); } }
private static async Task LogRequest( NancyContext ctx, ILifetimeScope requestContainer, HttpStatusCode?statusCode = null) { var repository = requestContainer.Resolve <IAccessLogRepository>(); var logger = requestContainer.Resolve <ILogger>(); try { var processingTime = CalculateProcessingTime(ctx); var sensitiveInfoInPathRegex = ctx.GetRegexForSensitiveInfoInPath(); var actionStr = sensitiveInfoInPathRegex != null ? sensitiveInfoInPathRegex.Replace(ctx.Request.Path, SensitiveInfoReplacement) : ctx.Request.Path; var logEntry = new AccessLogEntry { Action = Truncate(actionStr, 255), Method = Truncate(ctx.Request.Method, 15), ClientIp = Truncate(ctx.GetClientHost(), 255), StatusCode = (int?)(statusCode ?? ctx.Response?.StatusCode), ProcessedAt = DateTime.UtcNow, UserAgent = Truncate(string.Join(", ", ctx.Request.Headers["User-Agent"]), 255), UserId = Truncate(ctx.CurrentUser?.Identity?.Name, 128), ProcessingTime = processingTime, Referer = Truncate(ctx.Request.Headers.Referrer, 255), AcceptLanguage = ctx.Request.Headers["Accept-Language"].Any() ? Truncate(string.Join("|", ctx.Request.Headers["Accept-Language"]), 255) : null, }; await repository.Insert(logEntry); } catch (Exception ex) { logger.Error(ex, "LogRequest error"); } }
/// <summary> /// Saves the specified log entry. /// </summary> /// <param name="logEntry">The log entry.</param> public bool save(AccessLogEntry logEntry) { return(DAL.singleton().insert("accesslog", "", logEntry.alUser.ToString(), logEntry.alUser.accessLevel.ToString(), logEntry.alReqaccesslevel.ToString(), "", logEntry.alClass.ToString(), (logEntry.alAllowed ? "1" : "0"), logEntry.alChannel, logEntry.alParams) != -1); }
public AccessLogEntry[] get(params DAL.WhereConds[] conditions) { return(AccessLogEntry.get(conditions)); }
public static AccessLogEntry[] get(params DAL.WhereConds[] conditions) { DAL.Select q = new DAL.Select("*"); q.addWhere(conditions); q.setFrom("accesslog"); List <string> columns; ArrayList al = DAL.singleton().executeSelect(q, out columns); AccessLogEntry[] entries = new AccessLogEntry[al.Count]; for (int j = 0; j < al.Count; j++) { string[] row = (string[])al[j]; AccessLogEntry entry = new AccessLogEntry(); string usermask = string.Empty; User.UserRights useraccess = User.UserRights.Normal; #region parse for (int i = 0; i < row.Length; i++) { switch (columns[i]) { case ACCESSLOG_ID: entry._alId = int.Parse(row[i]); break; case ACCESSLOG_USER: usermask = row[i]; break; case ACCESSLOG_USER_ACCESS: useraccess = (User.UserRights)Enum.Parse(typeof(User.UserRights), row[i]); break; case ACCESSLOG_COMMAND_ACCESS: entry._alReqaccesslevel = (User.UserRights)Enum.Parse(typeof(User.UserRights), row[i]); break; case ACCESSLOG_DATE: entry._alDate = DateTime.Parse(row[i]); break; case ACCESSLOG_COMMAND_CLASS: entry._alClass = Type.GetType(row[i]); break; case ACCESSLOG_ALLOWED: entry._alAllowed = row[i] == "0" ? false : true; break; case ACCESSLOG_CHANNEL: entry._channel = row[i]; break; case ACCESSLOG_ARGS: entry._params = row[i]; break; } entry._alUser = User.newFromStringWithAccessLevel(usermask, useraccess); } #endregion entries[j] = entry; } return(entries); }
public void Post([FromBody] AccessLogEntry value) { db.AccessLogEntries.Add(value); db.SaveChanges(); }
public async Task NotifyLogAppendedAsync(AccessLogEntry accessLogEntry) { await accessLogHubContext.Clients.All.SendAsync("LogAppended", accessLogEntry); }