How to update filter in odata backend for aurelia slickgrid - slickgrid

This has no effect on backend call request. Any idea why and how to make a new odata request with added filter query.
public setFilter(filter: string) {
console.log("set filter ", filter);
this.filterValue = filter;
const odataService = this.gridOptions.backendServiceApi.service;
console.log("filterValue ", this.filterValue);
odataService.updateOptions({ filter: this.filterValue } as OdataOption);
console.log("odataService update ", odataService);
odataService.processOnFilterChanged
odataService.clearFilters();
this.aureliaGridObj.filterService.clearFilters();
return true;
}

Related

PayPal v2 Orders API - difference between OrdersGetRequest and OrdersCaptureRequest

I'm using checkout-sdk with angular and spring boot. Here is the code I have on the angular side
paypal
.Buttons({
style: {
color: 'blue',
shape: 'pill',
label: 'pay',
height: 40
},
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [
{
description: 'Order id: '+this.order.id,
amount: {
currency_code: 'EUR',
value: this.order.totalPrice
}
}
]
});
},
onApprove: async (data, actions) => {
const order = await actions.order.capture();
this.paidFor = true;
this.checkoutPaypal(this.id,order.id)
},
onError: err => {
}
})
.render(this.paypalElement.nativeElement);
This is function used to retrieve payment, and save details to database..
public String checkoutPaypal(Integer id, String orderId) {
OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
request.requestBody(buildRequestBody());
HttpResponse<com.paypal.orders.Order> response;
try {
response = payPalClient.client().execute(request);
} catch (IOException e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
}
for (PurchaseUnit purchaseUnit : response.result().purchaseUnits()) {
purchaseUnit.amountWithBreakdown();
for (Capture capture : purchaseUnit.payments().captures()) {
if (capture.status().equals("COMPLETED")) {
Order order = orderRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found!"));
order.setOrderState(OrderState.PAID);
order.setPaymentDetails("Charge id: " + capture.id() + "; Status: " + capture.status() + "; Time paid: " + capture.createTime() + " GMT");
order.addOrderStateChange(OrderState.PAID, false);
sendEmail(order, " paid successfully!", "Thanks for your purchase!<br>We will work as hard as we can, to deliver the order to you, as soon as possible!");
orderRepository.save(order);
}
}
}
return "Successfully paid!";
}
Which worked few days ago.. But now I'm getting this error
{"name":"UNPROCESSABLE_ENTITY","details":[{"issue":"ORDER_ALREADY_CAPTURED","description":"Order already captured.If 'intent=CAPTURE' only one capture per order is allowed."}],"message":"The requested action could not be performed, semantically incorrect, or failed business validation.","debug_id":"f058cb447ccbb","links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-ORDER_ALREADY_CAPTURED","rel":"information_link","method":"GET"}]}
But after replacing
OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
request.requestBody(buildRequestBody());
HttpResponse<com.paypal.orders.Order> response;
with
OrdersGetRequest request = new OrdersGetRequest(orderId);
HttpResponse<com.paypal.orders.Order> response;
It works as it should.
So my question is, what is the difference between
https://developer.paypal.com/docs/checkout/reference/server-integration/capture-transaction/
and
https://developer.paypal.com/docs/checkout/reference/server-integration/get-transaction/ ?
One is to get the status of the order, the other is to capture the order.
Capturing should not be done once you have called actions.order.capture() on the client side, and will always return an error in such a case. It may also also return an error when the order has been created on the client side (actions.order.create())
A correct server-based integration uses neither actions.order.create() nor actions.order.capture() on the client side. It is very important not to do so, as transactions will be created without your server receiving any immediate direct response from PayPal.
Instead, create two routes on your server, one for 'Create Order' and one for 'Capture Order' as documented here. These routes should return JSON data. Before returning data, the capture route should check for success and act accordingly to send an email or whatever other business operation you need.
The approval flow to pair with the above two routes is https://developer.paypal.com/demo/checkout/#/pattern/server

Secure Web API Post Method with Username and Password

