Example #1
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            //GET is supported for easy calls from terraform scripts since it only has GET request support out of the box.
            //https://www.terraform.io/docs/providers/http/data_source.html
            //POST calls are recommended to use over GET.

            if (_Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("ScheduleRequest: DELETE methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("DELETE methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            JObject ParsedBody = null;

            if (_Context.Request.HttpMethod == "DELETE")
            {
                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        try
                        {
                            ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                            return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                        }
                    }
                }
            }

            if (!ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.URL_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY].Type != JTokenType.String)
            {
                return(BWebResponse.BadRequest("Request must contain all necessary fields validly. Given argument: " + ParsedBody.ToString()));
            }

            string Url = (string)ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY];

            if (!Uri.TryCreate(Url, UriKind.Absolute, out Uri UriResult) ||
                (UriResult.Scheme != Uri.UriSchemeHttp && UriResult.Scheme != Uri.UriSchemeHttps))
            {
                return(BWebResponse.BadRequest("Given field " + ScheduledUrlTaskDBEntry.URL_PROPERTY + " is invalid. Given argument: " + ParsedBody.ToString()));
            }

            if (!DatabaseService.DeleteItem(
                    ScheduledUrlTaskDBEntry.DBSERVICE_SCHEDULED_URL_TASKS_TABLE(),
                    ScheduledUrlTaskDBEntry.KEY_NAME_TASK_URL,
                    new BPrimitiveType(WebUtility.UrlEncode(Url)),
                    out JObject _,
                    EBReturnItemBehaviour.DoNotReturn,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database delete operation has failed."));
            }

            return(BWebResponse.StatusOK("Task has been unscheduled."));
        }
Example #2
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("Model_GetHierarchyFile_ForRevision: GET method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            var RequestedModelName = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_ModelsKey]);

            if (!CommonMethods.TryGettingModelID(
                    DatabaseService,
                    RequestedModelName,
                    out RequestedModelID,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            if (!int.TryParse(RestfulUrlParameters[RestfulUrlParameter_RevisionsKey], out RequestedRevisionIndex))
            {
                return(BWebResponse.BadRequest("Revision index must be an integer."));
            }

            RequestedGeometryId = RestfulUrlParameters[RestfulUrlParameter_GeometryKey];

            return(GetProcessedUnrealHierarchyGeometryFile(RequestedGeometryId, _ErrorMessageAction));
        }
Example #3
0
            protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                string ApiPassthroughPublicEndpoint = null;
                string CADFileServiceEndpoint       = null;

                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("SetCallRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                JObject ParsedBody;

                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        try
                        {
                            ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("SetCallRequest-> Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                            return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                        }
                    }
                }

                if (!ParsedBody.ContainsKey(InternalSetState.API_PASSTHROUGH_PUBLIC_ENDPOINT_PROPERTY) &&
                    !ParsedBody.ContainsKey(InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY))
                {
                    _ErrorMessageAction?.Invoke("SetCallRequest-> Request does not have required fields.");
                    return(BWebResponse.BadRequest("Request does not have required fields."));
                }

                var LocalErrorMessage = "";

                if (ParsedBody.ContainsKey(InternalSetState.API_PASSTHROUGH_PUBLIC_ENDPOINT_PROPERTY))
                {
                    ApiPassthroughPublicEndpoint = (string)ParsedBody[InternalSetState.API_PASSTHROUGH_PUBLIC_ENDPOINT_PROPERTY];
                    if (!Process_SetApiPassthroughPublicEndpoint((string _Message) => { LocalErrorMessage = _Message; }, ApiPassthroughPublicEndpoint))
                    {
                        return(BWebResponse.InternalError(LocalErrorMessage));
                    }
                }
                if (ParsedBody.ContainsKey(InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY))
                {
                    CADFileServiceEndpoint = (string)ParsedBody[InternalSetState.CAD_FILE_SERVICE_ENDPOINT_PROPERTY];
                    if (!Process_SetCADFileServicePublicEndpoint((string _Message) => { LocalErrorMessage = _Message; }, CADFileServiceEndpoint))
                    {
                        return(BWebResponse.InternalError(LocalErrorMessage));
                    }
                }

                return(BWebResponse.StatusOK("Ok."));
            }
Example #4
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "POST" && _Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("Model_GetUpdateDeleteRevision: GET, POST and DELETE methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET, POST and DELETE methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            var RequestedModelName = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_ModelsKey]);

            if (!CommonMethods.TryGettingModelID(
                    DatabaseService,
                    RequestedModelName,
                    out RequestedModelID,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            if (!int.TryParse(RestfulUrlParameters[RestfulUrlParameter_RevisionsKey], out RequestedRevisionIndex))
            {
                return(BWebResponse.BadRequest("Revision index must be an integer."));
            }

            if (_Context.Request.HttpMethod == "GET")
            {
                return(GetRevisionInfo(_ErrorMessageAction));
            }
            else
            {
                if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), RequestedModelID, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Atomic operation control has failed."));
                }

                BWebServiceResponse Result;
                if (_Context.Request.HttpMethod == "DELETE")
                {
                    Result = DeleteRevision(_Context, _ErrorMessageAction);
                }
                else
                {
                    Result = UpdateRevisionInfo(_Context, _ErrorMessageAction);
                }

                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), RequestedModelID, _ErrorMessageAction);

                return(Result);
            }
        }
Example #5
0
        public static bool GetProcessedFileNode(
            WebServiceBaseTimeoutable _Request,
            ENodeType _FileType,
            IBDatabaseServiceInterface _DatabaseService,
            IBFileServiceInterface _FileService,
            string _CadFileStorageBucketName,
            string _ModelID,
            int _RevisionIndex,
            bool _bRootNodeRequested, ulong _NodeID,
            out BWebServiceResponse _SuccessResponse,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _SuccessResponse = BWebResponse.InternalError("");

            uint StartIndex = 0, Size = 0;

            if (!_bRootNodeRequested)
            {
                Convert.UniqueIDToStartIndexAndSize(_NodeID, out StartIndex, out Size);
                if (StartIndex == 0 || Size == 0)
                {
                    _FailureResponse = BWebResponse.BadRequest("Invalid Node ID.");
                    return(false);
                }
            }

            if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(_Request.InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), _ModelID, _ErrorMessageAction))
            {
                _FailureResponse = BWebResponse.InternalError("Atomic operation control has failed.");
                return(false);
            }

            var bResult = GetProcessedFileNode_Internal(
                _FileType,
                _DatabaseService,
                _FileService,
                _CadFileStorageBucketName,
                _ModelID,
                _RevisionIndex,
                _bRootNodeRequested,
                StartIndex,
                Size,
                out _SuccessResponse,
                out _FailureResponse,
                _ErrorMessageAction);

            Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(_Request.InnerProcessor, ModelDBEntry.DBSERVICE_MODELS_TABLE(), _ModelID, _ErrorMessageAction);

            return(bResult);
        }
Example #6
0
            protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("DeleteTestUser: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                JObject ParsedBody;

                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        try
                        {
                            ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("DeleteTestUser-> Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                            return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                        }
                    }
                }

                if (!ParsedBody.ContainsKey(AuthDBEntry.USER_ID_PROPERTY))
                {
                    _ErrorMessageAction?.Invoke("DeleteTestUser-> Request does not have required fields.");
                    return(BWebResponse.BadRequest("Request does not have required fields."));
                }

                var UserId = (string)ParsedBody[AuthDBEntry.USER_ID_PROPERTY];

                if (!DeleteUser(UserId, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("User delete process has been failed."));
                }

                return(BWebResponse.StatusCreated("Test user has been deleted.", new JObject()
                {
                    [AuthDBEntry.USER_ID_PROPERTY] = UserId
                }));
            }
Example #7
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("AccessCheckRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            string  RequestPayload = null;
            JObject ParsedBody;

            using (var InputStream = _Context.Request.InputStream)
            {
                using var ResponseReader = new StreamReader(InputStream);
                try
                {
                    RequestPayload = ResponseReader.ReadToEnd();
                    ParsedBody     = JObject.Parse(RequestPayload);
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("AccessCheckRequest-> Malformed request body. Body content: " + RequestPayload + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                    return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                }
            }

            if (!ParsedBody.ContainsKey("forUrlPath") ||
                !ParsedBody.ContainsKey("requestMethod") ||
                !ParsedBody.ContainsKey("authorization"))
            {
                _ErrorMessageAction?.Invoke("AccessCheckRequest-> Request does not have required fields.");
                return(BWebResponse.BadRequest("Request does not have required fields."));
            }

            return(OnRequest_Internal_Logic(ParsedBody, _ErrorMessageAction));
        }
Example #8
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("SSOAzureTokenRefreshRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);

                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method:  " + _Context.Request.HttpMethod));
            }

            if (!BWebUtilities.DoesContextContainHeader(out List <string> ClientAuthorizationHeaderValues, out string _, _Context, "client-authorization") ||
                !BUtility.CheckAndGetFirstStringFromList(ClientAuthorizationHeaderValues, out string ClientAuthorization) ||
                ClientAuthorization.Length == 0)
            {
                return(BWebResponse.BadRequest("Authorization header must be set validly."));
            }

            //Check and try refresh if expired
            if (new Controller_SSOAccessToken(ClientAuthorization, DatabaseService, MemoryService, AzureAD_AppID, AzureAD_ClientSecret, SSOSuperAdmins, _ErrorMessageAction)
                .PerformCheckAndRefresh(
                    out Controller_SSOAccessToken.EPerformCheckAndRefreshSuccessStatus SuccessStatus,
                    out ClientAuthorization,
                    out string UserID,
                    out string EmailAddressWithoutPostfix) &&
                ClientAuthorization != null && ClientAuthorization.Length > 0)
            {
                return(BWebResponse.StatusOK("Success.", new JObject()
                {
                    ["token"] = ClientAuthorization,
                    ["status"] = SuccessStatus == Controller_SSOAccessToken.EPerformCheckAndRefreshSuccessStatus.Refreshed ? "Refreshed" : "AlreadyValid",
                    ["userId"] = UserID,
                    ["email"] = EmailAddressWithoutPostfix
                }));
            }

            return(BWebResponse.Unauthorized("Please re-login."));
        }
