Monday, January 18, 2016

Enabling CORS : Solve Cross-Origin Request Blocked error

If you are trying to run two different servers on the same machine and trying to access each other through HTTP request, you might get a CORS error.

Something like this in Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://ab.com. This can be fixed by moving the resource to the same domain or enabling CORS.


and this error in Google Chrome:

XMLHttpRequest cannot load http://abc.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.


To solve this - first you need enable module "headers" on the server which is responding.

For Apache you run the following and restart the server:

sudo a2enmod headers

next add the following to your .htaccess file

<IfModule mod_rewrite.c>
  Header add Access-Control-Allow-Origin "*"
  Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
  Header add Access-Control-Allow-Headers: "Content-Type"

  ..........................................
  ..........................................
</IfModule>

Tuesday, December 22, 2015

Laravel : Organize Controllers in Modules

Working on any PHP Framework I like to organize my Controllers in sub-folders. Here is how I do it in Laravel. For the most common scenario where you have  - unauthenticated pages and an authenticated admin panel, I create sub-folder named admin and site for both views and controllers. So the folder structure would be something like this -
app-
    controllers -
        admin
            LoginController.php
            ProductController.php
        site
            SiteController.php
    views -
        admin
            login.blade.php
            admin.blade.php               
        site
            site.blade.php
I put the Controllers in their respective namespaces.
<?php
namespace Admin;

class ProductsController extends \BaseController {
...............................
and for the site
<?php
namespace Site;

class ProductController extends \BaseController {
...............................
To access these controllers from the routes.php there are two ways - one to use get directly like -
Route::get('/', 'Site\SiteController@getIndex');
and for the admin we will use group
Route::group(array('prefix'=>'admin',
                   'namespace' => 'Admin'),function() {
 Route::get('/','LoginController@getLogin');
 Route::get('login', 'AuthController@getLogin');
 Route::post('login', 'AuthController@postLogin'));
        Route::get('logout', 'AuthController@logout'));
});

Route::group(array('prefix'=>'admin',
                   'namespace' => 'Admin',
                   'before' => 'auth'),function() {
 Route::resource('product', 'ProductsController');
});
Now very importantly, after writing the controllers run the composer dumpautoload. Or you will get a error saying Class Site\SiteController not found.

Tuesday, December 15, 2015

Setting Up Raspberry Pi...

I love weekends like this. Got a pair of Raspberry Pi s. Had a great time setting them up.

There are lot of different OS you can install in the Raspberry. I tried Raspbian and hooked it up with my VGA Monitor using an adapter (Raspberry supports HDMI by default).



And then I tried Raspbmc, on my TV. That was really a great experience, the youtube video was coming full HD. And what more you can actually install xbmc remote on your smart phone (I installed it on my android) and use it as a remote.

Friday, January 18, 2013

Spring Security - First Steps

Here are my notes on getting started with using Spring Security with web applications.This  post focuses on authentication and securing web requests.

The first thing to do when using Spring with web applications is bootstrapping the application context. To do that add a context listener to the web.xml file.
<listener> 
         <listener-class>
               org.springframework.web.context.ContextLoaderListener
         </listener-class> 
</listener> 
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
                /WEB-INF/application-context.xml
                /WEB-INF/applicationContext-security.xml
        </param-value>
</context-param> 
Notice that there are 2 spring configuration files. The idea here is to keep the security related configuration in a separate xml configuration file of its own.
The next thing to do is to add a filter which will intercept the requests and delegate to a 'spring-context-aware' class which will add the actual security related functionality.
<filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
 </filter-mapping>
Now to configure the actual authentication and role based url access , add the following snippet to the applicationContext-security.xml
<http auto-config="true">
 <intercept-url  pattern="/test/**" access="ROLE_USER" />
 <intercept-url  pattern="*/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
