Proper way to redirect to a different page in Hybris - sap-commerce-cloud

what is the proper way to redirect to a different page in Hybris?I have been the following approach quite a lot:
link
But some people emphasized that it is better to redirect using a separate method and using redirect:
What is the correct way?

Let me first tell you basic difference between request Redirect Vs Forward.
Redirect: Server sends a header (in response) back to the browser/client, which contain redirect URL, then browser initiates a new request to redirect URL.
When can we use Redirect?
Usually, when data is posted to the server, we should redirect to get method(URL) to prevent data resubmission on browser refreshed(F5).
return "redirect:/redirectToGeturl";
Forward: Within the server, control can be forwarded to target resource(URL). Which is done by container internally so browser/client is not aware of it.
When can we use forward?
Sometimes, we want to show different page/resource in response without changing original URL, then we forward request to other controller internally.
return "forward:/404";
What is the proper way to redirect to a different page in Hybris?
public static final String REDIRECT_PREFIX = "redirect:";
public static final String FORWARD_PREFIX = "forward:";
This class level constants are defined in AbstractController. You can use that by extending your controller to AbstractPageController or AbstractController.
return REDIRECT_PREFIX + "/redirecturl";
return FORWARD_PREFIX + "/404";
< a href="< c:url value="/path" />">link< /a >
This is the correct way to declare a link on client/browser side, which sends GET request to /path once the user clicks it.
Find detail post here

Related

Redirection to incorrect page

I am trying to redirect using a button on a custom control (code below). the following is written to the debug toolbar which is where I want to go:
destBack=https://www.example.com/MyAttachments . But I instead get a Error 404 page and the following line appears on the server console:
HTTP Web Server: Item Not Found Exception [/site/home.nsf/https:/www.example.com/MyAttachments.xsp] Anonymous
I do have a reditection rule as follows:
Description: MyAttachmentsView
Type of rule: Redirection
Incoming URL pattern: */MyAttachments
Redirect to this URL: /site/home.nsf/MyProfileAttachmentsView.xsp
Send 301 Redirect:
If I copy and paste the destBack URL I get where I want to go.
My SSJS code behind the button is as follows
importPackage(com.example);
var destination = configBean.getValue("HostURL")+"MyAttachments";
dBar.info("destBack="+destination)
context.redirectToPage(destination)
Try this code to redirect
externalCtx = facesContext.getExternalContext();
externalCtx.redirect("http://www.tlcc.com");
See http://linqed.eu/2011/07/27/xpages-server-vs-client-side-redirects/
context.redirectToPage is designed to redirect the XPages runtime to an XPage within the current database. That's why the URL in the error message contains "/site/home.nsf/" (the current database path) and "https:/www.example.com/MyAttachments.xsp" (the URL you're defining).
If you want to change the whole URL, you need to change the URL client-side, not server-side, e.g. with location.href="...."

Rails 4 path traversal possible?

The app I'm working on has a controller that issues templates to the front end (single page app). It's very basic, and simply consists of
#path = params[:path]
render template: "templates/#{#path}", layout: nil
Here my concern however is the direct use of the users input. Everything about this to me feels like it can be attacked with something as simple as path traversal. The route for this is
get "/templates/:path.html" => "templates#file", constraints: { path: /.+/ }, defaults: { format: 'html' }
I've tried multiple things to attempt a path traversal attack, such as
request /templates/path/to/../somewhere/else.html
request /templates?path=/path/to/../../something.rb
request /templates/index.html?path=/path/to/../../config/something.html
request /templates/path/../../../file.html
Fortunately, I haven't had any success with this. The requests that just start with /templates and don't specify anything after it, don't match the route thanks to the constraint so that is good.
It seems as though when that route is matched, rails doesn't allow you to override the path parameter through a url parameter, so I don't seem to be able to inject it there.
The ones that interest are the first and last examples above, where rails seems to internally be changing the requested URL before invoking the routes file. When I request /templates/path/to/../somewhere/else.html, my console output shows a request for /templates/path/somewhere/else.html. When I make a request for /templates/path/../../../file.html, the log shows a request for /file.html.
Am I missing something somewhere that will leave the app open to security issues, or is this just rails being sensible and protecting itself for me?
UPDATE
I've done some more digging, and if I try doing some URL encoding then I can cause the server to simply not respond at all. If I request /templates/%2e%2e%2f%2e%2e%2f%2e%2e%2ffresult.html then I just get an empty response with a connection: close header.
I assume that the parameter parser higher up in the rack is checking all urls for this type of attack? Regardless, my original question still stands. Am I missing something here?

Routes in Codeigniter

I want to have a clean URL in CodeIgniter based application for User's Profile Information.
Please Take a look at URL formats below.
Actual URL : http://www.mydomain.com/index.php/users/profile/user1
I'm expecting users to have Personal URL's like
http://www.mydomain.com/user1
http://www.mydomain.com/user2
http://www.mydomain.com/user3
URL http://www.mydomain.com/user1 should process http://www.mydomain.com/index.php/users/profile/user1 in background execution.
I will be removing index.php from URL using Route library.
Thanks in advance for any sort of help.
Have a look at https://www.codeigniter.com/user_guide/general/routing.html.
$route['user(:num)'] = "users/profile/user/$1";
If you mean you want /anyusername to route to the users controller, you would have to put:
$route['(:any)'] = "users/profile/$1";
At the bottom of routes.php and every non user-URL above it. Otherwise every URL would be routed there, obviously. You will need to implement some mechanism in the users-controller to throw 404-errors, since you are routing all requests not catched in the routing rules above.
IN config/routes.php
add this line
$route['user(:num)'] = "users/profile/$1";

Is it possible to rewrite url (with extra parameters) with a Chrome extension

