Beispiel #1
0
        /// <summary>
        /// Returns an instance of the <see cref="IDynamicApiAction"/> if found and <see langword="null"/> if not.
        /// </summary>
        /// <param name="request">The request object.</param>
        public IDynamicApiAction GetAction(DynamicApiRequest request)
        {
            var key = GetActionKey(request.RequestedActionPath);

            if (_actions.TryGetValue(key, out var action))
            {
                return(action);
            }
            return(null);
        }
Beispiel #2
0
        private async Task <long> InvokeAction(DynamicApiRequest request, IDynamicApiAction action, DynamicApiActionParameterValue[] parameters, object context)
        {
            var value = await action.Invoke(parameters, context);

            var res      = JsonConvert.SerializeObject(value, _jsonSerializer);
            var response = request.HttpContext.Response;

            response.Headers.Add("Content-Type", "application/json");
            await response.WriteAsync(res);

            return(Encoding.UTF8.GetByteCount(res));
        }
Beispiel #3
0
        private async Task HandleRequest(DynamicApiRequest request)
        {
            IDynamicApiAction action = _cache.GetAction(request);

            Log(request, $"Checking cache for action.");

            if (action == null)
            {
                Log(request, $"Action not found in cache.");
                Log(request, $"Looking in repository actions.");
                action = _repositoryActionLoactor.CreateRepositoryAction(_repositoryManager, request);
                if (action == null)
                {
                    throw new DynamicApiException(DynamicApiExceptionCodes.ActionNotFound, "Action not found.");
                }
                _cache.AddAction(action);
                Log(request, $"Repository action created.");
            }
            else
            {
                Log(request, $"Action found in cache.");
            }

            Log(request, $"Parsing request parameters.");
            var parameters = await _parser.ParseParameters(action, request);

            if (action.RequiresAuthorization)
            {
                if (!_authorizationValidator.IsAuthorized(action, request))
                {
                    throw new DynamicApiException(DynamicApiExceptionCodes.Unauthorized, "Unauthorized client.");
                }
            }

            Log(request, $"Invoking action.");

            object context = null;

            if (_configurations.GetApiContext != null)
            {
                context = _configurations.GetApiContext(request);
            }

            var resLength = await InvokeAction(request, action, parameters, context);

            Log(request, $"Response completed in {(DateTime.Now - request.Date).Milliseconds} ms, content size:{SizeToString(resLength)}");
        }
        /// <inheritdoc />
        public bool IsAuthorized(IDynamicApiAction action, DynamicApiRequest request)
        {
            var user = request.HttpContext.User;

            if (user.Identity.IsAuthenticated)
            {
                if (string.IsNullOrEmpty(action.AuthorizeAttribute.Claim))
                {
                    return(true);
                }
                if (user.HasClaim(e => e.Type.Equals(action.AuthorizeAttribute.Claim)))
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #5
0
        private async Task HandleException(DynamicApiRequest request, Exception exception)
        {
            Log(request, exception);
            var statusCode = request.HttpContext.Response.StatusCode = GetExceptionStatusCode(exception);

            request.HttpContext.Response.Headers.Add(HttpHeaders.XCoddeeException, exception.GetType().AssemblyQualifiedName);
            if (_configurations.UseErrorPages)
            {
                string content = null;
                if (_configurations.ErrorPagesConfiguration.DisplayExceptionDetails)
                {
                    content = exception.BuildExceptionString(debuginfo: true);
                }
                string page = _pagesProvider.GetErrorPage(statusCode, content);
                await request.HttpContext.Response.WriteAsync(page);
            }
            else if (_configurations.ReturnException)
            {
                await request.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(exception, _jsonSerializer));
            }
        }
Beispiel #6
0
 private void Log(DynamicApiRequest request, Exception exception)
 {
     Log(request, exception.BuildExceptionString(0, true), LogRecordTypes.Error);
 }
Beispiel #7
0
 private void Log(DynamicApiRequest request, string content, LogRecordTypes logType = LogRecordTypes.Information)
 {
     Log($"[Request Id:{request.Id}] {content}", logType);
 }
Beispiel #8
0
        /// <summary>
        /// Parse request parameters.
        /// </summary>
        public async Task <DynamicApiActionParameterValue[]> ParseParameters(IDynamicApiAction action, DynamicApiRequest request)
        {
            var parameters  = new DynamicApiActionParameterValue[action.Parameters.Count];
            var httpRequest = request.HttpContext.Request;


            for (int i = 0; i < action.Parameters.Count; i++)
            {
                var  actionParameter = action.Parameters[i];
                bool found           = false;
                if (HttpMethod.IsGet(httpRequest.Method) || HttpMethod.IsDelete(httpRequest.Method))
                {
                    if (httpRequest.Query.ContainsKey(actionParameter.Name))
                    {
                        var value      = ParseGetValue(actionParameter, httpRequest.Query[actionParameter.Name]);
                        var paramValue = new DynamicApiActionParameterValue
                        {
                            Parameter = actionParameter,
                            Value     = value
                        };
                        parameters[i] = paramValue;
                        found         = true;
                    }
                }
                else
                {
                    string content;
                    using (var sr = new StreamReader(httpRequest.Body))
                    {
                        content = await sr.ReadToEndAsync();
                    }
                    var value      = ParsePostValue(actionParameter, content);
                    var paramValue = new DynamicApiActionParameterValue
                    {
                        Parameter = actionParameter,
                        Value     = value
                    };
                    parameters[i] = paramValue;
                    found         = true;
                }

                if (!found)
                {
                    throw new DynamicApiException(DynamicApiExceptionCodes.MissingParameter, $"Parameter ({actionParameter.Name}) is missing.");
                }
            }



            return(parameters);
        }
        /// <summary>
        /// Creates an <see cref="IDynamicApiAction"/> for a repository action.
        /// </summary>
        public IDynamicApiAction CreateRepositoryAction(IRepositoryManager repositoryManager, DynamicApiRequest request)
        {
            if (repositoryManager == null)
            {
                return(null);
            }

            var repositoryName = request.RequestedActionPath.RequestedController;
            var repository     = repositoryManager.GetRepository(repositoryName);

            if (repository == null)
            {
                return(null);
            }

            var actionName = request.RequestedActionPath.RequestedAction;

            if (actionName == "getitem")
            {
                actionName = "get_item";
            }

            var method = repository
                         .GetType()
                         .GetMethods()
                         .FirstOrDefault(e => e.Name.Equals(actionName, StringComparison.InvariantCultureIgnoreCase));

            var interfaceMethod = GetInterfaceMethod(repository, actionName);

            if (method == null || interfaceMethod == null)
            {
                return(null);
            }
            DynamicApiRepositoryAction action = CreateAction(repositoryManager, repositoryName, actionName, method, interfaceMethod);

            return(action);
        }