</http>
What we have done above is to configure spring so that whenever there is a request for any url under the test folder under the context root, spring checks whether the user is logged in and has the authority 'ROLE_USER'. If the user is not logged in, she is taken to the login page.

But where does the actual authentication happen? Spring provides a host of production ready authentication providers to do the actual authentication against a datasource or ldap or through other means. For this post , we'll look at the simplest case where the usernames and password are read from the spring application context file.
<authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="nandini" password="nnnnppp" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="sanjucta" password="sssppp" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>
So there we have it, we have configured spring security to be able to intercept web requests and force the user to login if he wants access to access 'restricted' urls.The username / password combination that the user enters is checked against the user names and passwords configured in security configuration file .

Looking into Advanced Zend_Navigation - Part 2

Continued from Looking into Zend_Navigation - Part 1

Choose A Menu...


Now that we have the basic in place how about some tweaks? May be you don't want to style your menu yourself. You have found a cool and FREE jquery menu - something like this one, that you want to use. (Of course you can have your own favorite. But once you have understood the way things go you can have your own pick).



Lets see how to get this done using Zend_Navigation.

First download the menu files from here.

Incorporate The Menu In Your Application...


Unzip it in your public folder. Study the html files and lets get to business. We will go for the top dock menu. For that we will need the css-dock-top.html. Copy the content of the file and paste it in the layout. You will need to change the paths to absolute path. To do that add the baseUrl in your application.ini :

resources.frontController.baseUrl = "http://localhost/php/learning_zend_nav/public"
And in the layout use
<?php echo $this->baseUrl();?>
to get the absolute path. The current layout.phtml we get is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>CSS Mac Dock</title>
<script type="text/javascript" src="<?php echo $this->baseUrl();?>/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo $this->baseUrl();?>/js/interface.js"></script>
<link href="<?php echo $this->baseUrl();?>/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="dock" id="dock">
   <div class="dock-container">
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/home.png" alt="home" /><span>Home</span></a> 
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/email.png" alt="contact" /><span>Contact</span></a> 
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/portfolio.png" alt="portfolio" /><span>Portfolio</span></a> 
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/music.png" alt="music" /><span>Music</span></a> 
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/video.png" alt="video" /><span>Video</span></a> 
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/history.png" alt="history" /><span>History</span></a> 
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/calendar.png" alt="calendar" /><span>Calendar</span></a> 
   <a class="dock-item" href="#"><img src="<?php echo $this->baseUrl();?>/images/rss.png" alt="rss" /><span>RSS</span></a> 
 </div>
</div>
<script type="text/javascript"> 
 $(document).ready(
  function()
  {
   $('#dock').Fisheye(
    {
     maxWidth: 50,
     items: 'a',
     itemsText: 'span',
     container: '.dock-container',
     itemWidth: 40,
     proximity: 90,
     halign : 'center'
    }
   )
  }
 );
</script>
</body>
</html>
it just shows the un-customized menu in all the pages. Now lets customize this for ourselves.

Customize...


We have four menu-heads, we will use the icons for Home and Portfolio but for the other menu-heads get the related images from somewhere like - http://www.iconfinder.com.

We are representing each menu with an image, now how to get the image information from the navigation.xml. Well, we can put in our custom fields in the page entity directly and access it from the view. Lets go ahead and change our xml.
<?xml version="1.0" encoding="UTF-8"?>
<configdata>
    <nav>
     <home>
         <label>Home</label>
         <controller>index</controller>
   <action>index</action>
   <image>home.png</image>
         <pages>
             <aboutus>
                 <label>About Us</label>
                 <controller>index</controller>
                 <action>aboutus</action>
                 <image>information.png</image>
             </aboutus>
             <portfolio>
                 <label>Portfolio</label>
                 <controller>index</controller>
                 <action>portfolio</action>
                 <image>portfolio.png</image>
             </portfolio>
             <services>
              <label>Services</label>
                 <controller>index</controller>
                 <action>services</action>
                 <image>services.png</image>
             </services>            
         </pages>
     </home>
    </nav>
