private AuthenticationStatus AuthenticateViaDirectory(LoginInfo loginInfo, string password) { try { if (!_authenticator.SearchDirectory(loginInfo, password)) { return(AuthenticationStatus.Error); } } catch (COMException comException) { _log.LogError(LogSourceLdap, comException); if (comException.ErrorCode == ActiveDirectoryInvalidCredentialsErrorCode) { return(AuthenticationStatus.InvalidCredentials); } return(AuthenticationStatus.Error); } catch (Exception ex) { _log.LogError(LogSourceLdap, ex); return(AuthenticationStatus.Error); } return(AuthenticationStatus.Success); }
public async Task <IHttpActionResult> GetLoginUser() { try { var loginUser = await _userRepository.GetLoginUserByIdAsync(Session.UserId); if (loginUser == null) { throw new AuthenticationException($"User does not exist with Id: {Session.UserId}"); } loginUser.LicenseType = Session.LicenseLevel; loginUser.IsSso = Session.IsSso; loginUser.IsProjectAdmin = loginUser.InstanceAdminRoleId == 1 || await _userRepository.CheckUserHasProjectAdminRoleAsync(Session.UserId); return(Ok(loginUser)); } catch (AuthenticationException) { return(Unauthorized()); } catch (Exception ex) { await _log.LogError(WebApiConfig.LogSourceUsers, ex); return(InternalServerError()); } }
public static async Task ProcessMessages(string logSource, TenantInformation tenant, IServiceLogRepository serviceLogRepository, IList <IWorkflowMessage> messages, string exceptionMessagePrepender, IWorkflowMessagingProcessor workflowMessagingProcessor) { if (messages == null || messages.Count <= 0) { return; } var processor = workflowMessagingProcessor ?? WorkflowMessagingProcessor.Instance; foreach (var actionMessage in messages.Where(a => a != null)) { try { await ActionMessageSender.Send((ActionMessage)actionMessage, tenant, processor); string message = $"Sent {actionMessage.ActionType} message: {actionMessage.ToJSON()} with tenant id: {tenant.TenantId} to the Message queue"; await serviceLogRepository.LogInformation(logSource, message); } catch (Exception ex) { string message = $"Error while sending {actionMessage.ActionType} message with content {actionMessage.ToJSON()}. {exceptionMessagePrepender}. Exception: {ex.Message}. StackTrace: {ex.StackTrace ?? string.Empty}"; await serviceLogRepository.LogError(logSource, message); throw; } } }
public async Task <IHttpActionResult> GetActiveLicenses() { try { var licenses = await _repo.GetActiveLicenses(DateTime.UtcNow, WebApiConfig.LicenseHoldTime); var response = Request.CreateResponse(HttpStatusCode.OK, licenses); return(ResponseMessage(response)); } catch (Exception ex) { await _log.LogError(WebApiConfig.LogSourceLicenses, ex); return(InternalServerError()); } }
public HttpContent Generate(int recordLimit, long?recordId = null, int?chunkSize = null, bool showHeader = true) { try { using (var writer = new StreamWriter(_stream, Encoding.Default, 512, true)) { writer.AutoFlush = true; try { if (!chunkSize.HasValue || chunkSize.Value < 0 || chunkSize.Value > recordLimit) { chunkSize = recordLimit; } int? totalRecords = 0; long currentId = 0; do { foreach (var record in _repository.GetRecords(chunkSize.Value, recordId, showHeader && currentId == 0)) { currentId = record.Id; writer.WriteLine(record.Line); } // remember the last id to start the next chunk request with that id-1 recordId = currentId - 1; totalRecords += chunkSize; } while (totalRecords < recordLimit); } catch (Exception ex) { writer.WriteLine(ex.Message); writer.WriteLine(ex.StackTrace); throw; } finally { _repository.Close(); } } } catch (Exception ex) { _log.LogError(WebApiConfig.LogRecordStatus, ex.Message).Wait(); } finally { _stream.Position = 0; } Headers.ContentType = new MediaTypeHeaderValue(mediaType); Headers.ContentDisposition = new ContentDispositionHeaderValue(dispositionType) { FileName = attachmentFileName }; Headers.ContentLength = _stream.Length; return(this); }
public async Task <IHttpActionResult> PostSession(string login, [FromBody] string password, bool force = false) { try { var decodedLogin = SystemEncryptions.Decode(login); var decodedPassword = SystemEncryptions.Decode(password); var user = await _authenticationRepository.AuthenticateUserAsync(decodedLogin, decodedPassword, false); return(await RequestSessionTokenAsync(user, force)); } catch (AuthenticationException ex) { await _log.LogInformation(WebApiConfig.LogSourceSessions, ex.Message); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.CreateHttpError())); } catch (ApplicationException ex) { await _log.LogInformation(WebApiConfig.LogSourceSessions, ex.Message); return(Conflict()); } catch (ArgumentNullException ex) { await _log.LogInformation(WebApiConfig.LogSourceSessions, ex.Message); return(BadRequest()); } catch (FormatException ex) { await _log.LogInformation(WebApiConfig.LogSourceSessions, ex.Message); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message)); } catch (Exception ex) { await _log.LogError(WebApiConfig.LogSourceSessions, ex); return(InternalServerError()); } }
internal Task LoadAsync() { return(Task.Run(async() => { try { await _log.LogInformation(WebApiConfig.LogSourceSessions, "Service starting..."); var ps = 1000; var pn = 1; int count; var expiredSessions = new List <Session>(); do { count = 0; var sessions = await _repo.SelectSessions(ps, pn); foreach (var session in sessions) { ++count; if (session.IsExpired()) { expiredSessions.Add(session); } else { InsertSession(session); } } ++pn; }while (count == ps); // Mark expired sessions as trully expired in the DB foreach (var session in expiredSessions) { await _repo.EndSession(session.SessionId, session.EndTime); } var logExpiredSessionsCount = expiredSessions.Count > 0 ? $" {expiredSessions.Count} sessions expired" : string.Empty; await _log.LogInformation(WebApiConfig.LogSourceSessions, $"Service started.{logExpiredSessionsCount}"); } catch (Exception ex) { await _log.LogError(WebApiConfig.LogSourceSessions, new Exception("Error loading sessions from database.", ex)); } })); }
public async Task <IHttpActionResult> GetLicenseTransactions(int days) { try { var uri = new Uri(WebApiConfig.AccessControl); var http = _httpClientProvider.Create(uri); if (!Request.Headers.Contains("Session-Token")) { throw new ArgumentNullException(); } var request = new HttpRequestMessage { RequestUri = new Uri(uri, "licenses/transactions?days=" + days + "&consumerType=1"), // LicenseConsumerType.Client Method = HttpMethod.Get }; request.Headers.Add("Session-Token", Request.Headers.GetValues("Session-Token").First()); var result = await http.SendAsync(request); var transactions = (await result.Content.ReadAsAsync <IEnumerable <LicenseTransaction> >()).ToArray(); var users = (await _userRepository.GetLicenseTransactionUserInfoAsync(transactions.Select(t => t.UserId).Distinct())).ToDictionary(u => u.Id); foreach (var transaction in transactions.Where(t => users.ContainsKey(t.UserId))) { var user = users[transaction.UserId]; transaction.Username = user.Login; transaction.Department = user.Department; } var response = Request.CreateResponse(HttpStatusCode.OK, transactions); return(ResponseMessage(response)); } catch (ArgumentNullException) { return(Unauthorized()); } catch (Exception ex) { await _log.LogError(WebApiConfig.LogSourceLicenses, ex); return(InternalServerError()); } }
public async Task ProcessMessages(string logSource, IApplicationSettingsRepository applicationSettingsRepository, IServiceLogRepository serviceLogRepository, IList <IWorkflowMessage> messages, string exceptionMessagePrepender, IDbTransaction transaction = null) { var tenantInfo = await applicationSettingsRepository.GetTenantInfo(transaction); if (string.IsNullOrWhiteSpace(tenantInfo?.TenantId)) { throw new TenantInfoNotFoundException("No tenant information found. Please contact your administrator."); } if (messages == null || messages.Count <= 0) { return; } foreach (var actionMessage in messages.Where(a => a != null)) { try { await WorkflowMessagingProcessor.Instance.SendMessageAsync(tenantInfo.TenantId, actionMessage); string message = $"Sent {actionMessage.ActionType} message: {actionMessage.ToJSON()} with tenant id: {tenantInfo.TenantId} to the Message queue"; await serviceLogRepository.LogInformation(logSource, message); } catch (Exception ex) { string message = $"Error while sending {actionMessage.ActionType} message with content {actionMessage.ToJSON()}. {exceptionMessagePrepender}. Exception: {ex.Message}. StackTrace: {ex.StackTrace ?? string.Empty}"; await serviceLogRepository.LogError(logSource, message); throw; } } }
/// <summary> /// Modifies serviceStatus in place, returns whether status was successfully obtained. /// </summary> private async Task <List <StatusResponse> > TryGetStatusResponse(IStatusRepository statusRepo) { try { return(await statusRepo.GetStatuses(GET_STATUS_TIMEOUT)); } catch (Exception ex) { await Log.LogError(LogSource, ex); List <StatusResponse> responseWithError = new List <StatusResponse>(); var responseData = new StatusResponse() { Name = statusRepo.Name, AccessInfo = statusRepo.AccessInfo, Result = $"ERROR: {ex.ToString()}", NoErrors = false }; responseWithError.Add(responseData); return(responseWithError); } }
public async Task Execute(IApplicationSettingsRepository applicationSettingsRepository, IServiceLogRepository serviceLogRepository, ActionMessage message, IDbTransaction transaction) { var tenantInfo = await applicationSettingsRepository.GetTenantInfo(transaction); var tenantId = tenantInfo?.TenantId; try { if (string.IsNullOrWhiteSpace(tenantId)) { throw new TenantInfoNotFoundException("No tenant information found. Please contact your administrator."); } await WorkflowMessagingProcessor.Instance.SendMessageAsync(tenantId, message); await serviceLogRepository.LogInformation("SendMessageExecutor", $"Sent {message.ActionType} message for tenant {tenantId}: {message.ToJSON()}"); } catch (Exception ex) { await serviceLogRepository.LogError("SendMessageExecutor", $"Failed to send {message.ActionType} message for tenant {tenantId}: {message.ToJSON()}. Exception: {ex.Message}"); throw; } }