Example #9
0
        //TODO: If SSO is enabled for user; when it loses access to the tenant, delete all rights but keep the models and user.
        private BWebServiceResponse DeleteAccessMethodForUser(HttpListenerContext _Context, out bool _bSetClearanceForApiKey, out string _ApiKey, Action <string> _ErrorMessageAction)
        {
            _bSetClearanceForApiKey = false;
            _ApiKey = null;

            var UserKey = new BPrimitiveType(RequestedUserID);

            if (!DatabaseService.GetItem(
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserDBEntry.Properties,
                    out JObject UserObject,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database fetch-user-info operation has failed."));
            }
            if (UserObject == null)
            {
                return(BWebResponse.NotFound("User does not exist."));
            }

            if (!UserObject.ContainsKey(UserDBEntry.AUTH_METHODS_PROPERTY))
            {
                return(BWebResponse.NotFound("User does not have any auth method."));
            }

            bool bFound = false;

            var AuthMethodsArray = (JArray)UserObject[UserDBEntry.AUTH_METHODS_PROPERTY];

            for (var i = (AuthMethodsArray.Count - 1); i >= 0; i--)
            {
                var MethodObject = (JObject)AuthMethodsArray[i];
                var Method       = JsonConvert.DeserializeObject <AuthMethod>(MethodObject.ToString());

                string AuthMethodKey = null;
                switch (Method.Method)
                {
                case AuthMethod.Methods.USER_EMAIL_PASSWORD_METHOD:
                {
                    if (!bIsInternalCall && Method.UserEmail.EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX))
                    {
                        return(BWebResponse.BadRequest("This auth method cannot be deleted."));
                    }
                    AuthMethodKey = Method.UserEmail + Method.PasswordMD5;
                    break;
                }

                case AuthMethod.Methods.USER_NAME_PASSWORD_METHOD:
                {
                    AuthMethodKey = Method.UserName + Method.PasswordMD5;
                    break;
                }

                case AuthMethod.Methods.API_KEY_METHOD:
                {
                    AuthMethodKey = Method.ApiKey;

                    _bSetClearanceForApiKey = true;
                    _ApiKey = Method.ApiKey;

                    if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + Method.ApiKey, _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Atomic operation control has failed."));
                    }
                    break;
                }
                }

                if (AuthMethodKey == RequestedAuthMethodKey)
                {
                    AuthMethodsArray.RemoveAt(i);
                    bFound = true;
                }
            }

            if (!bFound)
            {
                return(BWebResponse.NotFound("Auth method does not exist."));
            }

            //Update UserDBEntry
            Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                _Context,
                UserDBEntry.DBSERVICE_USERS_TABLE(),
                UserDBEntry.KEY_NAME_USER_ID,
                UserKey,
                UserObject);

            //Delete AuthDBEntry
            Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                _Context,
                AuthDBEntry.DBSERVICE_AUTHMETHODS_TABLE(),
                AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY,
                new BPrimitiveType(RequestedAuthMethodKey));

            if (_bSetClearanceForApiKey)
            {
                //Delete ApiKey from UniqueUserFields
                Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                    _Context,
                    UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                    UniqueUserFieldsDBEntry.KEY_NAME_API_KEY,
                    new BPrimitiveType(_ApiKey));
            }

            //Delete from cache
            MemoryService.DeleteKey(
                CommonData.MemoryQueryParameters,
                AuthDBEntry.KEY_NAME_AUTH_DB_ENTRY + RequestedAuthMethodKey,
                _ErrorMessageAction);

            return(BWebResponse.StatusOK("Access method has been deleted."));
        }
Example #10
0
        private BWebServiceResponse ProcessRequestLocked(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            var RequestedModelName = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_ModelsKey]);

            if (!CommonMethods.TryGettingModelID(
                    DatabaseService,
                    RequestedModelName,
                    out RequestedModelID,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            string  RequestPayload = null;
            JObject ParsedBody;

            using (var InputStream = _Context.Request.InputStream)
            {
                using var ResponseReader = new StreamReader(InputStream);
                try
                {
                    RequestPayload = ResponseReader.ReadToEnd();
                    ParsedBody     = JObject.Parse(RequestPayload);
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("Model_ChangeSharingWithUsers-> Malformed request body. Body content: " + RequestPayload + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                    return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                }
            }

            var bShareWithAllExists = ParsedBody.ContainsKey("shareWithAll");
            var bEmailsExist        = ParsedBody.ContainsKey("emails");
            var bUserIdsExist       = ParsedBody.ContainsKey("userIds");

            var FinalUserIds = new List <string>();

            bool bShareWithAll = false;

            if (bShareWithAllExists /*Exist*/)
            {
                if (ParsedBody["shareWithAll"].Type != JTokenType.Boolean)
                {
                    return(BWebResponse.BadRequest("Request is invalid."));
                }
                bShareWithAll = (bool)ParsedBody["shareWithAll"];

                if (bShareWithAll)
                {
                    if (bEmailsExist || bUserIdsExist)
                    {
                        return(BWebResponse.BadRequest("Request has shareWithAll field; therefore cannot have emails or userIds."));
                    }

                    FinalUserIds.Add("*");
                }
            }

            if (!CommonMethods.TryGettingModelInfo(
                    DatabaseService,
                    RequestedModelID,
                    out JObject _,
                    true, out ModelDBEntry Model,
                    out FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            if (!bShareWithAll)
            {
                var EmailAddresses = new List <string>();

                if (bEmailsExist)
                {
                    if (ParsedBody["emails"].Type != JTokenType.Array)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }
                    var AsJArray = (JArray)ParsedBody["emails"];

                    foreach (var Token in AsJArray)
                    {
                        if (Token.Type != JTokenType.String)
                        {
                            return(BWebResponse.BadRequest("Request is invalid."));
                        }

                        var Lowered = ((string)Token).ToLower();
                        if (!EmailAddresses.Contains(Lowered))
                        {
                            EmailAddresses.Add(Lowered);
                        }
                    }
                }
                if (bUserIdsExist)
                {
                    if (ParsedBody["userIds"].Type != JTokenType.Array)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }
                    var AsJArray = (JArray)ParsedBody["userIds"];

                    foreach (var Token in AsJArray)
                    {
                        if (Token.Type != JTokenType.String)
                        {
                            return(BWebResponse.BadRequest("Request is invalid."));
                        }

                        var Lowered = ((string)Token).ToLower();
                        if (!FinalUserIds.Contains(Lowered))
                        {
                            FinalUserIds.Add(Lowered);
                        }
                    }
                }

                if (EmailAddresses.Count > 0)
                {
                    GetTracingService()?.On_FromServiceToService_Sent(_Context, _ErrorMessageAction);

                    var EmailsJArray = new JArray();

                    foreach (var CurEmail in EmailAddresses)
                    {
                        EmailsJArray.Add(CurEmail);
                    }

                    var RequestObject = new JObject()
                    {
                        ["emailAddresses"] = EmailsJArray
                    };

                    var Result = BWebServiceExtraUtilities.InterServicesRequest(new BWebServiceExtraUtilities.InterServicesRequestRequest()
                    {
                        DestinationServiceUrl = AuthServiceEndpoint + "/auth/internal/fetch_user_ids_from_emails?secret=" + InternalCallPrivateKey,
                        RequestMethod         = "POST",
                        bWithAuthToken        = true,
                        UseContextHeaders     = _Context,
                        ContentType           = "application/json",
                        Content = new BStringOrStream(RequestObject.ToString()),
                        ExcludeHeaderKeysForRequest = null
                    },
                                                                                false,
                                                                                _ErrorMessageAction);

                    GetTracingService()?.On_FromServiceToService_Received(_Context, _ErrorMessageAction);

                    if (!Result.bSuccess || Result.ResponseCode >= 400)
                    {
                        return(new BWebServiceResponse(Result.ResponseCode, Result.Content, Result.ContentType));
                    }

                    string InterServicesRequestStringResponse = null;

                    JObject Map;
                    try
                    {
                        InterServicesRequestStringResponse = Result.Content.String;

                        var Json = JObject.Parse(InterServicesRequestStringResponse);
                        Map = (JObject)Json["map"];
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("Model_ChangeSharingWithUsers-> Malformed request body has been returned from auth service. Body content: " + InterServicesRequestStringResponse + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.InternalError("Malformed request body has been returned from auth service."));
                    }

                    foreach (var UserIdToken in Map.Values())
                    {
                        if (UserIdToken.Type == JTokenType.String)
                        {
                            var UserId = (string)UserIdToken;
                            if (!FinalUserIds.Contains(UserId))
                            {
                                FinalUserIds.Add(UserId);
                            }
                        }
                    }
                }
            }

            if (Model.ModelSharedWithUserIDs.OrderBy(t => t).SequenceEqual(FinalUserIds.OrderBy(t => t)))
            {
                return(BWebResponse.StatusOK("No change has been done."));
            }

            var OldSharedList = new List <string>(Model.ModelSharedWithUserIDs);

            Model.ModelSharedWithUserIDs = FinalUserIds;

            Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                _Context,
                ModelDBEntry.DBSERVICE_MODELS_TABLE(),
                ModelDBEntry.KEY_NAME_MODEL_ID,
                new BPrimitiveType(RequestedModelID),
                JObject.Parse(JsonConvert.SerializeObject(Model)));

            var bOldHasStar = OldSharedList.Contains("*");
            var bNewHasStar = FinalUserIds.Contains("*");

            if (bOldHasStar && !bNewHasStar)
            {
                Controller_DeliveryEnsurer.Get().DB_DeleteItem_FireAndForget(
                    _Context,
                    GloballySharedModelIDsDBEntry.DBSERVICE_GLOBALLY_SHARED_MODEL_IDS_TABLE(),
                    GloballySharedModelIDsDBEntry.KEY_NAME_MODEL_ID,
                    new BPrimitiveType(RequestedModelID));
            }
            else if (!bOldHasStar && bNewHasStar)
            {
                Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                    _Context,
                    GloballySharedModelIDsDBEntry.DBSERVICE_GLOBALLY_SHARED_MODEL_IDS_TABLE(),
                    GloballySharedModelIDsDBEntry.KEY_NAME_MODEL_ID,
                    new BPrimitiveType(RequestedModelID),
                    JObject.Parse(JsonConvert.SerializeObject(new GloballySharedModelIDsDBEntry())));
            }

            Controller_ModelActions.Get().BroadcastModelAction(new Action_ModelSharedWithUserIdsChanged
                                                               (
                                                                   RequestedModelID,
                                                                   Model.ModelOwnerUserID,
                                                                   FinalUserIds,
                                                                   OldSharedList,
                                                                   AuthorizedUser.UserID
                                                               ),
                                                               _ErrorMessageAction);

            return(BWebResponse.StatusOK("Operation has been completed."));
        }
Example #11
0
        public static BWebServiceResponse OnRequestWebhook(HttpListenerContext _Context, string _CallerMethod, Func <ServiceUtilities.Action, bool> _HandleAction, Action <string> _ErrorMessageAction = null)
        {
            string SerializedData = null;
            string TopicName      = null;

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var Reader = new StreamReader(InputStream))
                {
                    var JsonMessage = Reader.ReadToEnd();
                    try
                    {
                        var Parsed = JObject.Parse(JsonMessage);
                        if (Parsed.ContainsKey("data"))
                        {
                            var DataObject = (JObject)Parsed["data"];

                            if (DataObject.ContainsKey("topicName") /*,
                                                                     * DataObject.ContainsKey("namespaceName")
                                                                     * && DataObject.ContainsKey("requestUri")
                                                                     * && DataObject.ContainsKey("subscriptionName")*/)
                            {
                                TopicName = (string)DataObject["topicName"];
                                //var NamespaceName = (string)DataObject["namespaceName"];
                                //var RequestUri = (string)DataObject["requestUri"];
                                //var SubscriptionName = (string)DataObject["subscriptionName"];

                                _ErrorMessageAction?.Invoke($"{_CallerMethod}->OnRequest[INFO]: Action received from CloudEventSchemaV1_0. TopicName: '{TopicName}'");
                            }
                        }
                        else
                        {
                            _ErrorMessageAction?.Invoke(_CallerMethod + "->OnRequest[ERROR]: Invalid CloudEventSchemaV1_0 data type. Payload is: " + JsonMessage);
                            return(BWebResponse.BadRequest("Invalid CloudEventSchemaV1_0 data type. Json Parse error occurred."));
                        }
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke(_CallerMethod + "->OnRequest[ERROR]: Invalid CloudEventSchemaV1_0 data type. Error: " + e.Message + ", trace: " + e.StackTrace + ", payload is: " + JsonMessage);
                        return(BWebResponse.BadRequest("Invalid CloudEventSchemaV1_0 data type. Json Parse error occurred."));
                    }
                }
            }

            if (!Manager_PubSubService.Get().ReceiveSingleMessage(TopicName,
                                                                  (string ReceivedTopic, string ReceivedMessage) =>
            {
                var ParsedMessage = JObject.Parse(ReceivedMessage);
                if (ParsedMessage.ContainsKey("data"))
                {
                    SerializedData = ParsedMessage["data"].ToString();
                }
                else
                {
                    SerializedData = ParsedMessage.ToString();
                }

                if (!Manager_PubSubService.Get().DeserializeReceivedMessage(SerializedData,
                                                                            out Actions.EAction Action,
                                                                            out string SerializedAction,
                                                                            _ErrorMessageAction))
                {
                    _ErrorMessageAction?.Invoke(_CallerMethod + "->SubscribeAction: An error occured. Retrying.");
                }

                if (!_HandleAction.Invoke(Actions.DeserializeAction(Action, SerializedAction)))
                {
                    _ErrorMessageAction?.Invoke(_CallerMethod + "->DeserializeAction: An error occured. Retrying.");
                }
            }, _ErrorMessageAction))