</configdata>
You can see we have added a image attribute to each of the menu items. But we need to override the menu rendering of Zend_Navigation and make it to display a different format using the image attribute. For that Zend provides us with something called the View Partials. We will create our own partial menu template, set it in the Zend_Navigation menu object and ask Zend to render it.

Creating the Partial Menu Template...


Create a _menu.phtml under the layout/scripts folder (the folder in which we have the layout.phtml itself). Copy and paste the following :
<?php 
 $menu_dir = $this->baseUrl().'/images/';
?>
<div class="dock" id="dock">
   <div class="dock-container">
<?php  
   foreach ($this->container as $menu) {
?>
  <a class="dock-item" href="#"><img src="<?php echo $menu_dir.$menu->image;?>" alt="<?php echo $menu->label;?>" /><span><?php echo $menu->label;?></span></a> 
<?php 
  foreach ($menu as $menu) {
?>
  <a class="dock-item" href="#"><img src="<?php echo $menu_dir.$menu->image;?>" alt="<?php echo $menu->label;?>" /><span><?php echo $menu->label;?></span></a> 
<?php 
  }
?>  
<?php }?>
 </div>
</div>
<script type="text/javascript"> 
 $(document).ready(
  function()
  {
   $('#dock').Fisheye(
    {
     maxWidth: 50,
     items: 'a',
     itemsText: 'span',
     container: '.dock-container',
     itemWidth: 40,
     proximity: 90,
     halign : 'center'
    }
   )
  }
 );
</script>
Let us see what exactly we did here. We got the navigation container and iterated into the menus/submenus and displayed them the way we want. Note that we accessed the image attribute of the menu items by a simple - $menu->image. We can similarly use any custom attribute for our menu display - like a description attribute for bubble help.

To render the menu using the partial - we simply set it in the layout, like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Learning Zend_Navigation - Part 2</title>
<script type="text/javascript" src="<?php echo $this->baseUrl();?>/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo $this->baseUrl();?>/js/interface.js"></script>
<link href="<?php echo $this->baseUrl();?>/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php 
 $this->navigation()->menu()->setPartial('_menu.phtml');
 echo $this->navigation()->menu()->render();
?>
</body>
</html>
Now we have our customized menu using Zend_Navigation up and ready. Lets see how it looks...

 photo out_4_zps82c39ef1.gif

Looking into Zend_Navigation - Part 1

Zend_Navigation is an elegant way to handle the navigation elements of your site, i.e. the menus, breadcrumbs, sitemaps etc. It lets you to keep the view, where you might be using smart looking javascript menu libraries and the content separate.  You can integrate your navigation with Zend_Acl, which would handle the authorization part of the navigation. Isn't that just awesome!!!

In this tutorial we will look into Zend_Navigation step-by-step, from easy to advanced. And even some hacks that I found useful when I was trying some real cool menu libraries.

Setting up for Zend_Navigation...


First lets start with the basic. Our main menu structure would be the following, we will add sub-menus to it later. For simplicity we will assume only one controller with several actions.

Home  - links to default route i.e. index/index
Abouts Us - links to index/aboutus
Portfolio - links to index/portfolio
Services - links to index/services

Get your Zend setup ready. I am working with Zend Framework 1.12 but I guess any 1.x version should work. First create all the required actions in the IndexController and their corresponding views. The actions doesn't need do much except show their corresponding view page, as we are not actually bothered about what they do or show in this tutorial, but how to navigate to them. The corresponding views similarly can be simple - just stating what they are should be sufficient.

We should have something like this to start work with-

Now we will need to create the default layout for the views. For that create layout.phtml in application/layouts/scripts. And copy the following to it.
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Learning Zend Navigation</title>
</head>
<body>
<h1>Learning Zend Navigation</h1>
<?php
    echo $this->layout()->content;
