Temporary repo to track my changes on LTS functions app porting
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

263 lines
10 KiB

  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Azure.Functions.Worker;
  4. using Microsoft.Azure.Functions.Worker.Http;
  5. using Microsoft.Extensions.Logging;
  6. using Newtonsoft.Json;
  7. namespace CDP
  8. {
  9. public class AuditFunctions
  10. {
  11. private readonly ILogger<AuditFunctions> _logger;
  12. public static string FileAuditContainer = "FileAudits";
  13. public static string UserAuditContainer = "UserAudits";
  14. public static string GroupAuditContainer = "GroupAudits";
  15. public static string TenantAuditContainer = "TenantAudits";
  16. public AuditFunctions(ILogger<AuditFunctions> logger)
  17. {
  18. _logger = logger;
  19. }
  20. [Function("GetAuditLogForFile")]
  21. public async Task<IActionResult> GetAuditLogForFile([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
  22. {
  23. _logger.LogInformation("GetAuditLogForFile invoked");
  24. // Convert the JSON payload to a string
  25. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  26. if (string.IsNullOrEmpty(requestBody))
  27. return new BadRequestObjectResult(new { error = true, message = "The body is empty" });
  28. _logger.LogInformation(requestBody);
  29. GetAuditLogForFileDto dto = JsonConvert.DeserializeObject<GetAuditLogForFileDto>(requestBody);
  30. if (dto == null)
  31. return new BadRequestObjectResult(new { error = true, message = "Parse error." });
  32. List<AuditRecord> ad = await AuditDB.GetAuditRecordsBetweenDates(dto.FileId, DateTime.MinValue, DateTime.MaxValue, CDPLite.FileAuditContainer);
  33. return new OkObjectResult(ad);
  34. }
  35. [Function("GetAuditLogForUser")]
  36. public async Task<IActionResult> GetAuditLogForUser([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
  37. {
  38. _logger.LogInformation("GetAuditLogForUser invoked");
  39. // Convert the JSON payload to a string
  40. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  41. if (string.IsNullOrEmpty(requestBody))
  42. return new BadRequestObjectResult(new { error = true, message = "The body is empty" });
  43. _logger.LogInformation(requestBody);
  44. GetAuditLogForUserDto dto = JsonConvert.DeserializeObject<GetAuditLogForUserDto>(requestBody);
  45. if (dto == null)
  46. return new BadRequestObjectResult(new { error = true, message = "Parse error." });
  47. string userId = Helpers.HashAndShortenText(dto.Email.ToLower());
  48. List<AuditRecord> ad = await AuditDB.GetAuditRecordsBetweenDates(userId, DateTime.MinValue, DateTime.MaxValue, UserAuditContainer);
  49. return new OkObjectResult(ad);
  50. }
  51. [Function("GetAuditLogForGroup")]
  52. public async Task<IActionResult> GetAuditLogForGroup([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
  53. {
  54. _logger.LogInformation("GetAuditLogForGroup invoked");
  55. // Convert the JSON payload to a string
  56. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  57. if (string.IsNullOrEmpty(requestBody))
  58. return new BadRequestObjectResult(new { error = true, message = "The body is empty" });
  59. _logger.LogInformation(requestBody);
  60. GetAuditLogForGroupDto dto = JsonConvert.DeserializeObject<GetAuditLogForGroupDto>(requestBody);
  61. if (dto == null)
  62. return new BadRequestObjectResult(new { error = true, message = "Parse error." });
  63. List<AuditRecord> ad = await AuditDB.GetAuditRecordsBetweenDates(dto.GroupId, DateTime.MinValue, DateTime.MaxValue, GroupAuditContainer);
  64. return new OkObjectResult(ad);
  65. }
  66. [Function("GetAuditLogForTenant")]
  67. public async Task<IActionResult> GetAuditLogForTenant([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
  68. {
  69. _logger.LogInformation("GetAuditLogForGroup invoked");
  70. // Convert the JSON payload to a string
  71. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  72. if (string.IsNullOrEmpty(requestBody))
  73. return new BadRequestObjectResult(new { error = true, message = "The body is empty" });
  74. _logger.LogInformation(requestBody);
  75. GetAuditLogForTenantDto dto = JsonConvert.DeserializeObject<GetAuditLogForTenantDto>(requestBody);
  76. if (dto == null)
  77. return new BadRequestObjectResult(new { error = true, message = "Parse error." });
  78. List<AuditRecord> ad = await AuditDB.GetAuditRecordsBetweenDates(dto.AppKey, DateTime.MinValue, DateTime.MaxValue, TenantAuditContainer);
  79. return new OkObjectResult(ad);
  80. }
  81. [Function("AddAccessViolation")]
  82. public async Task<Boolean> AddAccessViolation([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
  83. {
  84. _logger.LogInformation("AddAccessViolation invoked");
  85. // Convert the JSON payload to a string
  86. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  87. if (string.IsNullOrEmpty(requestBody))
  88. return false;
  89. _logger.LogInformation(requestBody);
  90. AddAccessViolationDto dto = JsonConvert.DeserializeObject<AddAccessViolationDto>(requestBody);
  91. if (dto == null)
  92. return false;
  93. string message = string.Format($"Access violation recorded for file {dto.FileName}");
  94. string action = "Access Violation";
  95. await AddAudits(dto.AppKey, dto.FileId, dto.FileName, "", "", action, message);
  96. return true;
  97. }
  98. public static async Task<string> AddAuditsEvent(string appKey, string fileId, string fileName, string userId, string groupid, string action, string message)
  99. {
  100. using (var mt = new MethodTimer("AddAuditsEventMessage"))
  101. {
  102. if (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(fileId) || string.IsNullOrEmpty(action) || string.IsNullOrEmpty(message))
  103. return "";
  104. AuditEventMetadata auditEvent = new AuditEventMetadata
  105. {
  106. FileId = fileId,
  107. FileName = fileName,
  108. UserId = userId,
  109. GroupId = groupid,
  110. Action = action,
  111. Message = message
  112. };
  113. string jobId = Guid.NewGuid().ToString();
  114. string jobMeta = JsonConvert.SerializeObject(auditEvent);
  115. Job job = new Job { AppKey = appKey, EventType = JobType.AddAudits, Id = jobId, JobMetadata = jobMeta };
  116. await MetaProcessor.PublishJob(job);
  117. return jobId;
  118. }
  119. }
  120. public static async Task AddAudits(string appKey, string fileId, string fileName, string userId, string groupid, string action, string message)
  121. {
  122. if (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(fileId) || string.IsNullOrEmpty(action) || string.IsNullOrEmpty(message))
  123. {
  124. Console.WriteLine(string.Format("something weird? appKey, fileId, action, message: {0} {1} {2} {3}", appKey, fileId, action, message));
  125. return;
  126. }
  127. AuditRecord faRec = new FileAuditRecord()
  128. {
  129. AppKey = appKey,
  130. FileId = fileId,
  131. FileName = fileName,
  132. UserId = userId,
  133. GroupId = groupid,
  134. Action = action,
  135. Message = message,
  136. EventTime = DateTime.UtcNow,
  137. };
  138. Console.WriteLine("Adding File Audit Record");
  139. await AuditDB.AppendRecord(faRec.id, faRec, FileAuditContainer);
  140. AuditRecord faRecTenant = new TenantAuditRecord()
  141. {
  142. AppKey = appKey,
  143. FileId = fileId,
  144. FileName = fileName,
  145. UserId = userId,
  146. GroupId = groupid,
  147. Action = action,
  148. Message = message,
  149. EventTime = DateTime.UtcNow,
  150. };
  151. await AuditDB.AppendRecord(faRecTenant.id, faRecTenant, TenantAuditContainer);
  152. if (!string.IsNullOrEmpty(groupid))
  153. {
  154. AuditRecord faRecGroup = new GroupAuditRecord()
  155. {
  156. AppKey = appKey,
  157. FileId = fileId,
  158. FileName = fileName,
  159. UserId = userId,
  160. GroupId = groupid,
  161. Action = action,
  162. Message = message,
  163. EventTime = DateTime.UtcNow,
  164. };
  165. await AuditDB.AppendRecord(faRecGroup.id, faRecGroup, GroupAuditContainer);
  166. }
  167. AuditRecord faRecUser = new UserAuditRecord()
  168. {
  169. AppKey = appKey,
  170. FileId = fileId,
  171. FileName = fileName,
  172. UserId = userId,
  173. GroupId = groupid,
  174. Action = action,
  175. Message = message,
  176. EventTime = DateTime.UtcNow,
  177. };
  178. await AuditDB.AppendRecord(faRecUser.id, faRecUser, UserAuditContainer);
  179. }
  180. /// <summary>
  181. /// Adds the audit record on a background thread.
  182. /// </summary>
  183. private static async Task AddFileAudit(AuditRecord far)
  184. {
  185. await AuditDB.AppendRecord(far.id, far, FileAuditContainer);
  186. }
  187. private static async Task AddUserAudit(AuditRecord far)
  188. {
  189. await AuditDB.AppendRecord(far.id, far, UserAuditContainer);
  190. }
  191. private static async Task AddTenantAudit(AuditRecord far)
  192. {
  193. await Task.Run(async () =>
  194. {
  195. try
  196. {
  197. await AuditDB.AppendRecord(far.id, far, TenantAuditContainer);
  198. }
  199. catch (Exception e)
  200. {
  201. }
  202. });
  203. }
  204. private static async Task AddGroupAudit(AuditRecord far)
  205. {
  206. await Task.Run(async () =>
  207. {
  208. try
  209. {
  210. await AuditDB.AppendRecord(far.id, far, GroupAuditContainer);
  211. }
  212. catch (Exception e)
  213. {
  214. }
  215. });
  216. }
  217. }
  218. }