Example #12
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            if (_Context.Request.HttpMethod != "GET")
            {
                return(BWebResponse.BadRequest($"This service does not accept requests of type : {_Context.Request.HttpMethod}"));
            }

            string FileTypeStr = "";
            string Filename    = "file";

            try
            {
                FileTypeStr = _Context.Request.QueryString.Get("fileType").ToLower().Trim().TrimStart('.');
            }
            catch
            {
                return(BWebResponse.BadRequest($"Expected parameters have not been provided"));
            }

            EProcessedFileType FileTypeEnum = EProcessedFileType.NONE_OR_RAW;

            if (Constants.ProcessedFileType_Enum_Map.ContainsKey(FileTypeStr))
            {
                FileTypeEnum = Constants.ProcessedFileType_Enum_Map[FileTypeStr];
            }
            else
            {
                return(BWebResponse.BadRequest($"Invalid File Type was provided"));
            }

            try
            {
                Filename = _Context.Request.QueryString.Get("fileName");
            }
            catch
            {
                //This is an optional field so do nothing
            }

            if (string.IsNullOrWhiteSpace(Filename))
            {
                Filename = "file";
            }

            string Url       = _Context.Request.RawUrl;
            int    CopyStart = Url.LastIndexOf('/') + 1;
            int    CopyEnd   = Url.IndexOf("?");
            string Podname   = Url.Substring(CopyStart, CopyEnd - CopyStart).TrimEnd('/');

            if (CopyEnd == -1)
            {
                return(BWebResponse.BadRequest($"Expected parameters have not been provided"));
            }

            BatchProcessingCreationService.Instance.GetBucketAndFile(Podname, out string _Bucket, out string _Filename);

            if (!string.IsNullOrWhiteSpace(_Bucket) && !string.IsNullOrWhiteSpace(_Filename))
            {
                string RawStrippedPath     = _Filename.TrimStart("raw/");
                int    FilenameStripLength = RawStrippedPath.LastIndexOf('/');
                RawStrippedPath = RawStrippedPath.Substring(0, FilenameStripLength);

                if (!FileService.CreateSignedURLForUpload(out string SignedUploadUrl, DEFAULT_UPLOAD_BUCKET, $"{Constants.ProcessedFileType_FolderPrefix_Map[FileTypeEnum]}{RawStrippedPath}/{Filename}.{Constants.ProcessedFileType_Extension_Map[FileTypeEnum]}", UPLOAD_CONTENT_TYPE, UPLOAD_URL_VALIDITY_MINUTES, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Failed to create Upload Url"));
                }

                return(BWebResponse.StatusOK("success", new JObject()
                {
                    ["uploadUrl"] = SignedUploadUrl
                }));
            }
            else
            {
                return(BWebResponse.NotFound("Could not find pod details"));
            }
        }
Example #13
0
        private BWebServiceResponse UpdateUserInfo(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            var UpdateFieldsUserEntry = new JObject();

            var    UpdateFieldsAuthEntry = new JObject();
            string NewEmailChange        = null;
            string NewUserNameChange     = null;

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                        foreach (var Child in ParsedBody)
                        {
                            if (UserDBEntry.UpdatableProperties.Contains(Child.Key))
                            {
                                if (!UserDBEntry.UpdatablePropertiesValidityCheck[Child.Key](Child.Value))
                                {
                                    return(BWebResponse.BadRequest("Given field " + Child.Key + " has invalid value."));
                                }
                                UpdateFieldsUserEntry[Child.Key] = Child.Value;
                            }
                            if (AuthDBEntry.UpdatableProperties.Contains(Child.Key))
                            {
                                UpdateFieldsAuthEntry[Child.Key] = Child.Value;
                            }

                            if (Child.Key == UserDBEntry.USER_EMAIL_PROPERTY)
                            {
                                NewEmailChange = ((string)Child.Value).ToLower();
                                if (NewEmailChange.EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX))
                                {
                                    return(BWebResponse.BadRequest("Email address cannot end with " + Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX));
                                }
                            }
                            else if (Child.Key == UserDBEntry.USER_NAME_PROPERTY)
                            {
                                NewUserNameChange = (string)Child.Value;
                                if (NewUserNameChange.EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX))
                                {
                                    return(BWebResponse.BadRequest("Username cannot end with " + Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX));
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("User_GetUpdateDeleteUser->UpdateUserInfo: Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            if (UpdateFieldsUserEntry.Count == 0)
            {
                return(BWebResponse.BadRequest("Request does not contain any matching field with the expected structure."));
            }

            bool bNewEmailAtomicnessSet = false, bNewUsernameAtomicnessSet = false;

            try
            {
                if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Atomic operation control has failed."));
                }

                if (!DatabaseService.GetItem(
                        UserDBEntry.DBSERVICE_USERS_TABLE(),
                        UserDBEntry.KEY_NAME_USER_ID,
                        new BPrimitiveType(RequestedUserID),
                        UserDBEntry.Properties,
                        out JObject UserObject,
                        _ErrorMessageAction))
                {
                    return(BWebResponse.InternalError("Database fetch-user-info operation has failed."));
                }
                if (UserObject == null)
                {
                    return(BWebResponse.NotFound("User does not exist."));
                }
                var bEmailExistInUserObject    = UserObject.ContainsKey(UserDBEntry.USER_EMAIL_PROPERTY);
                var bUsernameExistInUserObject = UserObject.ContainsKey(UserDBEntry.USER_NAME_PROPERTY);

                if (NewEmailChange != null && bEmailExistInUserObject && (string)UserObject[UserDBEntry.USER_EMAIL_PROPERTY] == NewEmailChange)
                {
                    NewEmailChange = null;
                    UpdateFieldsUserEntry.Remove(UserDBEntry.USER_EMAIL_PROPERTY);
                    UpdateFieldsAuthEntry.Remove(AuthDBEntry.USER_EMAIL_PROPERTY);
                }
                else if (NewEmailChange != null)
                {
                    if (bEmailExistInUserObject &&
                        ((string)UserObject[UserDBEntry.USER_EMAIL_PROPERTY]).EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX))
                    {
                        return(BWebResponse.BadRequest("E-mail address cannot be changed for this account type."));
                    }

                    if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL + ":" + NewEmailChange, _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Atomic operation control has failed."));
                    }
                    bNewEmailAtomicnessSet = true;

                    if (!DatabaseService.GetItem(
                            UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                            UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL,
                            new BPrimitiveType(NewEmailChange),
                            UniqueUserFieldsDBEntry.Properties,
                            out JObject ExistenceCheck,
                            _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Database fetch-uniqueness-info operation has failed."));
                    }
                    if (ExistenceCheck != null)
                    {
                        return(BWebResponse.Conflict("A user with same user e-mail already exists."));
                    }
                }

                if (NewUserNameChange != null && UserObject.ContainsKey(UserDBEntry.USER_NAME_PROPERTY) && (string)UserObject[UserDBEntry.USER_NAME_PROPERTY] == NewUserNameChange)
                {
                    NewUserNameChange = null;
                    UpdateFieldsUserEntry.Remove(UserDBEntry.USER_NAME_PROPERTY);
                    UpdateFieldsAuthEntry.Remove(AuthDBEntry.USER_NAME_PROPERTY);
                }
                else if (NewUserNameChange != null)
                {
                    if (bUsernameExistInUserObject &&
                        ((string)UserObject[UserDBEntry.USER_NAME_PROPERTY]).EndsWith(Controller_SSOAccessToken.EMAIL_USER_NAME_POSTFIX))
                    {
                        return(BWebResponse.BadRequest("Username cannot be changed for this account type."));
                    }

                    if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME + ":" + NewUserNameChange, _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Atomic operation control has failed."));
                    }
                    bNewUsernameAtomicnessSet = true;

                    if (!DatabaseService.GetItem(
                            UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                            UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME,
                            new BPrimitiveType(NewUserNameChange),
                            UniqueUserFieldsDBEntry.Properties,
                            out JObject ExistenceCheck,
                            _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Database fetch-uniqueness-info operation has failed."));
                    }
                    if (ExistenceCheck != null)
                    {
                        return(BWebResponse.Conflict("A user with same username already exists."));
                    }
                }

                return(UpdateUserInfo_Internal(
                           _Context,
                           NewEmailChange,
                           NewUserNameChange,
                           UserObject,
                           UpdateFieldsUserEntry,
                           UpdateFieldsAuthEntry,
                           _ErrorMessageAction));
            }
            finally
            {
                Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), RequestedUserID, _ErrorMessageAction);
                if (bNewEmailAtomicnessSet)
                {
                    Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL + ":" + NewEmailChange, _ErrorMessageAction);
                }
                if (bNewUsernameAtomicnessSet)
                {
                    Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_USER_NAME + ":" + NewUserNameChange, _ErrorMessageAction);
                }
            }
        }
Example #14
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            //Azure sends a GET request in case user does not have access set from Integral.
            if (_Context.Request.HttpMethod == "GET")
            {
                if (!UrlParameters.TryGetValue("redirect_url", out string RedirectUrlEncoded) || RedirectUrlEncoded.Length == 0)
                {
                    RedirectUrlEncoded = SSOAzureLoginRequest.DEFAULT_REDIRECT_URL_ENCODED;
                }

                return(SSOCommon.MakeCallerRedirected(WebUtility.UrlDecode(RedirectUrlEncoded), true, BWebResponse.Error_Unauthorized_Code, "You do not have access to this service."));
            }

            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("SSOLoginCallback: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            string ResponseContent = null;

            try
            {
                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        ResponseContent = ResponseReader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("Error: SSOLoginCallback: Error occured during request body read. Message: " + e.Message + ", trace: " + e.StackTrace);
                return(BWebResponse.BadRequest("Request body must be provided correctly."));
            }

            if (ResponseContent == null)
            {
                return(BWebResponse.BadRequest("Request body must be provided."));
            }

            if (!Parse_FirstLeg_Authentication_Content(
                    ResponseContent,
                    out string AuthorizationCode_From_FirstLeg,
                    out BMemoryQueryParameters SSOStateUniqueID_QueryParameters,
                    out SSOStateMEntry SSOState,
                    out string LocalRedirectUrl_From_FirstLeg,
                    out string EmailAddress_From_FirstLeg,
                    out string AzureADUniqueID_From_FirstLeg,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, true, FailureResponse.StatusCode, FailureResponse.ResponseContent.String));
            }

            if (!Perform_SecondLeg_Authorization(
                    AuthorizationCode_From_FirstLeg,
                    SSOStateUniqueID_QueryParameters,
                    SSOState,
                    out AuthorizationResult SuccessResponse,
                    out FailureResponse,
                    _ErrorMessageAction))
            {
                return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, true, FailureResponse.StatusCode, FailureResponse.ResponseContent.String));
            }

            //Like: Bearer [accessToken]
            var NewAuthorizationField = SuccessResponse.TokenType + (char)32 + SuccessResponse.AccessToken;

            var AccessTokenManager = new Controller_SSOAccessToken(NewAuthorizationField, DatabaseService, MemoryService, AzureAD_AppID, AzureAD_ClientSecret, SSOSuperAdmins, _ErrorMessageAction);

            if (!AccessTokenManager.RegisterUser(out string _UserID, SuccessResponse.RefreshToken, SuccessResponse.ExpiresInSeconds))
            {
                return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, true, 500, "User registration has failed."));
            }

            return(SSOCommon.MakeCallerRedirected(LocalRedirectUrl_From_FirstLeg, false, 0, null, _UserID, NewAuthorizationField));
        }
