Retrieve url param value from strapi - strapi

How do I get the parameters value passed in the url? For example, my url is /forgot-password?email=testing#example.com&token=fb49d692186dd4744af50446fad2f031
I want to get the value of email and token. All I found from the doc is only about the segment as parameters value which set from route as /user/:id which is different usage for my case.

Strapi uses koa.
Therefor you can just use ctx.request.query.
Inside your handler:
async test(ctx) {
let queryObj = ctx.request.query
//use them...
}
For your stated request the object will contain:
{
email: 'testing#example.com',
token: 'fb49d692186dd4744af50446fad2f031'
}

Related

Can I get the model or model name from a strapi request context?

I am building a policy in a Strapi instance. I want it to be a global policy that I can apply anywhere in the app, but I'll need to evaluate the model specific to the endpoint being requested. For example if I put this policy on a "restaurants" endpoint, I want to be able to make a query on the "restaurant" model.
The request of course would be something to the effect of "POST /restaurants/1234" And I know I could do a string split on the forward slash and drop the "s" from the end of restaurants. But I want to know is there a better supported way of converting the restaurants url into the actual serviceable model name?
I solved it by parsing the route handler. Not sure if this is a cleaner way.
module.exports = async (ctx, config, { strapi }) => {
let handler = ctx.state.route.handler;
let modelName = handler.substring(0, handler.lastIndexOf("."));
const entities = await strapi.db.query(modelName).findMany({
where: {
owner: ctx.state.user.id,
},
});
};

axios get passing parameter to laravel route

