public DomainUser GetAppOwner(QlikQrsHub qrsHub, string appId) { DomainUser resultUser = null; try { var qrsResult = qrsHub.SendRequestAsync($"app/{appId}", HttpMethod.Get).Result; logger.Trace($"appResult:{qrsResult}"); if (qrsResult == null) { throw new Exception($"The result of the QRS request 'app/{appId}' of is null."); } dynamic jObject = JObject.Parse(qrsResult); string userDirectory = jObject?.owner?.userDirectory ?? null; string userId = jObject?.owner?.userId ?? null; if (!String.IsNullOrEmpty(userDirectory) && !String.IsNullOrEmpty(userId)) { resultUser = new DomainUser($"{userDirectory}\\{userId}"); logger.Debug($"Found app owner: {resultUser}"); } else { logger.Error($"No user directory {userDirectory} or user id {userId} found."); } } catch (Exception ex) { logger.Error(ex, $"The owner of the app {appId} could not found."); } return(resultUser); }
private static bool HasReadRights(QlikQrsHub qrsHub, ManagedTask task) { try { logger.Debug($"Search for read right of user {task.Session.User}"); var parameter = CreateAuditMatrixParameters(task.Session.User); var contentData = Encoding.UTF8.GetBytes(parameter.ToString()); var data = new ContentData() { ContentType = "application/json", FileData = contentData, }; var matrixResponse = qrsHub.SendRequestAsync("systemrule/security/audit/matrix", HttpMethod.Post, data).Result; var responseObject = JObject.Parse(matrixResponse); var matrix = responseObject["matrix"]?.FirstOrDefault(m => m["resourceId"]?.ToString() == task.Session.AppId) ?? null; if (matrix != null) { var privileges = responseObject["resources"][matrix["resourceId"]?.ToObject <string>()]["privileges"].ToList() ?? new List <JToken>(); var canAppRead = privileges?.FirstOrDefault(p => p?.ToObject <string>() == "read") ?? null; if (canAppRead != null) { return(true); } } return(false); } catch (Exception ex) { logger.Error(ex, "The read rights of the user could not found."); return(false); } }
private static QlikQrsHub GetQrsApiConnection(Connection socketConnection) { try { var hubUri = Connection.BuildQrsUri(socketConnection?.ConnectUri ?? null, socketConnection?.Config?.ServerUri ?? null); QrsHub = new QlikQrsHub(hubUri, socketConnection.ConnectCookie); return(QrsHub); } catch (Exception ex) { throw new Exception("No connection to the QRS API could be established.", ex); } }
public static bool ValidateSession(SessionInfo sessionInfo) { try { var qrsHub = new QlikQrsHub(sessionInfo.ConnectUri, sessionInfo.Cookie); var result = qrsHub.SendRequestAsync("about", HttpMethod.Get).Result; if (String.IsNullOrEmpty(result)) { return(false); } return(true); } catch { return(false); } }
private static DateTime?GetLastReloadTime(Uri serverUri, Cookie cookie, string appId) { try { var qrshub = new QlikQrsHub(serverUri, cookie); var qrsResult = qrshub.SendRequestAsync($"app/{appId}", HttpMethod.Get).Result; logger.Trace($"appResult:{qrsResult}"); dynamic jObject = JObject.Parse(qrsResult); DateTime reloadTime = jObject?.lastReloadTime.ToObject <DateTime>() ?? null; return(reloadTime); } catch (Exception ex) { logger.Error(ex, "The last reload time could not found."); return(null); } }
private JArray GetAllowedTasks(List <ManagedTask> activeTasks, QlikRequest request) { var results = new JArray(); try { Options.Analyser?.SetCheckPoint("GetAllowedTasks", $"Start - Find all running tasks"); var session = Options.SessionHelper.GetSession(Options.Config.Connection, request); var qrsHub = new QlikQrsHub(session.ConnectUri, session.Cookie); foreach (var activeTask in activeTasks) { if (activeTask.Status == 4) { continue; } var appOwner = request.GetAppOwner(qrsHub, activeTask.Session.AppId); if (appOwner != null && appOwner.ToString() == activeTask.Session.User.ToString()) { logger.Debug($"The app owner '{appOwner}' was found."); results.Add(CreateTaskResult(activeTask)); } else { if (HasReadRights(qrsHub, activeTask)) { results.Add(CreateTaskResult(activeTask)); } } } Options.Analyser?.SetCheckPoint("GetAllowedTasks", $"End - Find all running tasks"); } catch (Exception ex) { logger.Error(ex, "The list of tasks could not be determined."); } return(results); }
private static int GetTaskStatus(Uri serverUri, Cookie cookie, string appId) { try { var qrshub = new QlikQrsHub(serverUri, cookie); var qrsResult = qrshub.SendRequestAsync($"task/full", HttpMethod.Get).Result; logger.Trace($"taskResult:{qrsResult}"); dynamic tasks = JArray.Parse(qrsResult); foreach (var task in tasks) { if (task.app.id == appId) { return(task.operational.lastExecutionResult.status); } } return(0); } catch (Exception ex) { logger.Error(ex, "The last reload time could not found."); return(0); } }
public override async Task ExecuteFunction(IAsyncStreamReader <BundledRows> requestStream, IServerStreamWriter <BundledRows> responseStream, ServerCallContext context) { var response = new QlikResponse(); try { logger.Debug("The method 'ExecuteFunction' is called..."); //Read function header var functionHeader = context.RequestHeaders.ParseIMessageFirstOrDefault <FunctionRequestHeader>(); //Read common header var commonHeader = context.RequestHeaders.ParseIMessageFirstOrDefault <CommonRequestHeader>(); //Set appid logger.Info($"The Qlik app id '{commonHeader?.AppId}' in header found."); var qlikAppId = commonHeader?.AppId; //Set qlik user logger.Info($"The Qlik user '{commonHeader?.UserId}' in header found."); var domainUser = new DomainUser(commonHeader?.UserId); //Very important code line await context.WriteResponseHeadersAsync(new Metadata { { "qlik-cache", "no-store" } }); //Read parameter from qlik var row = GetParameter(requestStream); var userJson = GetParameterValue(0, row); //Parse request from qlik script logger.Debug("Parse user request..."); var request = QlikRequest.Parse(domainUser, qlikAppId, userJson); var functionCall = (ConnectorFunction)functionHeader.FunctionId; logger.Debug($"Call Function id: '{functionCall}' from client '{context?.Peer}'."); if (functionCall == ConnectorFunction.START) { #region Switch qlik user to app owner if (domainUser?.UserId == "sa_scheduler" && domainUser?.UserDirectory == "INTERNAL") { try { var oldUser = domainUser.ToString(); domainUser = new DomainUser("INTERNAL\\ser_scheduler"); logger.Debug($"Change Qlik user '{oldUser}' to task service user '{domainUser}'."); var connection = RuntimeOptions.Config.Connection; var tmpsession = RuntimeOptions.SessionHelper.Manager.CreateNewSession(connection, domainUser, qlikAppId); if (tmpsession == null) { throw new Exception("No session cookie generated. (Qlik Task)"); } var qrsHub = new QlikQrsHub(RuntimeOptions.Config.Connection.ServerUri, tmpsession.Cookie); qrsHub.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; domainUser = request.GetAppOwner(qrsHub, qlikAppId); if (domainUser == null) { throw new Exception("The owner of the App could not found."); } logger.Debug($"App owner '{domainUser}' found."); request.QlikUser = domainUser; } catch (Exception ex) { logger.Error(ex, "Could not switch the task user to real qlik user."); } } #endregion #region Function call SER.START logger.Debug("Function call SER.START..."); var newManagedTask = new ManagedTask() { StartTime = DateTime.Now, Message = "Create new report job...", Cancellation = new CancellationTokenSource(), Status = 0 }; RuntimeOptions.TaskPool.ManagedTasks.TryAdd(newManagedTask.Id, newManagedTask); var startFunction = new StartFunction(RuntimeOptions); startFunction.StartReportJob(request, newManagedTask); response.TaskId = newManagedTask.Id.ToString(); #endregion } else if (functionCall == ConnectorFunction.STOP) { #region Function call SER.STOP logger.Debug("Function call SER.STOP..."); var stopFunction = new StopFunction(RuntimeOptions); stopFunction.StopReportJobs(request); if (request.ManagedTaskId == "all") { response.Log = "All report jobs is stopping..."; } else { response.Log = $"Report job '{request.ManagedTaskId}' is stopping..."; } response.Status = 4; #endregion } else if (functionCall == ConnectorFunction.RESULT) { #region Function call SER.RESULT logger.Debug("Function call SER.RESULT..."); var resultFunction = new ResultFunction(RuntimeOptions); response = resultFunction.FormatJobResult(request); #endregion } else if (functionCall == ConnectorFunction.STATUS) { #region Function call SER.STATUS logger.Debug("Function call SER.STATUS..."); var statusFunction = new StatusFunction(RuntimeOptions); response = statusFunction.GetStatusResponse(request); #endregion } else { throw new Exception($"The id '{functionCall}' of the function call was unknown."); } } catch (Exception ex) { logger.Error(ex, $"The method 'ExecuteFunction' failed with error '{ex.Message}'."); response.Status = -1; response.SetErrorMessage(ex); } finally { logger.Trace($"Qlik status result: {JsonConvert.SerializeObject(response)}"); await responseStream.WriteAsync(GetResult(response)); LogManager.Flush(); } }
private static HubInfo GetSharedContentFromUser(string name, DomainUser hubUser, QlikQrsHub qrsApi) { var hubRequest = new HubSelectRequest() { Filter = HubSelectRequest.GetNameFilter(name), }; var sharedContentInfos = qrsApi.GetSharedContentAsync(hubRequest)?.Result; if (sharedContentInfos == null) { return(null); } if (hubUser == null) { return(sharedContentInfos.FirstOrDefault() ?? null); } foreach (var sharedContent in sharedContentInfos) { if (sharedContent.Owner.ToString() == hubUser.ToString()) { return(sharedContent); } } return(null); }