Example #15
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("CheckModelsExist: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                string  RequestPayload = null;
                JObject ParsedBody;

                try
                {
                    using (var InputStream = _Context.Request.InputStream)
                    {
                        using var ResponseReader = new StreamReader(InputStream);

                        RequestPayload = ResponseReader.ReadToEnd();
                        ParsedBody     = JObject.Parse(RequestPayload);
                    }
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("CheckModelsExist-> Malformed request body. Body content: " + RequestPayload + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                    return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                }

                //get UserModels from parsed request body
                var UserModelIDs = new List <string>();

                if (ParsedBody["userModelIds"].Type != JTokenType.Array)
                {
                    return(BWebResponse.BadRequest("Request is invalid."));
                }
                var UserModelsJArray = (JArray)ParsedBody["userModelIds"];

                foreach (var CurrentUserModelID in UserModelsJArray)
                {
                    if (CurrentUserModelID.Type != JTokenType.String)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }

                    var UserModelID = (string)CurrentUserModelID;
                    if (!UserModelIDs.Contains(UserModelID))
                    {
                        UserModelIDs.Add(UserModelID);
                    }
                }

                //get UserSharedModels from parsed request body
                var UserSharedModelIDs = new List <string>();

                if (ParsedBody["userSharedModelIds"].Type != JTokenType.Array)
                {
                    return(BWebResponse.BadRequest("Request is invalid."));
                }
                var UserSharedModelsJArray = (JArray)ParsedBody["userSharedModelIds"];

                foreach (var CurrentUserSharedModelID in UserSharedModelsJArray)
                {
                    if (CurrentUserSharedModelID.Type != JTokenType.String)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }

                    var UserSharedModelID = (string)CurrentUserSharedModelID;
                    if (!UserSharedModelIDs.Contains(UserSharedModelID))
                    {
                        UserSharedModelIDs.Add(UserSharedModelID);
                    }
                }

                var CheckedUserModelIDs = new JArray();

                foreach (var ModelID in UserModelIDs)
                {
                    var ModelKey = new BPrimitiveType(ModelID);

                    if (!CommonMethods.TryGettingModelInfo(
                            DatabaseService,
                            ModelID,
                            out JObject _,
                            true, out ModelDBEntry ModelData,
                            out BWebServiceResponse _FailedResponse,
                            _ErrorMessageAction))
                    {
                        if (_FailedResponse.StatusCode >= 400 && _FailedResponse.StatusCode < 500)
                        {
                            continue;
                        }
                        else if (_FailedResponse.StatusCode >= 500)
                        {
                            return(BWebResponse.InternalError("Getting user model info operation has been failed."));
                        }
                    }

                    if (!CheckedUserModelIDs.Contains(ModelID))
                    {
                        CheckedUserModelIDs.Add(ModelID);
                    }
                }

                var CheckedUserSharedModelIDs = new JArray();

                foreach (var SharedModelID in UserSharedModelIDs)
                {
                    var ModelKey = new BPrimitiveType(SharedModelID);

                    if (!CommonMethods.TryGettingModelInfo(
                            DatabaseService,
                            SharedModelID,
                            out JObject _,
                            true, out ModelDBEntry ModelData,
                            out BWebServiceResponse _FailedResponse,
                            _ErrorMessageAction))
                    {
                        if (_FailedResponse.StatusCode >= 400 && _FailedResponse.StatusCode < 500)
                        {
                            continue;
                        }
                        else if (_FailedResponse.StatusCode >= 500)
                        {
                            return(BWebResponse.InternalError("Getting user shared model info operation has been failed."));
                        }
                    }

                    if (!CheckedUserSharedModelIDs.Contains(SharedModelID))
                    {
                        CheckedUserSharedModelIDs.Add(SharedModelID);
                    }
                }

                return(BWebResponse.StatusOK("Check models have successfully been completed.", new JObject()
                {
                    ["checkedUserModelIds"] = CheckedUserModelIDs,
                    ["checkedUserSharedModelIds"] = CheckedUserSharedModelIDs
                }));
            }
Example #16
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            _ErrorMessageAction?.Invoke("Job complete called");
            if (_Context.Request.HttpMethod != "GET")
            {
                return(BWebResponse.BadRequest($"This service does not accept requests of type : {_Context.Request.HttpMethod}"));
            }

            string Url       = _Context.Request.RawUrl;
            int    CopyStart = Url.LastIndexOf('/') + 1;


            string Podname = Url.Substring(CopyStart);

            BatchProcessingCreationService.Instance.GetBucketAndFile(Podname, out string _Bucket, out string _Filename);

            if (_Bucket == null || _Filename == null)
            {
                return(BWebResponse.BadRequest($"The provided pod name does not exist"));
            }

            string NewConversionID_FromRelativeUrl_UrlEncoded = WebUtility.UrlEncode(_Filename);

            var NewDBEntry = new FileConversionDBEntry()
            {
                ConversionStatus = (int)EInternalProcessStage.ProcessComplete
            };

            if (!DatabaseService.UpdateItem(
                    FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                    FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                    new BPrimitiveType(NewConversionID_FromRelativeUrl_UrlEncoded),
                    JObject.Parse(JsonConvert.SerializeObject(NewDBEntry)),
                    out JObject _, EBReturnItemBehaviour.DoNotReturn,
                    null,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database error"));
            }

            if (!BatchProcessingCreationService.Instance.NotifyPodSucceded(Podname.Trim(), _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Failed to do Pod Completion or connect to kubernetes"));
            }


            //Code for initial method of starting optimizer after pixyz completes
            //if (!BatchProcessingCreationService.Instance.StartUnrealOptimizer(_Bucket, _Filename))
            //{
            //    NewDBEntry.ConversionStatus = (int)EInternalProcessStage.ProcessFailed;

            //    if (!DatabaseService.UpdateItem(
            //        FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
            //        FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
            //        new BPrimitiveType(NewConversionID_FromRelativeUrl_UrlEncoded),
            //        JObject.Parse(JsonConvert.SerializeObject(NewDBEntry)),
            //        out JObject _, EBReturnItemBehaviour.DoNotReturn,
            //        null,
            //        _ErrorMessageAction))
            //    {
            //        return BWebResponse.InternalError("Failed to start unreal optimizer and experienced a Database error");
            //    }

            //    return BWebResponse.InternalError("Failed to start unreal optimizer");
            //}


            return(BWebResponse.StatusOK("Job completion confirmed. Unreal Optimizer scheduled."));
        }
Example #17
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("StopProcessRequest: POST methods is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST methods is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            string BucketName       = null;
            string RelativeFilename = null;
            string ConversionID_FromRelativeUrl_UrlEncoded = null;

            using (var InputStream = _Context.Request.InputStream)
            {
                var NewObjectJson = new JObject();

                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());

                        if (!ParsedBody.ContainsKey("bucketName") ||
                            !ParsedBody.ContainsKey("rawFileRelativeUrl"))
                        {
                            return(BWebResponse.BadRequest("Request body must contain all necessary fields."));
                        }
                        var BucketNameToken         = ParsedBody["bucketName"];
                        var RawFileRelativeUrlToken = ParsedBody["rawFileRelativeUrl"];
                        if (BucketNameToken.Type != JTokenType.String ||
                            RawFileRelativeUrlToken.Type != JTokenType.String)
                        {
                            return(BWebResponse.BadRequest("Request body contains invalid fields."));
                        }
                        BucketName = (string)BucketNameToken;
                        ConversionID_FromRelativeUrl_UrlEncoded = WebUtility.UrlEncode((string)RawFileRelativeUrlToken);
                        RelativeFilename = (string)RawFileRelativeUrlToken;
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            //Temporarily, TODO: Change this when the implementation is in place.
            if (!DatabaseService.DeleteItem(
                    FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                    FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                    new BPrimitiveType(ConversionID_FromRelativeUrl_UrlEncoded),
                    out JObject _, EBReturnItemBehaviour.DoNotReturn,
                    _ErrorMessageAction))
            {
                if (!DatabaseService.GetItem(
                        FileConversionDBEntry.DBSERVICE_FILE_CONVERSIONS_TABLE(),
                        FileConversionDBEntry.KEY_NAME_CONVERSION_ID,
                        new BPrimitiveType(ConversionID_FromRelativeUrl_UrlEncoded),
                        FileConversionDBEntry.Properties,
                        out JObject _ReturnObject,
                        _ErrorMessageAction) ||
                    _ReturnObject != null)
                {
                    return(BWebResponse.InternalError("Database error."));
                }
            }

            if (!BatchProcessingCreationService.Instance.StopBatchProcess(BucketName, RelativeFilename, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Failed to stop pod or connect to kubernetess"));
            }

            return(BWebResponse.StatusAccepted("Request has been accepted; process is now being stopped."));
        }
Example #18
0
        private BWebServiceResponse UpdateBaseRightForUser(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            var NewRights = new List <string>();

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var NewRightsArray = JArray.Parse(ResponseReader.ReadToEnd());
                        foreach (string NewRight in NewRightsArray)
                        {
                            var NewRightCaseCorrected = NewRight.ToUpper();
                            if (AccessScopeLibrary.ACCESS_RIGHTS.Contains(NewRightCaseCorrected))
                            {
                                NewRights.Add(NewRightCaseCorrected);
                            }
                        }
                        NewRights = NewRights.Distinct().ToList();
                        NewRights.Sort();
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("User_UpdateDeleteBaseRight_ForUser->UpdateBaseRightForUser: Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            if (NewRights.Count == 0)
            {
                return(BWebResponse.BadRequest("Request does not contain any valid access right. Use DELETE method for deleting the scope. Access rights can be: " + AccessScopeLibrary.GetPossibleAccessRightsText()));
            }

            var UserKey = new BPrimitiveType(RequestedUserID);

            if (!DatabaseService.GetItem(
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserDBEntry.Properties,
                    out JObject UserObject,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database fetch-user-info operation has failed."));
            }
            if (UserObject == null)
            {
                return(BWebResponse.NotFound("User does not exist."));
            }

            if (!UserObject.ContainsKey(UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY))
            {
                return(BWebResponse.NotFound("User does not have any base rights."));
            }

            var BaseAccessScopeAsArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY];
            var BaseAccessScopeAsList  = new List <AccessScope>();

            //Check existence of access scope
            AccessScope ExistingAccessScope      = null;
            int         ExistingAccessScopeIndex = -1;

            int j = 0;

            foreach (JObject BaseAccessScopeObject in BaseAccessScopeAsArray)
            {
                var Scope = JsonConvert.DeserializeObject <AccessScope>(BaseAccessScopeObject.ToString());
                BaseAccessScopeAsList.Add(Scope);

                if (ExistingAccessScopeIndex == -1 && Scope.WildcardPath == RequestedBaseRightWildcard)
                {
                    ExistingAccessScope      = Scope;
                    ExistingAccessScopeIndex = j;
                }
                j++;
            }

            if (ExistingAccessScopeIndex == -1)
            {
                return(BWebResponse.NotFound("User does not have the given base right."));
            }

            ExistingAccessScope.AccessRights.Sort();

            //Check if requested rights are different
            bool bDifferent = false;

            if (ExistingAccessScope.AccessRights.Count == NewRights.Count)
            {
                for (var i = 0; i < ExistingAccessScope.AccessRights.Count; i++)
                {
                    if (ExistingAccessScope.AccessRights[i] != NewRights[i])
                    {
                        bDifferent = true;
                        break;
                    }
                }
            }
            else
            {
                bDifferent = true;
            }

            if (bDifferent)
            {
                ExistingAccessScope.AccessRights = NewRights;
                BaseAccessScopeAsArray[ExistingAccessScopeIndex] = JObject.Parse(JsonConvert.SerializeObject(ExistingAccessScope));

                UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY] = BaseAccessScopeAsArray;

                Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                    _Context,
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserObject);

                MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[]
                {
                    new Tuple <string, BPrimitiveType>(
                        UserBaseAccessMEntry.M_KEY_NAME_USER_ID + RequestedUserID,
                        new BPrimitiveType(JsonConvert.SerializeObject(new UserBaseAccessMEntry()
                    {
                        BaseAccessScope = BaseAccessScopeAsList
                    })))
                }, _ErrorMessageAction);
            }

            return(BWebResponse.StatusOK("Base right has been updated."));
        }
