PHP redirect page - exception

i have a kohana website, and i want that, if someone modifies the current url (in the browser when he visits the website), and that specific page doesn't exist, he should be redirected to the current page (where he is now), or on the homepage, but without displaying any error.
any idea about how this can be done?

The guide gives the basic steps you need to take.
You basically replace the existing exception handler by defining a class called Kohana_Exception.
In that handler, you would check the error number and if it's a 404, then do a redirect based on the http referer.
class Kohana extends Kohana_Core
{
public static function handler(Exception $e)
{
if($e instanceof Kohana_Request_Exception)
{
Request::current()->redirect(Request::initial()->referrer());
}
}
}
This should be placed in for example application/classes/kohana.php
Note that this is the basic gist. You should expand on this and check if HTTP_Referer is set and based that the user actually came from your site.
Also note that this can cause confusion as people often don't notice they have been redirected.
Check the guide for other things you should do in the exception handler (for example, pass it on to the default handler.

Related

Angular 6 : Checking for safe route/URL

In my Angular 6 application, I would like to check if the given route does not contain any miscellaneous cross-site scripting code like adding a javascript URL or anything which can expose critical data to a third party.
Here is the below code where I am to check if the URL is safe or not, like if the URL contains iframe or javascript injection. but this not give any flag whether it is safe or not.
let's say URL is like this.
https://localhost/MyApp/%60%22%22%3E%3Ciframe srcdoc=%22<img src=x:x onerror=alert(document.cookie)>%22%3E%3C/iframe%3E%60
// in app.component.ts
this.router.events
.filter(event => event instanceof RoutesRecognized)
.map((event: RoutesRecognized) => {
console.log("test", this._sanitizer.sanitize(SecurityContext.URL,
event.state.url));
// here I want to proceed if anything fishy here and will route to 404 page.
}
any idea here, on how to prevent such csrf/xsrf.
You can refer below links, which might be helpful to you.
Link1
Link2

HTML 5 History - Open/reload subpage

I build a website based on one html file. I based the routing on HTML 5 API History. I made the addresses of the subpage with help from history.pushState and everything is ok, eg www.mypage.com/about.
The problem is in this when I try to refresh the subpage or how I will go directly to the address www.mypage.com/about. You can have an idea to call the function after going to www.mypage.com/about.
I tried to do something like that, but I get a 404 error
if (window.location.href.indexOf ("about")> -1) {
     someAction (0);
}
However, if I added in the url address "?" or "#":
www.mypage.com/?about
Then this condition will be fulfilled and the function will be called.
The point of the HTML5 History API is to avoid refreshing the browser. If refreshing the browser is what you want to do, then just call window.location.reload():
if (window.location.href.indexOf ("about") >= 0) {
window.location.reload();
}

Yii2: exclude specific controller actions from '$this->goBack()'

I have views from various controller actions which are solely to be run from an iframe placed in another view.
Currently, when the iframe loads, and I go to the log in page to log in, on success the login controller (using yii2 user module) calls $this->goBack(), redirecting me to the iframe source URL (since it's the last page visited), rather than the original page containing the iframe.
Basically, I'd like to exclude specific controller actions from being set as the return URL when $this->goBack() is called. Bonus points if all actions loaded in iframes are automatically excluded from $this->goBack().
Ok, I'll have a go at this! This code is totally untested! Your problem is that the action has no way of knowing whether it's been called from an iframe or not, unless you give it one. So, the basis of my attempt at an answer is that all urls for iframes should have an additional get parameter. Lets call that caller. So each iframe should look something like
<iframe url="index.php?r=controller/action&caller=this-controller/action</iframe>
Now you can always test the request url to see if it was called from an iframe. In addition, every link within the iframe should have this parameter added to it's url.
So, now we have at least two problems. Firstly, how to automatically add caller as a get parameter, without having to re-write every url, and secondly, how to reconfigure the goBack() method so it knows the difference between the two types of request.
The first problem can be relatively easily resolved by adding another view layer in between the controller and the view you want I'll call it iframe. So in your controller action, add this;
$view = 'The name of the view you want to render';
$this->render('iframe', 'view' => $view);//Add in any other parameters you want to pass
Your iframe view file should contain something like this;
<iframe src="<?php Url::to(['however you generate the url for your iframe', 'caller' => Url::to($this->context->route)]); ?>">
<?php $this->render($view); ?>//Pass additional parameters to the view if needed
</iframe>
Now we have a way of testing a controller/action call to see if it being requested by am iframe. The caller parameter is important because it allows us to extract a string to use as the value for goBack() and other methods.
Next, we need to extend UrlManager, as all request, response, Url:to() and goBack() methods and classes ultimately use the UrlManager to complete the methods for generating urls.
So, create a new UrlManager. We'll copy most of the code from the existing UrlManager, just adding some spiciness of our own. I've stored mine in commands, but put your where you like and change the namespace accordingly.
<?php
namespace app\commands;
use Yii;
use yii\web\UrlManager;
class CustomUrlManager extends UrlManager {
public function createUrl($params){
$request = Yii::$app()->request;
$caller = $request->get('caller');
if ($caller && !$params['caller']){
$params['caller'] = $caller;
}
return parent::createUrl($params);
}
}
So now, the iframe generates a caller parameter, and every link within the iframe will also have caller appended as a parameter, as long ass you've used either Url::to() (or variants on that method) or Yii::$app->UrlManager to generate your links.
Now all we need to do is customise the goBack() method of your controller to send any goBack() requests to the original source iframe.
public function goBack($defaultUrl = null)
{
$caller = Yii::$app->request->get('caller');
if ($caller){
return Yii::$app->getResponse()->redirect($caller);
}
return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
}
Finally you need to configure Yii to use your new UrlManager, in your config file;
'components' => [
'urlManager' => [
'class' => 'app/commands/CustomUrlManager'
]
]
I'd love to know if this works, it's been an interesting challenge!

load html pages on client side on button click

I am new to GWT. How do i load different and static HTML pages on the client side via button clicks. Have read up and do not wish to go into RPC, frames, client bundles and the following page:
best way to externalize HTML in GWT apps?
If client bundles are the closest i can get, may I have a very simple example, assuming that i have 4 HTML pages to be loaded on the client side, navigable by button clicks?
From my understanding, these individual pages may be created by UIBinders - please correct me if I'm wrong.
I have only the following code to display another page upon click, which is not working the way I want it. Also it gives a 403 error:
button.addClickHandler (new ClickHandler(){
#Override
public void onClick (ClickEvent event){
//Window.alert("Hello again");
String winUrl = GWT.getModuleBaseURL();
String winName = "Testing Window";
openNewWindow (winName, winUrl);
}
});
If you don't care about the state of your browser client page, then something like:
Window.Location.replace(newUrl);
Then the html page you point to in newUrl may or may not load the same java script as the current page.
If you do care about keeping the state of your browser client page and just want to avoid loading your static page at initial load time (by default all your pages get loaded at once), then code splitting is your friend. The principle is to wrap the code showing your new page around an async call defining the code split, something like:
GWT.runAsync(new RunAsyncCallback()
{
#Override
public void onFailure(Throwable reason)
{
Window.alert("Error in fetching the split javascript for page ...");
}
#Override
public void onSuccess()
{
// Code to setup and show your new static page instead of the current page.
// This code will be in a javascript file that won't be loaded at initial page load.
// You must make sure though that the below code does not use/include common code.
RootPanel.get().clear();
RootPanel.get().add(newWidget);
}
});
I guess it is as simple as:
Window.Location.assign("MenuPage.html");

How to hide HTML and other Content in EJS and Node

Having a tough time doing a simple web site in EJS.
I have this set up in my server file:
//Use the .html extension instead of having to name the views as *.ejs
server.engine('.html', require('ejs').__express);
// This avoids having to provide the extension to res.render()
server.set('view engine', 'html');
//set up directory to serve css and javascript files
server.use(Express.static(__dirname, '/views'));
This works great. I have HTML files, I have graphics, I have CSS. I am serving it up with a simple controller that renders the page. Nothing dynamic in these pages. But I do want them protected with an id/password system, and only served up through Express.
The access works fine, I have an end point set up to serve them. I'm forcing log in in that end point. But the problem is, that if someone knows the actual path to those files, they can get at them. So, the access is localhost:8081/admin/documentation/. However, the files are at /views/app_documents. And by entering in localhost:8081/views/app_documents/file_name.html, they can download/view the content, without going through my controls. I moved the content out of views, and grab it in my code, and serve it up, but that doesn't work for images or CSS.
Any suggestions for how to get around this?
Well, the things you find out after the fact.
This:
server.use(Express.static(__dirname, '/views'));
Is very bad. It should be:
server.use(Express.static('./views'));
The way it was, you could download our code, also. So, server.js was available for download. Yikes.
Live and learn.
Still can download the content without going through my authentication, though.
In case anyone else wants to do this, took a while. There are a few problems, as you still need to be able to directly access JS libraries, images and CSS. I found my answer in enter link description here.
The following modifications to that code does the trick. UserIsAllowed checks my permissions system to see if they can access that folder. If they can, no harm, off you go. Otherwise, kill the attempt. They get ACCESS_DENIED back as a string. I can't just kill anyone not going through my code, because then the CSS and images would not work. But this functions nicely. I now am able to serve up content based on my custom permissions system, which is part of a bunch of other administration functions. I can also have multiple different areas based on the URL that are protected by different privileges.
// This function returns a middleware function. It checks to see if the user has access
var protectPath = function(regex)
{
return function(request, response, next)
{
if (!regex.test(request.url)) { return next(); }
userIsAllowed(regex,function(allowed)
{
if (allowed)
{
next(); // send the request to the next handler, which is express.static
}
else
{
response.end('ACCESS_DENIED');
}
});
function userIsAllowed(regex,callback) {
if (regex.test('documentation_website') && request.session.admin_me && _.contains(request.session.admin_me["privileges"],"view_server_documentation")) callback(true);
else callback(false);
}
};
};
server.use(protectPath(/^\/documentation_website\/.*$/));