I am trying to pass an id through axios.get in vue.js to laravel route.
my axios code plus parameter are as following,
axios.get('http://localhost/laravel_back/public/api/bpaper',{
params: {
id:12
}
and my laravel route is as follows,
Route::get('bpaper/{id}', function($id)
{
return 'Paper '.$id;
});
when executing this code i get a 404 error on my browser console. and the request url is,
Request URL:http://localhost/laravel_back/public/api/bpaper?id=12
I have already given the access-control allow methods to allow communication through axios. And the code runs when not providing a parameter. any one know a fix.
Considerind server-side is Route::get('bpaper/{id}', function($id) { ..., the id is part of the path, not a parameter. Add it to the URL. Do:
var myId = 12;
axios.get('http://localhost/laravel_back/public/api/bpaper/' + myId)
Added it to a myId variable for clarity, you don't have to do it. Using:
axios.get('http://localhost/laravel_back/public/api/bpaper/12')
would work just as well.
Also, if you have access to newer versions of JavaScript, you can profit from template strings:
var myId = 12;
axios.get(`http://localhost/laravel_back/public/api/bpaper/${myId}`)

Sending array of string from postman client

I am using web api with identity 2.0.
I want to assign multiple roles to a user.
I am using post man client to communicate with web api.
In api the method i used to get user id and roles for the user is given below:
public async Task<IHttpActionResult> AddRoleToUser(string userid,[FromUri] string[] selectedRoles)
Here selectedRoles is an array.
From postman client i am passing array as given below :
I am passing user id in the url.
Am i passing the array of roles in correct format from postman client?
The call to api was success ,but selectedRoles always contains null value.
I tried with raw json as given below,but it did not worked
If i can pass the roles as raw json,can any show an example
First problem: you're specifying that selectedRoles array comes from the URI (URL) with this attribute: [FromUri]. You need to remove this attribute, because you're sending it in the request body, not in the URL.
Web API actions can only receive a single parameter from the request body, and any number of parameters from the URL. So you need to pass the userid parameter as a query string parameter, like this ?userid=123123, and the other parameter in the body. (You could also create a route that includes a userid, or receive the userid as the id parameter and pass it as an URL segment, if you're using the deafult route)
You also need to specify in your headers the format of the information you're sending in the body. So you need to include this header: Content-Type: application/json, because you're including JSON in your request body.
Finally, as you're sending a single parameter from the body, you can send it like this:
['Admin', 'Employee']
If you want to use the format in your example, you shuould create a class to use as parameter in your action, that would look like this:
public class RoleList
{
public string[] selectedRoles { get; set; }
}
And your action should include this as parameter:
public async Task<IHttpActionResult>
AddRoleToUser(string userid, RoleList roleList)
method code in C#:
public void Put([FromBody]string[] selectedRoles)
{
foreach (var role in selectedRoles)
{
}
}
to call method in postman
in heading tab add your parameter and Content-type parameter with value application/x-www-form-urlencoded
in body tab select raw and JSON(application/json)
then in body box add your array like below:
['Admin', 'Employee']

Pass URL containing a query string as a parameter ASP.Net Web API GET?

I'm trying to pass in an URL as a string parameter to a WEB API GET method.
The controller:
public class LinksController : ApiController
{
public HttpResponseMessage Get(string targetUrl)
{
//query db with targetURL
}
}
The aim is to query the database to see if the URL is stored. This works fine with simple URLs and URLs whose query string contains a single parameter, like:
http://www.youtube.com/watch?v=nLPE4vhSBx4
The problem I'm encountering is specifically when the query string contains multiple parameters, e.g.
http://www.youtube.com/watch?v=nLPE4vhSBx4&feature=youtube_gdata
When debugging, the value of targetUrl is only ".../watch?v=nLPE4vhSBx4" which means &feature=youtube_gdata is lost.
The GET request looks like this:
http://localhost:58056/api/links?targetUrl=http://www.youtube.com/watch? v=nLPE4vhSBx4&feature=youtube_gdata
I've also tried to add the following route in WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "Links",
routeTemplate: "api/links/{targetUrl}",
defaults: new { controller = "Links", targetUrl= RouteParameter.Optional }
);
But the GET request then results in 400 Bad Request.
So my question is, can't this be done? I would like the complete URL! Or would I need to change the method header to use the [FromBody] attribute and pass it as a JSON object?
You should URLEncode your target URL parameter so that it doesn't get mistaken for subsequent query string parameter. This means the URL you specified should appear as:
http://localhost:58056/api/links?targetUrl=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnLPE4vhSBx4%26feature%3Dyoutube_gdata
And then inside your Get method, URLDecode the string that is passed as a parameter.
Both methods can be found in System.Web.HttpUtility

On Asp.net Web Api authorization filters, how can I access to parameters?

I'am starting with Asp.Net Web API and here's my problem :
I implement a custom authorization filter to inspect my message header looking for an API Key. Based on this API Key, I retrieve my user and then I would like to see if he can have access to some resources. The resources ID I want to check is on the parameters of the HTTP request. But when I'am on the AuthorizationFilter method, the actions parameters list is empty.
How can I do that ?
If I used an ActionFilter in replacement of an authorization filter, how can I be sure that this will be the first filter executed ? And globally, how can I specify the executing order of filters ?
Last question, is it possible to add some data "on the pipe" that I could retrieve on any filter ? Something like a session store but limited to the request ?
Thanks for any response
The authorization attributes run before parameter binding has run therefore you cannot (as you have seen) use the ActionArguments collection. Instead you will need to use the request uri for query parameters and route data for uri parameters as demonstrated below.
//request at http://localhost/api/foo/id?MyValue=1
public class MyAuthorizationAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
//will not work as parameter binding has not yet run
object value;
actionContext.ActionArguments.TryGetValue("id", out value);
//Will get you the resource id assuming a default route like /api/foo/{id}
var routeData = actionContext.Request.GetRouteData();
var myId = routeData.Values["id"] as string;
//uri is still accessible so use this to get query params
var queryString = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
var myQueryParam = queryString["MyValue"];
//and so on
}
}
About the execution order:
There are 3 different ways of specifying the execution order of filters using the FilterScope Enumeration... scope being Global, Controller and Action. The AuthoriseAttribute is "Global" and therefore it
Specifies an action before Controller.
If you needed to specify the execution order within these 3 scopes then you should read this blog article here where you will need to implement a FilterProvider
To add some data to the pipe:
Use the properties collection on the request this collection is available for the duration of the request.
protected override bool IsAuthorized(HttpActionContext actionContext)
{
actionContext.Request.Properties.Add("__MYKEY__","MyValue");
//access this later in the controller or other action filters using
var value = actionContext.Request.Properties["__MYKEY__"];
}
Another alternative to get to the parameters is to Execute the binding for the parameters.
try
{
var binding = actionContext.ActionDescriptor.ActionBinding;
var parameters = binding.ParameterBindings.OfType<ModelBinderParameterBinding>();
var newBinding = new HttpActionBinding(actionContext.ActionDescriptor, parameters.ToArray());
newBinding.ExecuteBindingAsync(actionContext, new CancellationToken());
var id = actionContext.ActionArguments["id"] as string;
}
catch
{
base.HandleUnauthorizedRequest(actionContext);
}
Note: You need to make sure you only filter on the parameters that will come from the Request URI, as I have noticed that executing the binding for any parameters that are expected to come from the Request body will no longer be passed on to the actual action. i.e. those parameters will be null.
This is just to note that you can do this, I'd recommend using GetRouteData()/RouteData as it is not likely to disrupt the further flow of ASP.NET MVC modelbinding.
var routeData = actionContext.ControllerContext.RouteData;
var id = routeData.Values["id"] as string;

Resources