Example #19
0
            protected override BWebServiceResponse Process(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("GetUserIDsFromEmailsRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                string  RequestPayload = null;
                JObject ParsedBody;

                using (var InputStream = _Context.Request.InputStream)
                {
                    using var ResponseReader = new StreamReader(InputStream);
                    try
                    {
                        RequestPayload = ResponseReader.ReadToEnd();
                        ParsedBody     = JObject.Parse(RequestPayload);
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("GetUserIDsFromEmailsRequest-> Malformed request body. Body content: " + RequestPayload + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }

                if (!ParsedBody.ContainsKey("emailAddresses") || ParsedBody["emailAddresses"].Type != JTokenType.Array)
                {
                    return(BWebResponse.BadRequest("Invalid request body."));
                }
                var AsJArray = (JArray)ParsedBody["emailAddresses"];

                var EmailAddresses = new List <string>();

                foreach (var Token in AsJArray)
                {
                    if (Token.Type != JTokenType.String)
                    {
                        return(BWebResponse.BadRequest("Invalid request body."));
                    }

                    var EmailAddress = ((string)Token).ToLower();
                    if (!EmailAddresses.Contains(EmailAddress))
                    {
                        EmailAddresses.Add(EmailAddress);
                    }
                }

                if (EmailAddresses.Count == 0)
                {
                    return(BWebResponse.BadRequest("Empty emailAddresses field."));
                }

                var ResponseObject = new JObject();

                foreach (var Email in EmailAddresses)
                {
                    if (!DatabaseService.GetItem(
                            UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                            UniqueUserFieldsDBEntry.KEY_NAME_USER_EMAIL,
                            new BPrimitiveType(Email),
                            UniqueUserFieldsDBEntry.Properties,
                            out JObject ExistenceCheck,
                            _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Database fetch-uniqueness-info operation has failed."));
                    }
                    if (ExistenceCheck == null)
                    {
                        return(BWebResponse.NotFound("A user with e-mail " + Email + " does not exist."));
                    }

                    ResponseObject[Email] = (string)ExistenceCheck[UserDBEntry.KEY_NAME_USER_ID];
                }

                return(BWebResponse.StatusOK("OK.", new JObject()
                {
                    ["map"] = ResponseObject
                }));
            }
Example #20
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext Context, Action <string> _ErrorMessageAction = null)
        {
            if (Context.Request.HttpMethod != "POST" && Context.Request.HttpMethod != "PUT")
            {
                _ErrorMessageAction?.Invoke("BPutSecretsRequest: POST/PUT methods are accepted. But received request method:  " + Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST/PUT methods are accepted. But received request method: " + Context.Request.HttpMethod));
            }

            JObject ParsedBody;

            using var InputStream    = Context.Request.InputStream;
            using var ResponseReader = new StreamReader(InputStream);
            try
            {
                ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("BPutSecretsRequest-> Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
            }

            if (ParsedBody.Count == 0)
            {
                _ErrorMessageAction?.Invoke("BPutSecretsRequest-> Request does not have any secret field.");
                return(BWebResponse.BadRequest("Request does not have secret field."));
            }

            var WaitUntilSignal = new ManualResetEvent(false);

            var CompletionStateStack = new ConcurrentStack <object>();

            for (int i = 0; i < ParsedBody.Count; i++)
            {
                CompletionStateStack.Push(new object());
            }

            var SucceedQueue = new ConcurrentQueue <string>();
            var FailedQueue  = new ConcurrentQueue <string>();

            foreach (var Pair in ParsedBody)
            {
                BTaskWrapper.Run(() =>
                {
                    using var MemStream = new MemoryStream();
                    using var MemWriter = new StreamWriter(MemStream);
                    MemWriter.Write(Pair.Value);
                    MemWriter.Flush();
                    MemStream.Position = 0;

                    if (FileService.UploadFile(
                            new BStringOrStream(MemStream, MemStream.Length),
                            SecretsStorageBucket,
                            Pair.Key,
                            EBRemoteFileReadPublicity.AuthenticatedRead,
                            null,
                            (string Message) =>
                    {
                        _ErrorMessageAction?.Invoke("BPutSecretsRequest->Error-> " + Message);
                    }))
                    {
                        SucceedQueue.Enqueue(Pair.Key);
                    }
                    else
                    {
                        FailedQueue.Enqueue(Pair.Key);
                    }

                    CompletionStateStack.TryPop(out object Ignore);
                    if (CompletionStateStack.Count == 0)
                    {
                        try
                        {
                            WaitUntilSignal.Set();
                        }
                        catch (Exception) { }
                    }
                });
            }

            try
            {
                WaitUntilSignal.WaitOne();
                WaitUntilSignal.Close();
            }
            catch (Exception) { }

            var ResultObject = new JObject
            {
                ["succeed"] = new JArray(),
                ["failed"]  = new JArray()
            };

            while (SucceedQueue.TryDequeue(out string SucceedKey))
            {
                ((JArray)ResultObject["succeed"]).Add(SucceedKey);
            }
            while (FailedQueue.TryDequeue(out string FailedKey))
            {
                ((JArray)ResultObject["failed"]).Add(FailedKey);
            }

            return(new BWebServiceResponse(
                       BWebResponse.Status_OK_Code,
                       new BStringOrStream(ResultObject.ToString()),
                       "application/json"));
        }
Example #21
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            //GET is supported for easy calls from terraform scripts since it only has GET request support out of the box.
            //https://www.terraform.io/docs/providers/http/data_source.html
            //POST calls are recommended to use over GET.

            if (_Context.Request.HttpMethod != "GET" && _Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("ScheduleRequest: GET and POST methods are accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET and POST methods are accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            JObject ParsedBody = null;

            if (_Context.Request.HttpMethod == "GET")
            {
                if (!UrlParameters.ContainsKey("serialized"))
                {
                    return(BWebResponse.BadRequest("Malformed request. Url parameters must contain serialized= key."));
                }

                try
                {
                    ParsedBody = JObject.Parse(WebUtility.UrlDecode(UrlParameters["serialized"]));
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace + ", Content: " + UrlParameters["serialized"]);
                    return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                }
            }
            else
            {
                using (var InputStream = _Context.Request.InputStream)
                {
                    using (var ResponseReader = new StreamReader(InputStream))
                    {
                        try
                        {
                            ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                            return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                        }
                    }
                }
            }

            if (!ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.URL_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY].Type != JTokenType.String ||
                !ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.VERB_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.VERB_PROPERTY].Type != JTokenType.String ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.HEADERS_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.HEADERS_PROPERTY].Type != JTokenType.Object) ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.BODY_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.BODY_PROPERTY].Type != JTokenType.Object) ||
                !ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY].Type != JTokenType.Integer ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY].Type != JTokenType.Boolean) ||
                (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY) &&
                 ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY].Type != JTokenType.Array) ||
                !ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY) ||
                ParsedBody[ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY].Type != JTokenType.Integer)
            {
                return(BWebResponse.BadRequest("Request must contain all necessary fields validly. Given argument: " + ParsedBody.ToString()));
            }

            var    Body = new JObject();
            bool   bCancelRetryOnSuccess = true;
            var    CancelOnReturnCodes   = new JArray();
            string Url = (string)ParsedBody[ScheduledUrlTaskDBEntry.URL_PROPERTY];

            if (!Uri.TryCreate(Url, UriKind.Absolute, out Uri UriResult) ||
                (UriResult.Scheme != Uri.UriSchemeHttp && UriResult.Scheme != Uri.UriSchemeHttps))
            {
                return(BWebResponse.BadRequest("Given field " + ScheduledUrlTaskDBEntry.URL_PROPERTY + " is invalid. Given argument: " + ParsedBody.ToString()));
            }
            string Verb = (string)ParsedBody[ScheduledUrlTaskDBEntry.VERB_PROPERTY];

            if (Verb != "GET" && Verb != "POST" && Verb != "PUT" && Verb != "DELETE")
            {
                return(BWebResponse.BadRequest("Field " + ScheduledUrlTaskDBEntry.VERB_PROPERTY + " must be one of these: GET, POST, PUT, DELETE. Given argument: " + ParsedBody.ToString()));
            }

            JObject Headers;

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.HEADERS_PROPERTY))
            {
                Headers = (JObject)ParsedBody[ScheduledUrlTaskDBEntry.HEADERS_PROPERTY];
            }
            else
            {
                Headers = new JObject();
            }

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.BODY_PROPERTY))
            {
                if (Verb == "GET" || Verb == "DELETE")
                {
                    return(BWebResponse.BadRequest("GET/DELETE requests cannot contain field " + ScheduledUrlTaskDBEntry.BODY_PROPERTY + ", given argument: " + ParsedBody.ToString()));
                }
                Body = (JObject)ParsedBody[ScheduledUrlTaskDBEntry.BODY_PROPERTY];
            }
            else if (Verb == "POST" || Verb == "PUT")
            {
                return(BWebResponse.BadRequest("POST/PUT requests must contain field " + ScheduledUrlTaskDBEntry.BODY_PROPERTY + ", given argument: " + ParsedBody.ToString()));
            }

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY))
            {
                bCancelRetryOnSuccess = (bool)ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_RETRY_ON_SUCCESS_PROPERTY];
            }

            if (ParsedBody.ContainsKey(ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY))
            {
                CancelOnReturnCodes = (JArray)ParsedBody[ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY];
                foreach (var Item in CancelOnReturnCodes)
                {
                    if (Item.Type != JTokenType.Integer)
                    {
                        return(BWebResponse.BadRequest("All elements of " + ScheduledUrlTaskDBEntry.CANCEL_ON_RETURN_CODES_PROPERTY + " must be integer"));
                    }
                }
            }

            int RetryCount = (int)ParsedBody[ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY];

            if (RetryCount < -1)
            {
                return(BWebResponse.BadRequest("Field " + ScheduledUrlTaskDBEntry.RETRY_COUNT_PROPERTY + " must be greater than or equal to -1. Given argument: " + ParsedBody.ToString()));
            }
            int RetryInSeconds = (int)ParsedBody[ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY];

            if (RetryInSeconds < 0)
            {
                return(BWebResponse.BadRequest("Field " + ScheduledUrlTaskDBEntry.RETRY_IN_SECONDS_PROPERTY + " must be greater than or equal to 0. Given argument: " + ParsedBody.ToString()));
            }

            if (!DatabaseService.UpdateItem(
                    ScheduledUrlTaskDBEntry.DBSERVICE_SCHEDULED_URL_TASKS_TABLE(),
                    ScheduledUrlTaskDBEntry.KEY_NAME_TASK_URL,
                    new BPrimitiveType(WebUtility.UrlEncode(Url)),
                    JObject.Parse(JsonConvert.SerializeObject(new ScheduledUrlTaskDBEntry()
            {
                Url = Url,
                Verb = Verb,
                Body = Body,
                Headers = Headers,
                RetryCount = RetryCount,
                bCancelRetryOnSuccess = bCancelRetryOnSuccess,
                CancelOnReturnCodes = CancelOnReturnCodes,
                RetryInSeconds = RetryInSeconds,
                ScheduledToTime = new DateTimeOffset(DateTime.UtcNow.AddSeconds(RetryInSeconds)).ToUnixTimeSeconds()
            })),
                    out _,
                    EBReturnItemBehaviour.DoNotReturn,
                    null,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database write operation has failed."));
            }

            return(BWebResponse.StatusOK("Task has been scheduled."));
        }