I have a Web API service hosted in Microsoft Azure. I need a certain POST method to be only accessible with one unique username and password.
I understand the [Authorize] method does a token based authentication but its not tied to a single username and password. In my app, the web api also does the login authentication, so anyone who registers can access this post method if im not mistaken. (Please correct me if im wrong)
I am new to this could you guide me the right way please.
This is my WebAPI Post method i want to secure access to with specific unique username&pass:
[AllowAnonymous]
[HttpPost, Route("send")]
public async Task<NotificationOutcome> Post([FromBody]string message)
{
string hubName = "myHub";
string hubNameDefaultShared = "myHubNameDefaultShared";
NotificationHubClient hub = NotificationHubClient
.CreateClientFromConnectionString(hubNameDefaultShared, hubName, enableTestSend: true);
string installationId = string.Empty;
var templateParams = new Dictionary<string, string>
{
["messageParam"] = message
};
NotificationOutcome result = null;
if (string.IsNullOrWhiteSpace(installationId))
{
result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
}
else
{
result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
}
return result;
}
And this is how I currently access the POST Method:
var client = new RestClient("myWebApiRouteName");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "46c23eba-8ca6-4ede-b4fe-161473dc063a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", messageBody, ParameterType.RequestBody);
try
{
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

How to Disable zuul filter for specific condition case and not sending to mapped URL

I have zuul filter implementation with route config
related:
path: /api/search/related/**
url: http://abc.xyz.neverhit.this.URl
and run implementation
#Override
public Object run() {
RequestContext context = getCurrentContext();
HttpServletRequest request = context.getRequest();
UriComponents uri = UriComponentsBuilder.fromHttpUrl(recommendationsServiceHostname)
.path("/recommendations/related")
.query(request.getQueryString()).build();
if (shouldRouteToRecommendationsService(request, uri)) {
logger.info("Calling proxy service");
try {
context.setRouteHost(new URL(uri.toString()));
} catch (MalformedURLException ex) {
logger.error("MalformedURLException for URL:" + uri.toString());
}
}
else
{
//Something here or Solution that should handle a request like a filter is not present.
}
return null;
}
Its working fine for if part and sending the request to proxy service. Problem is for else part.
What I am looking for is in else scenario it should behave like filter never existed and it should handle request it was handling early executing API call from local code.
Any hack or proper solution for this one ?

How to pass custom headers while calling a web api using Swagger(Swashbuckle)

We are using Swashbuckle to document our web apis and use it to test our web apis. I want to know how one can pass multiple custom headers with different values for each request using Swagger UI.
I have seen an answer like below in the internet to pass a header in Swagger UI but was unable to get my head around it. What's confusing is about the SwaggerExtensions file. What is the purpose of this file and why is there a mention of this file in the qualified name of the js file.
1.Add new file named “SwaggerExtensions”, then added new JS file named “onComplete.js”, you have to change the build action for this file to “Embedded Resource”.
2.Inside the file “onComplete.js” paste the following code:
$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
if (key && key.trim() != "") {
key = "Bearer " + key;
window.authorizations.add("key", new ApiKeyAuthorization("Authorization", key, "header"));
}
});
3.Open file “SwaggerConfig.cs” and inside the register method paste the code below:
SwaggerUiConfig.Customize(c =>
{
c.SupportHeaderParams = true;
c.InjectJavaScript(typeof(SwaggerConfig).Assembly, "AngularJSAuthentication.API.SwaggerExtensions.onComplete.js");
});
Swashbuckles implementation of swagger reads XML code comments to generate the required swagger specification. Unfortunately, if you require an authorization header (access token) to make requests, the XML code comments does not provide this info to Swashbuckle. You'll have to manually inject this new parameter during swagger specification generation.
Swashbuckle provides an interface called IOperationFilter to apply new parameters. Implementing this interface will look something like this.
public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline
.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter {
name = "Authorization",
#in = "header",
description = "access token",
required = true,
type = "string"
});
}
}
}
Inside your SwaggerConfig.cs file, add the following
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
c.SingleApiVersion("v1", "API").Description("An API ")
.TermsOfService("Some terms")
.Contact(cc => cc.Name("Team")
.Email("team#team.com"));
c.OperationFilter(() => new AuthorizationHeaderParameterOperationFilter()));
}
}
Swashbuckle suggest to use InjectJavaScript to accomplish this.
https://github.com/domaindrivendev/Swashbuckle#injectjavascript
I use the following code to add a bearer token for authorization in http header.
httpConfiguration
.EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) co
.EnableSwaggerUi(c =>
{
c.InjectJavaScript(containingAssembly, "ProjectName.SwaggerUIEnableBearerToken.js");
});
SwaggerUIEnableBearerToken.js
$(function () {
$('#input_apiKey').attr("placeholder", "bearer token");
$('#input_apiKey').off();
$('#input_apiKey').change(function () {
var token = this.value;
if (token && token.trim() !== '') {
token = 'Bearer ' + token;
var apiKeyAuth = new window.SwaggerClient.ApiKeyAuthorization("Authorization", token, "header");
window.swaggerUi.api.clientAuthorizations.add("token", apiKeyAuth);
}
}
});
})();
See more from this issue thread:
https://github.com/domaindrivendev/Swashbuckle/issues/222
You can add a parameter with SwaggerUI :
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("api_key", key, "header"));
I have stumbled across this question when trying to add a custom header containing some authentication information. This article suggests a way to accomplish this without injecting JavaScript (pure .NET approach) by providing a SecurityDefinition when configuring swagger integration:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1.0", new Info { Title = "Main API v1.0", Version = "v1.0" });
// Swagger 2.+ support
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
};
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(security);
});
This always to define a security token at API level or method level (some sort of log in) and this token will be used for all subsequent requests until logged out.

Passing and verifying the OWIN Bearer token in Query String in WebAPI

Short Version:
I need to pass and verify the OWIN bearing token as a query parameter rather than in the request header.
How do I then get the method to authorized based on that token string?
Background:
I want to call a webapi method to download a file as a stream (and never want the user to download it from a known file location).
I can't get this to work if I also need to set a custom Request header i.e. the bearer token.
I should be able to pass the token in the query string - but don't know how to get that token to then authenticate the user.
Do I need to filter? Do I need a special claim etc?
Does the webapi method need to include "access_token" as one of the function parameters?
For completeness, here's another neat solution.
Extract:
app.Use(async (context, next) =>
{
if (context.Request.QueryString.HasValue)
{
if (string.IsNullOrWhiteSpace(context.Request.Headers.Get("Authorization")))
{
var queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value);
string token = queryString.Get("access_token");
if (!string.IsNullOrWhiteSpace(token))
{
context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
}
}
}
await next.Invoke();
});
I wrote about how that works here:
http://leastprivilege.com/2013/10/31/retrieving-bearer-tokens-from-alternative-locations-in-katanaowin/
or do it like this
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = IdentityConfig.Authority,
RequiredScopes = new[] { "api" },
TokenProvider = new OAuthBearerAuthenticationProvider
{
OnRequestToken = ctx =>
{
if (String.IsNullOrWhiteSpace(ctx.Token) && ctx.Request.QueryString.HasValue)
{
NameValueCollection parsedQuery = HttpUtility.ParseQueryString(ctx.Request.QueryString.Value);
ctx.Token = parsedQuery["access_token"];
}
return Task.FromResult(0);
}
}
});

Resources