I am trying to append few extra parameters to the url that user typed (before the page gets loaded). Is it possible to do?
For example, if user types www.google.com, I would like to append ?q=query to url (final: www.google.com?q=query.
Thanks
The webRequest API might be what you need. This code goes in your background page:
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if( details.url == "http://www.google.com/" )
return {redirectUrl: "http://www.google.com/?q=defaultquery" };
},
{urls: ["http://www.google.com/*"]},
["blocking"]);
This is an extremely specific rule that redirects visits to http://www.google.com/ with http://www.google.com/?q=defaultquery, but I think you can see how to expand it to include more functionality.
Note that this will reroute all attempts to reach http://www.google.com/, including Ajax requests and iframes.
Per the documentation, you will need to add the webRequest and webRequestBlocking permissions, along with host permissions for every host you plan to intercept:
"permissions": [
"webRequest",
"webRequestBlocking",
"*://*.google.com/",
...
],
This is an old question still I am answering it for future readers.
Modification of query parameters is a little tricky because you can endup in an infinite loop and Chrome/Firefox may detect it and process whatever is the current state of the request URL.
I have faced this situation in my chrome extension Requestly where Users used Replace Rule and replaced www.google.com with www.google.com?q=query or did something similar.
The problem with this approach is browsers intercept the request URL after adding query parameter so the parameter will be added multiple times and corrupt the URL. So you have to ensure either of the following:-
Do not intercept a request once it has been redirected.
Check if the parameter already exists, then do not redirect it.
As correctly pointed out by #apsillers in his answer, you have to use webRequest API to perform any modifications to the URL. Please have a look at his answer
and write your code accordingly.
Just in case, you are looking for an already available solution, consider trying Requestly's Query Parameter Rule. Here is a screenshot of how it looks like:-
For Firefox, you can download Requestly from its home page.

Best practice: How to track outbound links?

How do you track outbound links for your web site, since the request is logged on the destination server, not yours?
You can add a quick JQuery script to the page that will track external links and can either redirect them to a file on your server that will track the link and then forward to it, or add an ajax request that will submit on click for external links, and track them that way.
See:
http://www.prodevtips.com/2008/08/19/tracking-clicks-with-jquery-and-google-analytics/
https://web.archive.org/web/20090214024330/http://www.justskins.com/development/how-to-track-clicks-on-outgoing-links/132
Method #1: target="_blank", onclick and Google Analytics Events
Format your outgoing links with the following attributes:
outgoing
Define a javascript tracking function (requires google analytics to be loaded already):
function trackOutgoing(el) {
ga('send', 'event', {eventCategory: 'outbound',
eventAction: 'send',
eventLabel: el.getAttribute('href'),
eventValue: 1});
};
Pros:
Does NOT interfere with normal link behavior
Does NOT require redirecting to another url
Cons:
The onclick is not guaranteed to execute (user or browser could terminate the main window)
Method #2: Redirecting with Javascript and Google Analytics Callbacks
Format your outgoing links with the following attributes:
outgoing
Define a javascript tracking function (requires google analytics to be loaded already):
function trackOutgoingAndRedirect(el) {
var url = el.getAttribute('href');
ga('send', 'event', {eventCategory: 'outbound',
eventAction: 'send',
eventLabel: url,
eventValue: 1,
hitCallback: function() { document.location = url; }});
}
Pros:
Does not require target="_blank"
Higher chance of your event being registered with Google Analytics (compared to Method #1)
Cons:
Overrides the default behavior of links with return false;
Cannot open outgoing links in a new window
Method #3: Using a Redirect URL
Format your outgoing links with the following attributes:
outgoing
On your site you will need to implement a redirect script which is beyond the scope of this answer.
Your redirect script would most likely track the outgoing link and then redirect to the provided url.
Pros:
No Javascript required
Does NOT require Google Analytics
Does NOT interfere with the normal link behavior
Cons:
Harder to trigger Google Analytics Events
Links do not link to their original URL. Which may have negative SEO implications.
Add an onclick or onmousedown handler to the anchor tag. You can see many sites doing this, such as Google.
I don't like the redirect as described by Eric Tuttleman, as you unfortunately lose the 'search engine friendliness' of the link.
I handle this on a site I own by adding an onClick to my outgoing links, which fires a function which sends the link URL and a timestamp to my database. I then wrote a backend which retrieves the data, and lets me view it by such categories as 'Most clicked / 24h', 'Most clicked / 1w' etc.
I hope this helps.
On one system I've worked on, we ended up storing redirects in a database table and creating a redirect page that takes an id as an input. On our content pages, we link to the redirect page with an unique id from this table. Once the redirect page looks up the url via the id from the table, it then sends the client a redirect response, sending them to the ending page.
This does give us logging of external links, and as an added bonus, it makes mass changes to external urls a bit easier in some cases.
Some newer options that work without any hacks as explained in https://css-tricks.com/send-an-http-request-on-page-exit/ are Fetch with the keepalive-flag or navigator.sendBeacon.
keepalive is not yet (Aug. 2022) supported by Firefox (Can I Use), but navigator.sendBeacon works in all modern browsers (Can I Use).
// normal fetch, not guaranteed to work
someLink.addEventListener('click', function(event){
fetch('http://www.testing.local/?origin=classic-fetch');
});
// fetch + keep alive (not working in Firefox as of 103, Aug. 2022)
someLink.addEventListener('click', function(event){
fetch('http://www.testing.local/?origin=fetch-keep-alive', {
keepalive: true
});
});
// navigator.sendBeacon (all modern browsers)
someLink.addEventListener('click', function(event){
navigator.sendBeacon('http://www.testing.local/?origin=beacon');
});

Resources