Example #22
0
        public static BWebServiceResponse OnRequest(HttpListenerContext _Context, string _CallerMethod, Func <ServiceUtilities.Action, bool> _HandleAction, Action <string> _ErrorMessageAction = null)
        {
            string SerializedData = null;

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var Reader = new StreamReader(InputStream))
                {
                    var JsonMessage = Reader.ReadToEnd();
                    try
                    {
                        var Parsed = JObject.Parse(JsonMessage);
                        if (Parsed.ContainsKey("message"))
                        {
                            var MessageObject = (JObject)Parsed["message"];
                            if (MessageObject.ContainsKey("data"))
                            {
                                var EncodedData = (string)MessageObject["data"];
                                SerializedData = Encoding.UTF8.GetString(Convert.FromBase64String(EncodedData));
                            }
                        }
                        if (SerializedData == null)
                        {
                            SerializedData = JsonMessage;
                        }
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke(_CallerMethod + "->OnRequest: Conversion from Base64 to string has failed with " + e.Message + ", trace: " + e.StackTrace + ", payload is: " + JsonMessage);
                        return(BWebResponse.BadRequest("Conversion from Base64 to string has failed."));
                    }
                }
            }

            if (!Manager_PubSubService.Get().DeserializeReceivedMessage(SerializedData,
                                                                        out Actions.EAction Action,
                                                                        out string SerializedAction,
                                                                        _ErrorMessageAction))
            {
                return(BWebResponse.BadRequest("Deserialization of Pub/Sub Message has failed."));
            }

            bool bResult;

            try
            {
                bResult = _HandleAction.Invoke(Actions.DeserializeAction(Action, SerializedAction));
            }
            catch (Exception e)
            {
                return(BWebResponse.BadRequest("Deserialization to Action has failed with " + e.Message + ", trace: " + e.StackTrace));
            }

            if (bResult)
            {
                return(BWebResponse.StatusOK("Processed."));
            }

            _ErrorMessageAction?.Invoke(_CallerMethod + "->OnRequest: An error occured. Retrying.");

            //Cooldown
            Thread.Sleep(1000);

            return(BWebResponse.BadRequest("An error occurred. Retrying."));
        }
Example #23
0
        private BWebServiceResponse AddUpdateBaseRightsForUser(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            var NewBaseScopeListFromRequest = new List <AccessScope>();

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var NewScopes = JArray.Parse(ResponseReader.ReadToEnd());
                        foreach (JObject NewScope in NewScopes)
                        {
                            var ConvertedScope = JsonConvert.DeserializeObject <AccessScope>(NewScope.ToString());
                            for (int i = ConvertedScope.AccessRights.Count - 1; i >= 0; i--)
                            {
                                ConvertedScope.AccessRights[i] = ConvertedScope.AccessRights[i].ToUpper();
                                if (!AccessScopeLibrary.ACCESS_RIGHTS.Contains(ConvertedScope.AccessRights[i]))
                                {
                                    ConvertedScope.AccessRights.RemoveAt(i);
                                }
                            }

                            if (ConvertedScope.AccessRights.Count > 0)
                            {
                                ConvertedScope.AccessRights = ConvertedScope.AccessRights.Distinct().ToList();
                                NewBaseScopeListFromRequest.Add(ConvertedScope);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("User_AddListBaseRights_ForUser->AddUpdateBaseRightsForUser: Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            if (NewBaseScopeListFromRequest.Count == 0)
            {
                return(BWebResponse.BadRequest("Request does not contain any valid base scope. Access rights can be: " + AccessScopeLibrary.GetPossibleAccessRightsText()));
            }

            var UserKey = new BPrimitiveType(RequestedUserID);

            if (!DatabaseService.GetItem(
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserDBEntry.Properties,
                    out JObject UserObject,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database fetch-user-info operation has failed."));
            }
            if (UserObject == null)
            {
                return(BWebResponse.NotFound("User does not exist."));
            }

            var NewBaseAccessScopeAsJArray = new JArray();
            var NewBaseAccessScopeAsList   = new List <AccessScope>();

            bool bUpdateOccurredForUserEntry = false;

            if (UserObject.ContainsKey(UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY))
            {
                var BaseAccessScopeAsArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY];

                foreach (var NewScope in NewBaseScopeListFromRequest)
                {
                    bool bNewScopeFoundInExisting = false;

                    NewScope.AccessRights.Sort();

                    foreach (JObject ExistingScopeObject in BaseAccessScopeAsArray)
                    {
                        bool bChangeOccurredForScope = false;

                        var ExistingScope = JsonConvert.DeserializeObject <AccessScope>(ExistingScopeObject.ToString());
                        ExistingScope.AccessRights.Sort();

                        if (!bNewScopeFoundInExisting && ExistingScope.WildcardPath == NewScope.WildcardPath)
                        {
                            bNewScopeFoundInExisting = true;

                            if (NewScope.AccessRights.Count != ExistingScope.AccessRights.Count)
                            {
                                bUpdateOccurredForUserEntry = true;
                                NewBaseAccessScopeAsList.Add(NewScope);
                                NewBaseAccessScopeAsJArray.Add(JObject.Parse(JsonConvert.SerializeObject(NewScope)));
                                break;
                            }
                            else
                            {
                                bool bLocalChangeExists = false;

                                for (int i = 0; i < NewScope.AccessRights.Count; i++)
                                {
                                    if (NewScope.AccessRights[i] != ExistingScope.AccessRights[i])
                                    {
                                        bLocalChangeExists = true;
                                        break;
                                    }
                                }

                                if (bLocalChangeExists)
                                {
                                    bUpdateOccurredForUserEntry = true;
                                    bChangeOccurredForScope     = true;
                                    NewBaseAccessScopeAsList.Add(NewScope);
                                    NewBaseAccessScopeAsJArray.Add(JObject.Parse(JsonConvert.SerializeObject(NewScope)));
                                }
                            }
                        }

                        if (!bChangeOccurredForScope)
                        {
                            NewBaseAccessScopeAsList.Add(ExistingScope);
                            NewBaseAccessScopeAsJArray.Add(ExistingScopeObject);
                        }
                    }

                    if (!bNewScopeFoundInExisting)
                    {
                        NewBaseAccessScopeAsList.Add(NewScope);
                        NewBaseAccessScopeAsJArray.Add(JObject.Parse(JsonConvert.SerializeObject(NewScope)));
                        bUpdateOccurredForUserEntry = true;
                    }
                }
            }

            if (bUpdateOccurredForUserEntry)
            {
                UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY] = NewBaseAccessScopeAsJArray;

                MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[]
                {
                    new Tuple <string, BPrimitiveType>(
                        UserBaseAccessMEntry.M_KEY_NAME_USER_ID + RequestedUserID,
                        new BPrimitiveType(JsonConvert.SerializeObject(new UserBaseAccessMEntry()
                    {
                        BaseAccessScope = NewBaseAccessScopeAsList
                    })))
                }, _ErrorMessageAction);

                Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                    _Context,
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserObject);
            }

            return(BWebResponse.StatusCreated("New base rights have been added."));
        }