?>
</body>
</html>
and add the following line to your application.ini
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
Refresh the page and this is how it should look -

Photobucket


The navigation.xml....


Now that we have the basic setup ready, let us start with the navigation. For that we create navigation.xml in application/configs with the following content.
<?xml version="1.0" encoding="UTF-8"?>
<configdata>
    <nav>
     <home>
         <label>Home</label>
         <controller>index</controller>
   <action>index</action>
         <pages>
             <aboutus>
                 <label>About Us</label>
                 <controller>index</controller>
                 <action>aboutus</action>
             </aboutus>
             <portfolio>
                 <label>Portfolio</label>
                 <controller>index</controller>
                 <action>portfolio</action>
             </portfolio>
             <services>
              <label>Services</label>
                 <controller>index</controller>
                 <action>services</action>
             </services>            
         </pages>
     </home>
    </nav>
</configdata>
In your Bootstrap.php read the xml and set it in the view.
protected function _initNavigation() {
    $config = new Zend_Config_Xml(
                 APPLICATION_PATH.'/configs/navigation.xml','nav');
    $container = new Zend_Navigation($config);
  
    $this->bootstrap('layout');
    $view = $this->getResource('layout')->getView();
    $view->navigation($container);
}
Now just render the menu in layout.phtml -
<body>
<h1>Learning Zend Navigation</h1>
<?php echo $this->navigation()->menu(); ?>
<?php
    echo $this->layout()->content;
?>
</body>
This will render the menu in all the pages and now we will be able to navigate to the pages using this menu.

Photobucket

The Breadcrumb....


For a simple breadcrumb lets add - did you know the term breadcrumb has originated from the story of Hansel and Gretel :P
<body>
<h1>Learning Zend Navigation</h1>
<?php echo $this->navigation()->menu(); ?>
<?php echo $this->navigation()->breadcrumbs(); // for breadcrumbs ?>
<?php
    echo $this->layout()->content;
?>
</body>

and Styling things up...


We are done with a simple navigation. But this doesn't look good. So let us do some simple styling. And the finished layout.phtml will look like this -
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Learning Zend Navigation</title>
    <style type="text/css">
            * {padding: 0 0; margin: 0 0; font-family: Helvetica, sans-serif;}
            .header { background-color:#DDD; }
            h1 { padding:10px; }
            .content { padding: 10px; }
            .topnav  { padding: 5px ; border-bottom:2px solid #000}
            .topnav ul , .topnav ul li { display: inline; }  
            .topnav ul li a
            {
                color: #00E;
                text-decoration: none;
                border-width: 1px 1px 0px 1px;
                border-color: #000;
                border-style: solid;
                padding: 5px;
                background: #808080;
            }
            .topnav ul li a:hover { background: #CCC; }
            .breadcrumbs { padding:10px; background:#EFEFEF; }            
        </style>
</head>
<body>
 <div class="header">
  <h1>Learning Zend Navigation</h1>
  <div class="topnav">
   <?php echo $this->navigation()->menu();?>
  </div>
 </div>
 <div class="breadcrumbs">
  <?php echo $this->navigation()->breadcrumbs();?>
 </div>
 <div class="content">
 <?php
     echo $this->layout()->content;
 ?>
 </div>
</body>
</html>
And this is what we get at this stage -

Photobucket


Looking into Advanced Zend_Navigation - Part 2

Monday, December 17, 2012

Ekiga DTMF setting for Asterisk

I was trying to test my Asterisk dialplans with Ekiga on my Ubuntu m/c. There is an excellent write-up on this here. Following the steps Ekiga registered to my SIP account without much trouble.

 But I found Asterisk was not reading the inputs from Ekiga, like the extension number or options for the IVR. To solve this problem I went to Ekiga - Edit -> Preferences -> Protocols -> SIP Settings. And changed the DTMF MODE : Send DTMF as to RFC2833.