Example #24
0
        private BWebServiceResponse UpdateRawFile(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            if (!CommonMethods.TryParsingRequestFor(
                    _Context,
                    out JObject UpdatedFileEntryJson,
                    true, out FileEntry CheckForGenerateUploadUrl,
                    out BWebServiceResponse FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }
            bool bGenerateUploadUrl = CheckForGenerateUploadUrl.bGenerateUploadUrl;

            if (bGenerateUploadUrl)
            {
                UpdatedFileEntryJson[FileEntry.FILE_ENTRY_FILE_TYPE_PROPERTY] = CheckForGenerateUploadUrl.FileEntryFileType.TrimStart('.').ToLower();
            }
            else
            {
                if (UpdatedFileEntryJson.ContainsKey(FileEntry.FILE_ENTRY_NAME_PROPERTY) ||
                    UpdatedFileEntryJson.ContainsKey(FileEntry.FILE_ENTRY_FILE_TYPE_PROPERTY) ||
                    UpdatedFileEntryJson.ContainsKey(FileEntry.ZIP_MAIN_ASSEMBLY_FILE_NAME_IF_ANY_PROPERTY) ||
                    UpdatedFileEntryJson.ContainsKey(FileEntry.DATA_SOURCE_PROPERTY))
                {
                    return(BWebResponse.BadRequest("Name|type related fields can only be set when " + FileEntry.GENERATE_UPLOAD_URL_PROPERTY + " option is true."));
                }
            }

            if (!CommonMethods.TryGettingAllInfo(
                    DatabaseService,
                    RequestedModelID,
                    RequestedRevisionIndex,
                    out ModelDBEntry ModelObject,
                    out Revision RevisionObject,
                    out int _,
                    out FailureResponse,
                    _ErrorMessageAction))
            {
                return(FailureResponse);
            }

            if (RevisionObject.FileEntry.FileEntryName != null && RevisionObject.FileEntry.FileEntryName.Length > 0)
            {
                if (UpdatedFileEntryJson.ContainsKey(FileEntry.FILE_ENTRY_NAME_PROPERTY) ||
                    UpdatedFileEntryJson.ContainsKey(FileEntry.FILE_ENTRY_FILE_TYPE_PROPERTY) ||
                    UpdatedFileEntryJson.ContainsKey(FileEntry.ZIP_MAIN_ASSEMBLY_FILE_NAME_IF_ANY_PROPERTY) ||
                    UpdatedFileEntryJson.ContainsKey(FileEntry.DATA_SOURCE_PROPERTY))
                {
                    return(BWebResponse.BadRequest("File entry (raw) must be deleted before updating."));
                }
            }

            RevisionObject.FileEntry.Merge(UpdatedFileEntryJson);

            RevisionObject.FileEntry.FileEntryFileType = RevisionObject.FileEntry.FileEntryFileType.ToLower().TrimStart('.');
            RevisionObject.FileEntry.SetRelativeUrls_GetCommonUrlPart_FileEntryFileTypePreSet(RequestedModelID, RequestedRevisionIndex);
            RevisionObject.FileEntry.FileEntryCreationTime = CommonMethods.GetTimeAsCreationTime();
            ModelObject.MRVLastUpdateTime = RevisionObject.FileEntry.FileEntryCreationTime;

            string UploadUrl_IfRequested = null;

            if (bGenerateUploadUrl &&

                !FileService.CreateSignedURLForUpload(
                    out UploadUrl_IfRequested,
                    CadFileStorageBucketName,
                    RevisionObject.FileEntry.RawFileRelativeUrl,
                    FileEntry.RAW_FILE_UPLOAD_CONTENT_TYPE,
                    FileEntry.EXPIRY_MINUTES,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Signed url generation has failed."));
            }

            Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                _Context,
                ModelDBEntry.DBSERVICE_MODELS_TABLE(),
                ModelDBEntry.KEY_NAME_MODEL_ID,
                new BPrimitiveType(RequestedModelID),
                JObject.Parse(JsonConvert.SerializeObject(ModelObject)));

            Controller_ModelActions.Get().BroadcastModelAction(new Action_ModelRevisionFileEntryUpdated
                                                               (
                                                                   RequestedModelID,
                                                                   RequestedRevisionIndex,
                                                                   ModelObject.ModelOwnerUserID,
                                                                   ModelObject.ModelSharedWithUserIDs,
                                                                   AuthorizedUser.UserID,
                                                                   UpdatedFileEntryJson
                                                               ),
                                                               _ErrorMessageAction);

            var ResultObject = new JObject();

            if (bGenerateUploadUrl)
            {
                ResultObject[FileEntry.FILE_UPLOAD_URL_PROPERTY]                     = UploadUrl_IfRequested;
                ResultObject[FileEntry.FILE_UPLOAD_CONTENT_TYPE_PROPERTY]            = FileEntry.RAW_FILE_UPLOAD_CONTENT_TYPE;
                ResultObject[FileEntry.FILE_DOWNLOAD_UPLOAD_EXPIRY_MINUTES_PROPERTY] = FileEntry.EXPIRY_MINUTES;
            }

            return(BWebResponse.StatusAccepted("Update raw file request has been accepted.", ResultObject));
        }
Example #25
0
        private bool Parse_FirstLeg_Authentication_Content(
            string _ResponseContent,
            out string _AuthorizationCode_From_FirstLeg,
            out BMemoryQueryParameters _SSOStateUniqueID_QueryParameters,
            out SSOStateMEntry _SSOState,
            out string _LocalRedirectUrl_From_FirstLeg,
            out string _EmailAddress_From_FirstLeg,
            out string _AzureADUniqueID_From_FirstLeg,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction)
        {
            _AuthorizationCode_From_FirstLeg  = null;
            _SSOStateUniqueID_QueryParameters = new BMemoryQueryParameters();
            _SSOState = null;
            _LocalRedirectUrl_From_FirstLeg = null;
            _EmailAddress_From_FirstLeg     = null;
            _AzureADUniqueID_From_FirstLeg  = null;
            _FailureResponse = BWebResponse.InternalError("");

            _ResponseContent = _ResponseContent.Trim();

            //Handle error
            if (_ResponseContent.StartsWith("error="))
            {
                var ErrorResponse = new JObject()
                {
                    ["result"] = "failure"
                };
                try
                {
                    var ErrorFields = _ResponseContent.Split('&');
                    if (ErrorFields != null && ErrorFields.Length >= 2)
                    {
                        ErrorResponse["error"]   = ErrorFields[0].Substring("error=".Length);
                        ErrorResponse["message"] = ErrorFields[1].Substring("error_description=".Length);
                    }
                }
                catch (Exception) { }

                _FailureResponse = BWebResponse.Unauthorized(ErrorResponse.ToString());
                return(false);
            }

            //Normal flow
            var Splitted = _ResponseContent.Split('&');

            if (Splitted == null || Splitted.Length < 3)
            {
                _FailureResponse = BWebResponse.BadRequest("Request body must contain all requested types. Split has failed.");
                return(false);
            }

            string IDToken    = null;
            string StateField = null;

            for (var i = 0; i < Splitted.Length; i++)
            {
                if (Splitted[i].StartsWith("id_token="))
                {
                    IDToken = Splitted[i].Substring("id_token=".Length);
                }
                else if (Splitted[i].StartsWith("code="))
                {
                    _AuthorizationCode_From_FirstLeg = Splitted[i].Substring("code=".Length);
                }
                else if (Splitted[i].StartsWith("state="))
                {
                    StateField = WebUtility.UrlDecode(Splitted[i].Substring("state=".Length));
                }
            }
            if (IDToken == null || _AuthorizationCode_From_FirstLeg == null || StateField == null)
            {
                _FailureResponse = BWebResponse.BadRequest("Request body must contain all requested types.");
                return(false);
            }

            Splitted = StateField.Split('&');
            if (Splitted == null || Splitted.Length < 3)
            {
                _FailureResponse = BWebResponse.BadRequest("State field must contain all mandatory entries. Split has failed.");
                return(false);
            }

            bool   bSSOStateUniqueID_QueryParameters_Set = false;
            string TenantName = null;

            for (var i = 0; i < Splitted.Length; i++)
            {
                if (Splitted[i].StartsWith("redirect_url="))
                {
                    _LocalRedirectUrl_From_FirstLeg = WebUtility.UrlDecode(Splitted[i].Substring("redirect_url=".Length));
                }
                else if (Splitted[i].StartsWith("tenant="))
                {
                    TenantName = Splitted[i].Substring("tenant=".Length);
                }
                else if (Splitted[i].StartsWith("state="))
                {
                    _SSOStateUniqueID_QueryParameters     = SSOStateMEntry.ID_SSO_STATE_MEMORY_SERVICE_KEY(Splitted[i].Substring("state=".Length));
                    bSSOStateUniqueID_QueryParameters_Set = true;
                }
            }
            if (_LocalRedirectUrl_From_FirstLeg == null || TenantName == null || !bSSOStateUniqueID_QueryParameters_Set)
            {
                _FailureResponse = BWebResponse.BadRequest("State field must contain all mandatory entries.");
                return(false);
            }

            var Serialized = MemoryService.GetKeyValue(_SSOStateUniqueID_QueryParameters, SSOStateMEntry.HASH_KEY, _ErrorMessageAction);

            if (Serialized == null)
            {
                _FailureResponse = BWebResponse.Unauthorized("Login prompt session has expired. Please try again.");
                return(false);
            }
            try
            {
                _SSOState = JsonConvert.DeserializeObject <SSOStateMEntry>(Serialized.AsString);
                if (_SSOState == null)
                {
                    throw new NullReferenceException();
                }
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("Error: SSOLoginCallback->Parse_FirstLeg_Authentication_Content: Invalid session state. Message: " + e.Message + ", trace: " + e.StackTrace);
                _FailureResponse = BWebResponse.InternalError("Invalid session state. Please try again.");
                return(false);
            }
            if (_SSOState.Status != SSOStateMEntry.STATUS_AUTHENTICATING)
            {
                _FailureResponse = BWebResponse.Unauthorized("Invalid SSO state. Please try again.");
                return(false);
            }
            if (TenantName != _SSOState.TenantName)
            {
                _FailureResponse = BWebResponse.Unauthorized("SSO state - request tenant mismatch. Please try again.");
                return(false);
            }

            var JWTHandler         = new JwtSecurityTokenHandler();
            JwtSecurityToken Token = null;

            try
            {
                Token = JWTHandler.ReadJwtToken(IDToken);
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("Error: SSOLoginCallback->Parse_FirstLeg_Authentication_Content: Invalid JWT token. Token: " + IDToken + ", message: " + e.Message + ", trace: " + e.StackTrace);
                _FailureResponse = BWebResponse.BadRequest("Invalid JWT token.");
                return(false);
            }

            if (!Token.Payload.TryGetValue("email", out object EmailObject))
            {
                _FailureResponse = BWebResponse.BadRequest("JWT token does not contain email in the payload.");
                return(false);
            }

            _EmailAddress_From_FirstLeg = ((string)EmailObject).ToLower();

            if (!Token.Payload.TryGetValue("sub", out object AzureADUserUniqueIDObject))
            {
                _FailureResponse = BWebResponse.BadRequest("JWT token does not contain sub in the payload.");
                return(false);
            }
            _AzureADUniqueID_From_FirstLeg = ((string)AzureADUserUniqueIDObject).ToLower();

            return(true);
        }
Example #26
0
        public static bool TryParsingRequestFor <T>(
            HttpListenerContext _Context,
            out JObject _SuccessResultJson,
            bool _bDeserialize, out T _SuccessResultDeserialized,
            out BWebServiceResponse _FailureResponse,
            Action <string> _ErrorMessageAction = null)
        {
            _FailureResponse           = BWebResponse.InternalError("");
            _SuccessResultDeserialized = default;
            _SuccessResultJson         = null;

            string[] MustHaveProperties;
            string[] UpdatableProperties;
            Dictionary <string, Func <JToken, bool> > UpdatablePropertiesValidityCheck;

            if (typeof(T) == typeof(ModelDBEntry))
            {
                MustHaveProperties  = ModelDBEntry.MustHaveProperties;
                UpdatableProperties = ModelDBEntry.UpdatableProperties;
                UpdatablePropertiesValidityCheck = ModelDBEntry.UpdatablePropertiesValidityCheck;
            }
            else if (typeof(T) == typeof(Revision))
            {
                MustHaveProperties  = Revision.MustHaveProperties;
                UpdatableProperties = Revision.UpdatableProperties;
                UpdatablePropertiesValidityCheck = Revision.UpdatablePropertiesValidityCheck;
            }
            else if (typeof(T) == typeof(FileEntry))
            {
                MustHaveProperties  = null;
                UpdatableProperties = FileEntry.UpdatableProperties;
                UpdatablePropertiesValidityCheck = FileEntry.UpdatablePropertiesValidityCheck;
            }
            else
            {
                throw new ArgumentException("Only ModelDBEntry and Revision are supported.");
            }

            using (var InputStream = _Context.Request.InputStream)
            {
                var NewObjectJson = new JObject();

                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());

                        var PropertiesList = new List <string>();
                        foreach (var Child in ParsedBody)
                        {
                            PropertiesList.Add(Child.Key);
                        }
                        if (MustHaveProperties != null)
                        {
                            foreach (var MustHaveProperty in MustHaveProperties)
                            {
                                if (!PropertiesList.Contains(MustHaveProperty))
                                {
                                    _FailureResponse = BWebResponse.BadRequest("Request body must contain all necessary fields.");
                                    return(false);
                                }
                            }
                        }

                        foreach (var Child in ParsedBody)
                        {
                            if (!UpdatablePropertiesValidityCheck[Child.Key](Child.Value))
                            {
                                _FailureResponse = BWebResponse.BadRequest("Given field " + Child.Key + " has invalid value.");
                                return(false);
                            }
                            if (UpdatableProperties.Contains(Child.Key))
                            {
                                NewObjectJson[Child.Key] = Child.Value;
                            }
                            else
                            {
                                _FailureResponse = BWebResponse.BadRequest("Unexpected field " + Child.Value.ToString());
                                return(false);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        _FailureResponse = BWebResponse.BadRequest("Malformed request body. Request must be a valid json form.");
                        return(false);
                    }
                }

                //For other elements to be created without any elements
                _SuccessResultJson = NewObjectJson;
                if (_bDeserialize)
                {
                    _SuccessResultDeserialized = JsonConvert.DeserializeObject <T>(NewObjectJson.ToString());
                }
            }

            return(true);
        }
Example #27
0
        private BWebServiceResponse CreateAccessMethodForUser(HttpListenerContext _Context, out bool _bSetClearanceForApiKey, out string _ApiKey, Action <string> _ErrorMessageAction)
        {
            _bSetClearanceForApiKey = false;
            _ApiKey = null;

            AuthMethod NewMethod = null;

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        NewMethod = JsonConvert.DeserializeObject <AuthMethod>(ResponseReader.ReadToEnd());
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("User_CreateListAccessMethods_ForUser->CreateAccessMethodForUser: Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            if (NewMethod == null)
            {
                return(BWebResponse.BadRequest("Request body does not contain all mandatory information or some fields are invalid."));
            }

            BPrimitiveType AuthMethodKey = null;

            if (NewMethod.Method == AuthMethod.Methods.USER_EMAIL_PASSWORD_METHOD)
            {
                if (NewMethod.UserEmail == null || NewMethod.PasswordMD5 == null || NewMethod.UserEmail.Length == 0 || NewMethod.PasswordMD5.Length == 0)
                {
                    return(BWebResponse.BadRequest("Request body does not contain all fields."));
                }
                AuthMethodKey = new BPrimitiveType(NewMethod.UserEmail + NewMethod.PasswordMD5);
            }
            else if (NewMethod.Method == AuthMethod.Methods.USER_NAME_PASSWORD_METHOD)
            {
                if (NewMethod.UserName == null || NewMethod.PasswordMD5 == null || NewMethod.UserName.Length == 0 || NewMethod.PasswordMD5.Length == 0)
                {
                    return(BWebResponse.BadRequest("Request body does not contain all fields."));
                }
                AuthMethodKey = new BPrimitiveType(NewMethod.UserName + NewMethod.PasswordMD5);
            }
            else if (NewMethod.Method == AuthMethod.Methods.API_KEY_METHOD)
            {
                int ExistenceTrial = 0;
                while (ExistenceTrial < 3)
                {
                    if (!BUtility.CalculateStringMD5(BUtility.RandomString(32, false), out NewMethod.ApiKey, _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Hashing error."));
                    }
                    NewMethod.ApiKey = NewMethod.ApiKey.ToUpper();

                    if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + NewMethod.ApiKey, _ErrorMessageAction))
                    {
                        return(BWebResponse.InternalError("Atomic operation control has failed."));
                    }

                    if (!DatabaseService.UpdateItem(
                            UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(),
                            UniqueUserFieldsDBEntry.KEY_NAME_API_KEY,
                            new BPrimitiveType(NewMethod.ApiKey),
                            new JObject()
                    {
                        [UserDBEntry.KEY_NAME_USER_ID] = RequestedUserID
                    },
                            out JObject _,
                            EBReturnItemBehaviour.DoNotReturn,
                            DatabaseService.BuildAttributeNotExistCondition(UniqueUserFieldsDBEntry.KEY_NAME_API_KEY),
                            _ErrorMessageAction))
                    {
                        Controller_AtomicDBOperation.Get().SetClearanceForDBOperationForOthers(InnerProcessor, UniqueUserFieldsDBEntry.DBSERVICE_UNIQUEUSERFIELDS_TABLE(), UniqueUserFieldsDBEntry.KEY_NAME_API_KEY + ":" + NewMethod.ApiKey, _ErrorMessageAction);
                        ExistenceTrial++;
                    }
                    else
                    {
                        _bSetClearanceForApiKey = true;
                        _ApiKey = NewMethod.ApiKey;
                        break;
                    }
                }
Example #28
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext Context, Action <string> _ErrorMessageAction = null)
        {
            if (Context.Request.HttpMethod != "POST" && Context.Request.HttpMethod != "DELETE")
            {
                _ErrorMessageAction?.Invoke("BDeleteSecretsRequest: POST/DELETE method is accepted. But received request method:  " + Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST/DELETE method is accepted. But received request method: " + Context.Request.HttpMethod));
            }

            JObject ParsedBody;

            using var InputStream    = Context.Request.InputStream;
            using var ResponseReader = new StreamReader(InputStream);
            try
            {
                ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("BDeleteSecretsRequest-> Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
            }

            if (!ParsedBody.ContainsKey("keys"))
            {
                _ErrorMessageAction?.Invoke("BDeleteSecretsRequest-> Request does not have keys field.");
                return(BWebResponse.BadRequest("Request does not have keys field."));
            }

            var ToBeDeletedKeys = (JArray)ParsedBody["keys"];

            if (ToBeDeletedKeys == null || ToBeDeletedKeys.Count == 0)
            {
                _ErrorMessageAction?.Invoke("BDeleteSecretsRequest-> Request does not have keys array or elements.");
                return(BWebResponse.BadRequest("Request does not have keys array."));
            }

            var CompletionStateStack = new ConcurrentStack <object>();

            for (int i = 0; i < ToBeDeletedKeys.Count; i++)
            {
                CompletionStateStack.Push(new object());
            }

            var WaitUntilSignal = new ManualResetEvent(false);

            var SucceedQueue = new ConcurrentQueue <string>();
            var FailedQueue  = new ConcurrentQueue <string>();

            foreach (string ToBeDeletedKey in ToBeDeletedKeys)
            {
                BTaskWrapper.Run(() =>
                {
                    if (FileService.DeleteFile(
                            SecretsStorageBucket,
                            ToBeDeletedKey,
                            (string Message) =>
                    {
                        _ErrorMessageAction?.Invoke("BDeleteSecretsRequest->Error-> " + Message);
                    }))
                    {
                        SucceedQueue.Enqueue(ToBeDeletedKey);
                    }
                    else
                    {
                        FailedQueue.Enqueue(ToBeDeletedKey);
                    }

                    CompletionStateStack.TryPop(out object Ignore);
                    if (CompletionStateStack.Count == 0)
                    {
                        try
                        {
                            WaitUntilSignal.Set();
                        }
                        catch (Exception) { }
                    }
                });
            }

            try
            {
                WaitUntilSignal.WaitOne();
                WaitUntilSignal.Close();
            }
            catch (Exception) {}

            var ResultObject = new JObject
            {
                ["succeed"] = new JArray(),
                ["failed"]  = new JArray()
            };

            while (SucceedQueue.TryDequeue(out string SucceedKey))
            {
                ((JArray)ResultObject["succeed"]).Add(SucceedKey);
            }
            while (FailedQueue.TryDequeue(out string FailedKey))
            {
                ((JArray)ResultObject["failed"]).Add(FailedKey);
            }

            return(new BWebServiceResponse(
                       BWebResponse.Status_OK_Code,
                       new BStringOrStream(ResultObject.ToString()),
                       "application/json"));
        }
Example #29
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            if (_Context.Request.HttpMethod != "POST")
            {
                _ErrorMessageAction?.Invoke("LoginRequest: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            JObject ParsedBody;

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        ParsedBody = JObject.Parse(ResponseReader.ReadToEnd());
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("LoginRequest-> Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            if (!ParsedBody.ContainsKey(AuthMethod.API_KEY_PROPERTY) &&
                ((!ParsedBody.ContainsKey(AuthMethod.USER_NAME_PROPERTY) && !ParsedBody.ContainsKey(AuthMethod.USER_EMAIL_PROPERTY)) || !ParsedBody.ContainsKey(AuthMethod.PASSWORD_MD5_PROPERTY)))
            {
                _ErrorMessageAction?.Invoke("LoginRequest-> Request does not have required fields.");
                return(BWebResponse.BadRequest("Request does not have required fields."));
            }

            string Method;

            if (ParsedBody.ContainsKey(AuthMethod.API_KEY_PROPERTY))
            {
                var ApiKey = (string)ParsedBody[AuthMethod.API_KEY_PROPERTY];
                Method = ApiKey;
            }
            else
            {
                var PasswordMD5 = ((string)ParsedBody[AuthMethod.PASSWORD_MD5_PROPERTY]).ToLower();

                if (ParsedBody.ContainsKey(UserDBEntry.USER_NAME_PROPERTY))
                {
                    Method = (string)ParsedBody[UserDBEntry.USER_NAME_PROPERTY] + PasswordMD5;
                }
                else
                {
                    Method = ((string)ParsedBody[UserDBEntry.USER_EMAIL_PROPERTY]).ToLower() + PasswordMD5;
                }
            }

            if (!AuthenticationCommon.FetchUserInfoFromMemoryService_ByMethod(MemoryService, Method, out string UserID, out string _, out string _, _ErrorMessageAction))
            {
                if (!AuthenticationCommon.FetchUserInfoFromDatabaseService_ByMethod(DatabaseService, MemoryService, Method, out UserID, out _, out _, out BWebServiceResponse FailureResponse, _ErrorMessageAction))
                {
                    return(FailureResponse);
                }
            }

            if (!BUtility.CalculateStringMD5(BUtility.RandomString(32, true), out string AccessTokenMD5, _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Hash operation failed."));
            }

            var AccessTokenMD5WithTokenType = "Basic " + AccessTokenMD5;

            var QueryParameters = new BMemoryQueryParameters()
            {
                Domain     = Resources_DeploymentManager.Get().GetDeploymentBranchNameEscapedLoweredWithDash().ToUpper(),
                SubDomain  = "SELF_SIGNED_ACCESS_TOKEN_VALIDATION",
                Identifier = AccessTokenMD5WithTokenType
            };

            MemoryService.SetKeyValue(QueryParameters, new Tuple <string, BPrimitiveType>[]
            {
                new Tuple <string, BPrimitiveType>("method", new BPrimitiveType(Method))
            },
                                      _ErrorMessageAction);

            MemoryService.SetKeyExpireTime(QueryParameters, TimeSpan.FromHours(1), _ErrorMessageAction);

            return(BWebResponse.StatusOK("Login successful.", new JObject()
            {
                ["userId"] = UserID,
                ["token"] = AccessTokenMD5WithTokenType
            }));
        }
Example #30
0
        private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            AuthorizedUser = ServiceUtilities.Common.Methods.GetAuthorizedRequester(_Context, _ErrorMessageAction);
            if (!AuthorizedUser.bParseSuccessful)
            {
                return(BWebResponse.InternalError(AuthorizedUser.ParseErrorMessage));
            }

            if (_Context.Request.HttpMethod != "GET")
            {
                _ErrorMessageAction?.Invoke("GetModelsBy_MetadataKeyValueUserPair: GET method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                return(BWebResponse.MethodNotAllowed("GET method is accepted. But received request method: " + _Context.Request.HttpMethod));
            }

            var UserID         = RestfulUrlParameters[RestfulUrlParameter_UserID];
            var MetadataKey    = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_MetadataKey]);
            var MetadataValues = WebUtility.UrlDecode(RestfulUrlParameters[RestfulUrlParameter_MetadataValues]);
            var SplittedValues = MetadataValues.Split("__DELIM__", StringSplitOptions.RemoveEmptyEntries);

            if (SplittedValues == null || SplittedValues.Length == 0)
            {
                return(BWebResponse.BadRequest("Metadata values parameter is invalid. Metadata values must be separated by __DELIM__ delimiter."));
            }

            if (!DatabaseService.GetItem(
                    AttributeKVPairUserToOwnerDBEntry.TABLE(),
                    AttributeKVPairUserToOwnerDBEntry.KEY_NAME,
                    Controller_AttributeTables.MakeKey(MetadataKey, new List <string>(SplittedValues), UserID),
                    new string[] { AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY },
                    out JObject Result,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database query has failed."));
            }

            if (Result == null || !Result.ContainsKey(AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY) || Result[AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY].Type != JTokenType.Array)
            {
                return(BWebResponse.NotFound("Entry not found."));
            }

            var AsArray = (JArray)Result[AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY];

            for (int i = 0; i < AsArray.Count; i++)
            {
                var AsStr = (string)AsArray[i];
                if (AsStr != null)
                {
                    if (AsStr.StartsWith(Controller_AttributeTables.MODEL_METADATA_PREFIX))
                    {
                        AsStr = AsStr.Substring(Controller_AttributeTables.MODEL_METADATA_PREFIX.Length);
                    }
                    else if (AsStr.StartsWith(Controller_AttributeTables.REVISION_METADATA_PREFIX))
                    {
                        AsStr = AsStr.Substring(Controller_AttributeTables.REVISION_METADATA_PREFIX.Length);
                        AsStr = AsStr.Replace(Controller_AttributeTables.REVISION_METADATA_MRV_DELIMITER, "->");
                    }

                    AsArray[i] = AsStr;
                }
            }

            return(BWebResponse.StatusOK("Model(s) have been located.", new JObject()
            {
                [AttributeKeyDBEntryBase.METADATA_LOCATOR_PROPERTY] = AsArray
            }));
        }