Docker Tomcat container SSH tips and tricks

Explains how to define environment vars available for tomcat inside docker container when JAVA_OPTS is not enough. We’ll explore some examples are based on one of our favorite customer’s projects.

Intro

Hello! In this post we’ll discuss a real customer use case and talk about some of the issues we solved in the process.

The customer’s architecture requirements included interfacing with a third party service into our custom PHP framework code. As the customer’s requirements also stipulated the service code must be written in Java (or .Net) we had to introduce Tomcat into the equation.

Even though PHP and Tomcat shared the server on the initial system, we decided to wrap all services within their own Docker containers.

Creating a Docker container for Tomcat

Let’s start with a docker-compose file that will define our tomcat container. We used tomcat:8.5.13-jre8-alpine as the base image.

At first glance this file contains 3 big sections, volumes, ports and expose.

The Volumes section will map files and folders needed to run a tomcat instance, included our app. You will notice in the example below that I included, in addition with .war file, JKS certificates and some configuration files I will explain later in this post.

The ports section will just bind container’s listen port with internal tomcat port (8080).

In the expose section we open some ports, in particularly 8009, that is required for server admin.

version: '2.1'

services:
  my_tomcat:
    container_name: my_tomcat
    image: tomcat:8.5.13-jre8-alpine
    volumes:
      - ./conf/catalina.properties:/usr/local/tomcat/conf/catalina.properties
      - ./client-keystore.jks:/etc/tomcat/client-keystore.jks
      - ./truststore.jks:/etc/tomcat/truststore.jks
      - ./myApp.war:/usr/local/tomcat/webapps/myApp.war
    env_file: ./environment.env
    ports:
      - "8080:8080"
    expose:
      - "8009"
      - "8080"

Setting our environment vars

As you may have noticed, we isolated the environment variables out of the docker-composer, in a new environment.env file, specified in env_file.

In addition to defining container variables, it will define JVM  requirements, such as JAVA_OPTS.

SHELL=/bin/sh


TOMCAT7_GROUP=tomcat7

TOMCAT_CFG_LOADED="1"

JAVA_OPTS="-Djavax.net.debug=ssl,handshake,keymanager,verbose  -Dendpoint=https://3rd-party.domain.com/services/api.wsdl -Djavax.net.ssl.keyStore=/etc/tomcat/client-keystore.jks -Djavax.net.ssl.keyStorePassword=secret -Djavax.net.ssl.trustStore=/etc/tomcat/truststore.jks -Djavax.net.ssl.trustStorePassword=changeit -Djava.awt.headless=true -Xms512m -Xmx2048m -XX:+UseConcMarkSweepGC -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2 -Djdk.tls.client.protocols=TLSv1.1,TLSv1.2 -Dsun.security.ssl.allowUnsafeRenegotiation=true"

SECURITY_MANAGER="false"

For this example, we’re telling the JVM to show verbose debug info for ssl and keymanager use (-Djavax.net.debug), which is the endpoint of the service (-Dendpoint), keystore and truststore files and passphrases repectively (-Djavax.net.ssl.keyStore, -Djavax.net.ssl.keyStorePassword, -Djavax.net.ssl.trustStore and -Djavax.net.ssl.trustStorePassword), among others.

Unfortunately, this is not enough with Alpine based container. In shortest explanation, when you start the container it runs catalina.sh that loads default configuration from the image.

But don’t panic, here’s the trick: the custom configuration can be placed in the catalina.properties file, letting those vars available for the system to be accessed like below:

System.getProperty("endpoint");

These custom properties file will be mounted as volume, replacing the default one and voila.

./conf/catalina.properties:/usr/local/tomcat/conf/catalina.properties

Adding and managing a Keystore

Once you have created your certificates stores (there is a powerful tool provided by Java, the keytool, which will be a topic for our future blog post), just copy the catalina.properties from standard tomcat and append variables at the end:

endpoint=https://3rd-party.domain.com/services/api.wsdl
javax.net.ssl.keyStore=/etc/tomcat/client-keystore.jks
javax.net.ssl.keyStorePassword=secret
javax.net.ssl.trustStore=/etc/tomcat/truststore.jks
javax.net.ssl.trustStorePassword=changeit

Final Thoughts

While this was a unique project, the common solution often works well. When I ran into common issues I also found a lot of recommendations for adding or updating a JAVA_OPTS environment variable. We did end up improvising to a point, but this was mostly reserved for edge cases.

I am glad you’re still here! Thank you and hope you have enjoyed reading. See you in next posts.

oAuth – Part 2

A practical example of oAuth integration into your system for authentication process.

Hello readers, today we will walk through a practical example about how to implement a simple login using the oAuth concepts described
in the previous post. To accomplish this goal we going to to create a new Erdiko project with three additional package that will help us to interact with Facebook API. Those packages are Erdiko-Authenticate and oauth2-client  and oauth2-facebook from The League of Extraordinary Packages. But before we can start coding we need to create a developer account and register our app.

How to register your app

This is the easy step; let’s demonstrate how to register using Facebook.
The first step is login in the developers site and sign in with a valid Facebook user. The next step is set you as Developer. To do this go to account, click on the button and follow instructions. Easy, right?
And the last step is to complete and submit this form. That’s it! Now you have registered your app to use Facebook API.

Prepare host project for the example

In this step we just need to create a new Erdiko project, for more details please refer to Erdiko

composer create erdiko/erdiko oauth_authenticate_sample

The next step is add the additional libraries.

In both cases, inside the project directory, will add new required packages

composer require erdiko/authenticate
composer require league/oauth2-client
composer require league/oauth2-facebook

setup erdiko-authenticate

Once it’s added we will need to add the config file in app/config/default/authenticate.json this is an example:

{
  "authentication": {
    "available_types": [{
      "name": "mock",
      "namespace": "erdiko_authenticate_Services",
      "classname": "Mock",
      "enabled": true
    }]
  },
  "storage": {
    "selected": "session",
    "storage_types": [{
      "name": "session",
      "namespace": "erdiko_authenticate_Services",
      "classname": "SessionStorage",
      "enabled": true
    }]
  }
}

we will revisit this file in future sections.

SETUP oAuth2 Client (from thephpleague)

This package doesn’t need a special configuration, but let’s take a look at constructor parameters we will user in our extension.

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'demoapp',    
    'clientSecret'            => 'demopass',   
    'redirectUri'             => 'http://example.com/yourredirecturl/',
    'urlAuthorize'            => 'http://example.com/oauth2/authorize',
    'urlAccessToken'          => 'http://example.com/oauth2/token',
    'urlResourceOwnerDetails' => 'http://example.com/oauth2/resource'
]);

clientId and clientSecret, come from the dashboard of your registered app, in the picture below are App ID and App Secret.

redirectUri, is a public URL in your server where you will be redirected after oAuth server finish the authentication process (Facebook in our example)

The last three keys (urlAuthorize, urlAccessToken and urlResouceOwnerDetails) will change based on which service we are using. In the above block, we assume that the the oAuth server is placed in example.com, maybe our custom implementation.

Create new Service class

We will implements AuthenticationInterface that way we can inject it in our authenticate package thru autenticate.json config file we added previously.

In authentication section you will have to add a new entry in available_types array:

{
      "name": "oauth",
      "namespace": "app_services",
      "classname": "oAuthAuthenticator",
      "enabled": true
}

In the constructor method of this class we will create a provider instance for the client, but we will use the third package (oauth2-facebook) to simplify things:

namespace app\services;


use erdiko\authenticate\AuthenticationInterface;
use \League\OAuth2\Client\Provider\Facebook;

class oAuthAuthenticator  implements AuthenticationInterface
{
    protected $provider;

    public function __construct()
    {
        session_start();

        $this->provider = new Facebook([
            'clientId'          => '1925853064368417',
            'clientSecret'      => '55ea4c1a56ca6d1db485b954ZZZ',
            'redirectUri'       => 'https://example.com/login/setlogin',
            'graphApiVersion'   => 'v2.8',
        ]);
    }

    public function login($credentials)
    {
        if(!$this->checkLoggedUser()) {
           $authorizationUrl = $this->provider->getAuthorizationUrl();
           $_SESSION['oauth2state'] = $this->provider->getState();
           header('Location: ' . $authorizationUrl);
           return;
        }
    }

    protected function checkLoggedUser()
    {
       return (
            isset($_SESSION['code']) 
            && isset($_SESSION['oauth2state'])
       );
    }

    public function verify($credentials)
    {
       return true;
    }
}

 

As you can see in the login method, I’ve added a simplistic check for a logged user, if there’s no record in session will redirect to login popup. Now we’re delegating the authentication process to Facebook, and the result of this process will be finally handled by method getSetLogin in the login controller.

Use new service in a Login Controller

In this example we are using a Login Controller just to keep authentication logic isolated. This is a normal erdiko controller, where we will have three basic actions: getLogin – that will load a basic -authenticator and invoke the login method. This action will be loaded when you click on Login with Facebook buttons that you can find everywhere these days.

public function getLogin()
{
   $authenticator = new BasicAuthenticator(new User);
   
   $authenticator->login(array(),'oauth');
}

getSetLogin – a callback method – is responsible to manage Facebook response and storage user in SESSION.

public function getSetLogin()
{
    $authenticator = new BasicAuthenticator(new User());
    if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

        unset($_SESSION['oauth2state']);
        throw new \Exception('Invalid state.');
    }
    $token = $this->provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);
    try{
        $user = $this->provider->getResourceOwner($token);
        $authenticator->persistUser($user);
    } catch (\Exception $e) {
        throw new \Exception($e->getMessage());
    }
}

Finally, we have the getLogout action, that will destroy the SESSION and user won’t be longer authenticated.

public function getLogout()
{
   $authenticator = new BasicAuthenticator(new User());
   $authenticator->logout();
   \erdiko\core\helpers\FlashMessages::set("Good bye, ".$authenticator->currentUser()->getUsername(), "success");
   $this->getLogin();
}

Conclusion

It’s pretty easy to add oAuth features on your system as you can see. Delegating the authentication process to a trusted server, providing users with the ability to use existing trusted accounts is a clear win.

Hope you enjoy this small example! Thanks for reading and hope to see you in my next post!

Using Stubs and Mocks in Jasmine to test your Angular code

Setting up your environment and is a very important part of unit testing AngularJS code. We discuss some of the tools and methods under which we can provide the full workflow of a system under test in this post.

Intro

Unit tests allow us to automatically test our code under a variety of conditions to prove that it works and when it breaks it does so in expected ways. In order to predictably test code, we also need to completely control the setup and data provided to the code under test.

Thankfully, the test tools provided for Angular testing allow you to mimic your models and control how your code responds to code in a very precise way. Jasmine provides some easy way to create test doubles and even “spy” on their execution.

In this post we will discuss some of the best practices and tools we use to control the environment your code is working against.

Why do we need to fake stuff?

We need to control the entire environment and workflow to make sure we are testing the exact scenarios.

Messing around with the DB and creating fake records can be difficult at best, at worst it can create false positives. Even more common, some CI systems lack access to a DB at all

We also need the ability to re-create the conditions under which a bug has been created. sometimes this means we need to replicate some crazy conditions

There are two tools to make this happen: Test Stubs (also known as  Fakes, depending on who you ask) and Mock Objects:

  • Test stubs are a very simplified object or data structure designed specifically for the test scenario. These can be constructed at the beginning of the test or per test.
  • Mock objects are class instances that mimic an existing class to provide the same method interface and return specific values when a method call occurs.

Test Stubs in AngularJS & Jasmine

Test stubs are a simple data structure or model we rely on when running our tests. These can be as simple as a static array of data or a very lightweight object with publically scoped methods. To differentiate a stub from a mock, we typically only mimic the methods we are actually testing. This is quite useful during

More often than not a stub is created at the beginning of the test suites and made accessible to the suite’s tests. A good practice is to limit the modifications to the stubs to make sure you are always testing the same thing.

If you must make changes it is a good idea to make a local copy to isolates your modifications to a specific test.

Test Stub Examples

HeaderComponent

Below is an abridged version of the component code we are unit testing. The important thing to note: at the end of this method’s execution we make a call to the router service to navigate the user to the “login” route and we need to make sure this and only this method is executed.

/**
 * Simple component providing a navigation header.
 */
...
export class HeaderComponent implements OnInit {
    ...
    /**
     * clickLogout clears the user's creds but also 
     * takes the user to the Login route
     */
    clickLogout() {
        ...
        this.router.navigate(['/login']);
    }
    ...
}

Test Suite Code

Here is the abridged test suite where we create our test stub

...

/** 
 * beforeEach setup executes before each test suite test runs.
 *
 * This allows us to setup the stub before each test
 */
beforeEach(async(() => {

    ...
    
    TestBed.configureTestingModule({
        ...
        providers: [

        /**
         * Create a very basic stub object with one method:'navigate'
         *
         * Use Jasmine's createSpy to create a very basic function
         * which also allows us to "listen in" when it's called
         */
        {
            provide: Router,
            useClass: class { 
                navigate = jasmine.createSpy("navigate"); 
            }
        }
        ...
    ]})
    .compileComponents();

    ...

}));

/**
 * Here we test the method and make sure we actually navigate
 */
it('should navigate to /login when clickLogout is fired', () => {
   ...
   let router = fixture.debugElement.injector.get(Router);
   component.clickLogout();

   // "listen" to make sure that the navigate method has been 
   // called and it was called with the expected value
   expect(router.navigate).toHaveBeenCalledWith(["/login"]);
   ...
});

 

Mocks

A Mock object is a simulated object instance used to mimic a classes behavior using the same interface. In simpler terms, this is a fake class with the same method signature as the Real Thing.

A mock object can be composed of multiple objects (and sometimes multiple mock objects), but most often should be created as simply as possible to keep your tests easily maintained.

Mock Object Example

/**
 * Create a mock of an existing service
 * by simply extending it and overriding some 
 * of the methods you wish to use in your tests
 */
class MockAuthService extends AuthService {

    /**
     * This method is implemented in the AuthService
     * we extend, but we overload it to make sure we
     * return a value we wish to test against
     */
    isLoggedIn() {
        return false;
    }
}

...

beforeEach(async(() => {

    ...

    TestBed.configureTestingModule({

        ...

        providers: [

        /**
         * Inject our mocked service in place of AuthService
         */
        {
            provide: AuthService,
            useClass: MockAuthService
        },

        ...

    ]})
    .compileComponents();

    ...

}));


it('should navigate to /login when clickLogout is fired', () => {

   /**
    * Get the mocked service here from our fixture
    * and add a spyOn over-ride to pretend we have
    * a logged in user.
    */
   let service = fixture.debugElement.injector.get(AuthService);
   spyOn(service, 'isLoggedIn').and.returnValue(true);
   
});

Conclusion

Unit tests are only as good as the environment you can provide for your code under tests. It’s very important to be able to mimic and recreate the environment under which you have both positive and negative results for your code.

Unit Testing AngularJS Components & Services

Unit testing is a very important part of software development, and it is extremely important to Angular applications as they become increasingly more complex. We’ll explain how to set up your unit tests and describe what you can actually test with some examples.

Intro

Unit testing is a very important part of the software development process, especially as your applications become more and more complex. Making sure your code is robust and adaptable is an important aspect of being professional. This is no less true with your AngularJS application.

If you are reading this, you are most likely already sold on unit testing but here’s some benefits and reasons for writing and maintaining your unit tests:

  • The ability to quickly update your code and make sure you are able to regressively test your code.
  • Updating your unit tests to cover a fixed bug will prevent the bug from getting re-introduced!
  • Use a CI to make sure EVERYONE on your team is testing the code.

Angular CLI, Jasmine & KarmaJS

Here at Arroyo Labs we use the latest version of Angular CLI a lot. It’s a great way to start a project very quickly provides a great start for your application. It also gives you some boilerplate unit tests for each component and service you create using the CLI.

While we have explained Jasmine and KarmaJS in past blog articles, here is a quick overview explaining how these frameworks work together:

  • Jasmine
    • A very popular behavior driven Javascript testing framework with a very clean syntax.
  • KarmaJS
    • A framework that allows you to run your Jasmine tests on a device or headless browser. The test runner itself will provide a DOM with which your code is rendered and provides the API that Jasmine will interact with.

Setting up your tests

To create a unit test, you need to include a consistent environment in which to run your code under test and we need to control the required classes and variables that go into creating this environment. Thanks to the magic of dependency injection, we can mock up some classes used by our classes and code.

Let’s take a look at the ‘top’ portion of a unit test we use in our user-admin project (you can find the whole unit test in our repo):

/**
 * Import some basic testing classes and utilities from AngularJS's
 * core testing code. This is the minimum required code to create 
 * a basic unit test.
 */
import {
     async,
     getTestBed,
     TestBed
} from '@angular/core/testing';

/**
 * Import some specific test classes used to mock the 
 * http backend and connection classes
 */
import {
    MockBackend,
    MockConnection
} from '@angular/http/testing';

/**
 * Import the HTTP classes we use in our service
 */
import {
    BaseRequestOptions,
    Http,
    Response,
    ResponseOptions,
    XHRBackend
} from '@angular/http';

/**
 * Finally, we import the required custom classes we use in our service,
 * and the service we are testing as well.
 */
import { User }         from '../shared/models/user.model';
import { AuthService }  from './auth.service';

import { UsersService } from './users.service';

What should we test in a service?

To test a service, we have to understand the underlying concept they represent: isolating logic and code into a re-usable class. This means we have a class we can pass around in our application where we get and manipulate data in expected ways.

Keep in mind, we can really only test publically scoped variables and functions. The unit test itself is really only able to interact with your service in the same way that an application is able to.

So, we have these things to test:

  • What public variables get initialized when we create the service?
  • Do public variables update as we expect when we call public functions?

Example Service Unit Test: UserService

In our UserAdmin project, we have a service called UserService used to interact with and manipulate user data we get from the AJAX backend.

The service itself only has quite a few public methods (it’s a very important class!) so we will focus on just two of the suite’s tests of the same method `getUsers`:

getUsers should return an empty observable list when the ajax request is unsuccessful

This is a test to make sure we return an empty list of users if the AJAX response does not contain an encoded list of users. This is a negative test, we are making sure that we return an expected response even when the backend returns an error.

it('#getUsers should return an empty observable list when the ajax   request is unsuccessful', () => {

 // set up the mocked service to return an
 // unsuccessful response (no users, 500 status)
 // with a helper method
 usersBodyData.success = false;
 setupConnections(backend, {
     body: {
         body: usersBodyData // use the previously init'd var for consistent responses
     },
     status: 500
 });

 // set up our subscriptions to test results 
 // when we actually get a result returned
 service.users$.subscribe((res) => {
     if(res) {
         expect(res).toBeTruthy();
         expect(res.length).toEqual(0);
     }
 });

 service.total$.subscribe((res) => {
     if(res) {
         expect(res).toBeTruthy();
         expect(res).toEqual(0);
     }
 });

 // make the actual request!
 let res = service.getUsers();

});

getUsers should return an observable list of users and result total when the ajax request is successful

This test makes sure that we get an observable list of users if the AJAX response is successful. To make sure this happens, we mock the response as though we have a JSON encoded list of users.

it('#getUsers should return an observable list of users and result total when the ajax request is successful', () => {
 // set up the mocked service to return an
 // unsuccessful response (users, 200 status)
 // with a helper method
 setupConnections(backend, {
 body: {
 body: usersBodyData
 },
 status: 200
 });
 
 // set up our subscriptions to test results 
 // when we actually get a result returned
 service.users$.subscribe((res) => {
 if(res) {
 expect(res).toBeTruthy();
 expect(res.length).toEqual(2);
 }
 });
 
 service.total$.subscribe((res) => {
 if(res) {
 expect(res).toBeTruthy();
 expect(res).toEqual(2);
 }
 });
 
 // make the actual request, with some params to pass via query string
 // we will explore this in a future post
 let res = service.getUsers(42, 42, 'id', 'desc');
});

What should we test in a component?

A component, like a service, is also a re-usable piece of code but it also has a defined lifecycle from its parent class and a frontend element via it’s template and optional CSS.

So, here is what we have to test:

  • Does this component actually get constructed?
  • What public variables get initialized and what DOM elements get rendered when we create the component?
  • Do public variables update as we expect when we call public functions?

Like we have noted above when discussing testing a service, you can really only test things that have been scoped as public by the component itself. This does include rendered DOM elements and you should test that these elements appear and render as expected since these are made public by the component itself.

Example Component Unit Test: UserListComponent

Test that the component actually results in a rendered component

it('should create', () => {
   fixture.detectChanges();
   const compiled = fixture.debugElement.nativeElement;
   component.ngOnInit();
 
   component.users = [];
   component.total = 0;
 
   // do we have a component at all?
   expect(component).toBeTruthy();
 
   // create new user button
   expect(compiled.querySelector('.btn-info')).toBeTruthy();
 
   // do we have a table
   expect(compiled.querySelector('table')).toBeTruthy();
   expect(compiled.querySelectorAll('tr').length).toBe(2);
});

Test that we display a list of users with a mocked response

it('should display list of users', () => {
   fixture.detectChanges();
   const compiled = fixture.debugElement.nativeElement;
 
   setupConnections(backend, {
       body: {
           body: bodyData
       },
       status: 200
   });
 
   component.ngOnInit();
 
   // create new user button
   expect(compiled.querySelector('.btn-info')).toBeTruthy();
 
   fixture.detectChanges();
 
   // do we have a table with users?
   fixture.detectChanges();
   expect(compiled.querySelectorAll('tr').length).toBe(21);
 
   // do we see the expected page count
   expect(component.getPageCount()).toBe(2); 
});

Conclusion

Unit testing is a not a oft-celebrated portion of the software development cycle, but it is an important part of the process. Once you have good tests in place, you can pivot direction and update your code with an increased sense of security.

Themes in the Erdiko Framework (Part 2)

In the first post we talked about how themes works in the Erdiko framework and covered important files to configure it. We continue with more advanced Erdiko theme topics and introduce new classes to discover more features, including layouts.

Today, I’m going to show you more concepts around themes in the Erdiko framework.  There are more concepts and classes to know and understand.

Layouts

To introduce the Layout class we need to define what is a layout: it includes the HTML for a basic web application structure in order to provide your own content. After made this clarification, we realize that a layout could be made by one, two, three or whatever number of columns.

Let’s look at the next code from Erdiko framework:

/**
 * Get two column layout example
 */
public function getTwocolumn()
{
    // Set columns directly using a layout
    $columns = array(
        'one' => $this->getView('examples/one'),
        'two' => $this->getView('examples/nested_view')
        );
    
    $this->setTitle('2 Column Layout');
    $this->setContent($this->getLayout('2column', $columns));
}

This code is an action from Example controller from code base of Erdiko framework. We can see how passing an array of views we can get a new layout built with ‘2column’ parameter. This way we instruct to Example controller what design we want to set to our application, and the final result will be something like this:

2columns

It’s important to take care about this latest parameter, it must exist as layout in the layout’s folder and the name must match exactly. Let’s recall our Erdiko folder structure:

layouts

the key method is Controller->getLayout():

 $this->setContent($this->getLayout('2column', $columns));

Under the hood, the controller delegates to a new Layout object composed of 2 views (one for each column) the call to render html code:

return  $layout->toHtml();

Pages

In order to reuse code the framework gives the chance of include html code often used, i.e. Header and Footer. This kind of content normally stay static around  the application. When we say “static” talk about structure however we also could include mustache code within the pages by using the {{ variable }} sintaxis.

Header

The header is a good example of html code that probably will not change in our web app. Erdiko framework installation provides us a nice default html code in the file:
app/themes/bootstrap/templates/pages/header.html

Something interesting to comment is the next piece of code:

<div class="navbar-collapse collapse" id="navbar-main">
  <ul class="nav navbar-nav">
    {{# menu.main }}
        <li>
            <a href="{{href}}">{{title}}</a>
        </li>
    {{/ menu.main }}
  </ul>
</div>

Ok, what is that sort of tag “menu.main”? Don’t worry just let’s say that we can create a html menu programmatically. When we talk about “Regions” will expand a better explanation. One important thing to highlight: the menu is built from the key “menu” in application.json file.

Footer

Footer section is more or less the same concept we talked previously with “header” but applied to the footer of application. Erdiko framework provides a default footer, the big difference against Header is the region used:

<div class="col-lg-12">
        <ul class="list-inline">
            <li class="pull-right"><a href="#top">Back to top</a></li>
            {{# menu.footer}}
                <li><a href="{{href}}">{{title}}</a></li>
            {{/ menu.footer}}
        </ul>
        <p>{{site.copyright}} {{site.full_name}}<br />
           Powered by <a href="https://github.com/ArroyoLabs/erdiko"
                         target="_blank">Erdiko</a>
        </p>
</div>

This time, the region used is ‘main.footer’ and the key used from application.json is “menu.footer”.

FlashMessages

To conclude with pages, another great and useful example is FlashMessages that provides (and being redundant) a flash message on top of the header page and denotes something important to show to the user application.

Unlike Header and Footer, FlashMessages is a helper, and you can call it:

<?php $messages = \erdiko\core\helpers\FlashMessages::get() ?>

‘$messages’ is an array and you are able to loop around it in order to give html structure:

<?php foreach($messages as $message): ?>
   <div class="alert alert-<?php echo $message['type'] ?> 
     alert-dismissible" role="alert">
     <button type="button" class="close" 
             data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
    </button>
    <?php echo $message['text'] ?>
   </div>
<?php endforeach ?>

If you can get messages, it’s logic that you can set messages too 😉 :

<?php 
$message ='This is a success message to show.';
//what color we want to show the message? 'danger' is by default.
$type = 'success';
\erdiko\core\helpers\FlashMessages::set($message,$type);
?>

Regions

In the first post when we talked about Mustache we understood how a content is rendered exactly in the right position into the html code. In order to conceive Regions, we can take the same concept, regions is just a “mark” in the html code to teach the framework about what kind of html structure we want to create, just in the right position where should be placed.

Let’s take the region part of footer.html:

 {{# menu.footer}}
     <li><a href="{{href}}">{{title}}</a></li>
 {{/ menu.footer}}

When the framework process this region tag, as result we will get a nice footer created programmatically. The million dollar question is:
– How the framework makes possible to know about footer structure?
Easy, Erdiko reads the section ‘menu.footer’ and iterates the key/values within  in application.json file.

Scripts and Styles

Previously, in our post “sample application using Erdiko Framework” we proposed as example a little dice to roll with a very simple view. That view used the controller method addJs() and addCss() in order to add css and js code to the view respectively. The method signature  is the next:

/**
 * Add Css includes to the page
 *
 * @param string $name
 * @param string $file
 * @param int $order
 * @param int $active
 */
public function addJs($name, $file, $order = 10, $active = 1)
{
    $this->getResponse()
        ->getTheme()
        ->addJs($name, $file, $order,$active);
}

Both methods share the same order and number of parameters.

Views

A view object is a piece of code to provide a visual representation of model data, in object terms is a very simple class where we can modularize our html code. Let’s take an example from Erdiko framework:

$this->addView('examples/about', $data);

here we add the view ‘examples/about’ to the  controller response. The views can receive parameters, here is the constructor:

public function __construct($template = null, $data = null, $templateRootFolder = ERDIKO_APP)
{
    $this->initiate($template, $data, $templateRootFolder);
    $this->setTemplateFolder('views');
}

by reading this code we can understand easy, what kind of parameters a view needs, look how the folder ‘views’ is assigned by default.

There is no more to talk about Views, the content will be rendered by the controller with addView() method internally, calling to:

$this->appendContent($view->toHtml());

Using properties

There are a set of  properties  defined and accessibles to the entire application, we can use it between {{ variableName }} in views or templates because are just keys/values already created in application.json config. file. To mention a few of them:
– site.name
– site. description
– site.copyright

Default.php

Default.php is, paradoxically, the default template theme applied to a given view. In a general manner, default.php is a complete html page with formal sections (head, body, etc) but instead make use of static code, it call the previously defined dynamic pages as header, footer and messages. Let’s see a fragment just to understand how the sections are referenced:

<?php echo $this->getTemplateHtml('header'); ?>
<?php echo $this->getTemplateHtml('messages'); ?>
<?php echo $this->getContent(); ?>
<?php echo $this->getTemplateHtml('footer'); ?>

where the method call:

$this->getContent()

what we want is to render the View code itself.

Conclusion

Erdiko framework provides a very flexible solution to easily change the aspect of a complete web application as complex as we propose it, the key to achieve that is setup properly all our config. files and templates.
Thanks for reading!

Dependency Injection

Dependency Injection is a widely used design pattern. We will define the concepts of this pattern and show a popular PHP implementation with a simple example.

What is DI?

Dependency Injection is a software design pattern that implements Inversion of control by decoupling software modules, introduced by Martin Fowler.

Usually a dependency injection container is used to manage and automate the construction and lifetimes of interdependent objects.

di_uml

Design pattern explanation and Use

Basically, if your class needs an object of other class, in this pattern you pass the dependency object as a constructor parameter or via property setters, instead of invoke factory or create dependency. You make it someone else’s problem.
Example 1:
class MyClass {
    private $objectA;
    public function __construct(ObjectA $object) {
        $this->objectA = $object;
    }
}
Example 2:
class MyClass {
    private $objectA;

    public function setObjectA(ObjectA $object) {
        $this->objectA = $object;
    }
}

In both examples, we don’t care how or where to create the objectA we just use it.

Some popular PHP DI-Container implementations

  • PHP-DI: is an interesting implementation of DI Container that has integration with several frameworks and IDEs like PHPStorm.
  • Symfony DependencyInjection: The DependencyInjection component allows you to standardize and centralize the way objects are constructed in your application.
  • Zend – DI: DI Container implementation for Zend framwork.
  • Pimple: Is a Dependency Injection Container from SensioLabs.

Pimple Presentation

This is an implementation from SensioLabs, and you guessed it, the same guys that created the Symfony libraries.

This is a friendly implemented package, lightweight and easy to use.
To install you just need to add to your composer.json,
$ ./composer.phar require pimple/pimple ~3.0
and you’re ready to use it!
$container = new \Pimple\Container();
Since it implements \ArrayAccess interface, you can store variables and factories as it was an array.
example of parameters:
$container['cookie_name'] = 'SESSION_ID';
an example of factory as a closure:
$container['session'] = $container->factory(function ($c) {
    return new Session($c['session_storage']);
});
It also provides methods to protect parameters, modify services after defined, extends, and more.
For more info refer to Pimple site.

Example Use Cases

Let’s imagine that we want to create factories dynamically based on a JSON configuration like this:
auth_config1
Then we can create a Trait with a method that will fill our container based on an argument that could be an array create from the decode of above JSON.
traits_builder
Here’s how we can use this trait:
di_using
Let’s break down the example above:
the class that implements the __construct method has defined a member attribute, container, that is an instance of Pimple.
Since we are using traits to buildAuthenticator, the result of the foreach block will be assigned into the class container attribute.
Within the build, we need to create a new temporary Pimple object. This is a hack I found to store nested containers.
This is needed because otherwise each time you attempt to add a sub-item within the “AUTHENTICATION” it overrides the previous one.
So once we have created all factories, we just set the temporal container in “AUTHENTICATION” cell of the main container.
To use your created object in the container you just need to do something like that:
$auth = $this->container["AUTHENTICATION"]["mock"];
$result  = $auth->doSomething();

Final Thoughts

This pattern is very useful and widely used these days especially in modern web development, in particular if you see it used in the Angular framework.
Even when you should pick the product that better match your requirements in each case, I can say that I feel very comfortable with Pimple. As I showed, it is very flexible, allowing you to create your own wrap class to customize its behavior and fit your needs.
Hope you enjoyed! Thanks for reading and see you on next posts!

Angular 2 Attribute Directives

Attribute Directives are a powerful way to affect the appearance or behavior of a DOM Element in your Angular 2 Application. We examine how attribute directives work, and how you can build re-usable custom code for your projects.

Introduction

AngularJS really introduced the concept of organizing and extending the DOM for use in real web applications. AngularJS 1.x brought us the idea of a Directive, or a way to indicate that a DOM element was “special” and will have a behaviors or an appearance that will be controlled by your code. AngularJS 2 took this idea and ran with it, but this also means we need to explain some stuff. We now have 3 tools at our disposal for interacting with the DOM: Components, Structural Directives and Attribute Directives.

Components, which you should have at least read about by now, are the most basic of the angular building blocks. Everything is a component and all components have directives; components are created from one or more directives. Directives are the method to identify a component’s behavior or associate a variable to a component.

Structural Directives are used to add or remove elements from the DOM. Common examples are *ngIf or *ngFor. These directives allows you manipulate a component based on a variable value or allow a component to iterate a series of values.

Finally, we have Attribute Directives. Attribute directives allow you to attach a behavior to an element or affect it’s appearance and re-use this throughout your application or package it up as something you use in all your projects.

Using Attribute Directives you can create a stylized DIV tag that formats all text and adds an event listener to change the color when the user mouses over the text. Show off your example code with some syntax highlighting!

I should also note that Attribute Directives can access and manipulate application values, but primarily are focused on affecting the component they have been attached. Think of this as more like CSS Selector Class on steroids. Make sure you do the “real math” of your application in your components.

Anatomy of an Attribute Directive & How to use it

Attribute Directives can be simple or complex. The simplest example of an Attribute Directive could be a simple CSS property attached to a P Tag:

<p [style.background]="'red'">I'm red!</p>

Anything more complex than the above example requires a little more wiring. Let’s look at an commented example from the official docs called “Highlight”:

// Import some stuff from the core library
import { Directive, ElementRef, Input, Renderer } from '@angular/core';

// create a Directive to decorate. To prevent confusion let's call this myHighlight to 
// illustrate the fact this this is a custom appearance
@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {

    /* 
    This is a pretty simple example, we just need a constructor. Pass the element we wish to affect in as "el" and make sure we interact with the DOM renderer with the obvious name of "renderer"
    */
    constructor(el: ElementRef, renderer: Renderer) {

       /* 
       Set the element's Background Color CSS property to Yellow, as though we "highlighted" it with a marker.

       Note we reference the element itself as el.nativeElement so we actually update the rendered DOM model itself.
       */
       renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
    }

}

Use and apply your custom directive attribute in your application
<p myHighlight>Highlight me!</p>

Some Attribute Directive Examples

Italic & Underline

A very simple example showing how we can make something italic, and underlined, using a simple attribute directive.

@Directive({ selector: '[alItalic]' })

export class ItalicDirective {
 
  constructor(el: ElementRef, renderer: Renderer) {
    renderer.setElementStyle(el.nativeElement, 'fontStyle', 'italic');
    renderer.setElementStyle(el.nativeElement, 'textDecoration', 'underline');
  }
 
}

Plnkr

Blink

We can also bring back the much missed BLINK tag using an attribute directive. This example illustrates how we can actually encapsulate some logic and manipulate the DOM element’s CSS with this logic by using an attribute directive that can be placed on any block element.

@Directive({ selector: '[alBlink]' })

export class BlinkDirective {
  
    constructor(el: ElementRef, renderer: Renderer) {
      setInterval(() => { 
        let style = "hidden";
        if(el.nativeElement.style.visibility && el.nativeElement.style.visibility == "hidden") {
          style = "visible";
        }
        renderer.setElementStyle(el.nativeElement, 'visibility', style); 
      }, 750);
    }
    
}

Plnkr

Detected User Event – Click

Finally, here’s an example where we can listen for a user event (click) on an element by simply using an attribute directive.

import { Directive, ElementRef, Input, Renderer, HostListener } from '@angular/core';

@Directive({ selector: '[alClick]' })

export class ClickDirective {
  
  private _el: ElementRef;
  
  constructor(el: ElementRef, renderer: Renderer) { 
    this._el = el;
  }

  @HostListener('click') onClick() {
    let str = this._el.nativeElement.innerHTML;
    alert("innerHTML from the element you clicked: " + str);
  }
    
}

Plnkr

Conclusion

We really only scratched the surface of what you can do with Attribute Directives. AngularJS has always been a framework that allowed you to organize and extend your DOM based applications, but AngularJS 2 has taken this to a whole new level.

Hope you enjoyed this post!

User Auth… What does it really mean?

Auth, a widely use term that can be a bit confused. We will show the meaning and how to work with both definitions as a system.

Auth, a term we can see every where these days. But, what does it really mean?
Honestly, it can be confusing when just saying Auth. Are you talking about authorization or authenticating?
More over, which is the difference between those two terms? Yeah, you got the point!

So now that I have your attention, let’s start by explaining what each is and how they are different and then how we can use both in our systems.

Difference between Authenticate and Authorize

We can roughly say, in the context of computer systems, authenticate is the process that ensures and confirms a user’s identity.

In other hand we can say that authorize or authorization, is the process responsible to determine the level of access that a user has in relation with a resource.

As you may already guessed, both of these should work together as a team.

That’s cool, but how to do that?

Let’s start with Authentication

Okay, starting from a very basic example, where you need to present two keys to the system, for example, username and password, where the first one will identify you and should be unique all system wide, and the other one would confirm that you are who you said you are.

Nowadays there are other architectures that requires multi-level security layers, tokens like oAuth, and so on, but I won’t go deeper on those in this post since this is just an overview.

So, going back to the previous example, you can tackle it at different level. That means, you can go with Sysadmins and request to keep .htaccess and .htpasswd files up to date, or you can choose to tackle at application level.

As you may guess, we will discuss the last one, programmatically. Here, again, we have a bunch of alternatives based on languages, patterns, etc.

My first thought when I had to work on that was, “why should I choose one? why not define an structure that let users select and implement the most appropriate for  each project?”
Yeah, sounds great, but how can I accomplish it? Well, actually is not a big deal (unless you’re trying to reinvent the wheel), is just take a look at already implemented things. The Database layer was my inspiration.

Let me explain how so. I’ve started defining a minimal interface that any Authenticator class should implement, that way I ensure that my controllers will not be broken when I change the configuration.

iauth

As a second step, I’ve added another two interfaces, one that defines requires method to store and retrieve “session” record of current user, and the other that ensure we have at least a “login” method.

storage_interface

Finally, I mixed all this stuff in a basic atuhenticator class, that with the use of Dependency Injection pattern (Pimple in my case) allow us to load based on a config file, any authenticator class that implements our interfaces. That means, I can choose to authenticate against a plain text file, database record or oAuth server like Facebook or Twitter, I just need to implement the logic for the selected service and put it in a config file.

mock_auth

And what about Authorization?

The good news is there’s a lot of alternatives. The bad news is that most of then are not implemented for all languages, instead, it seems that each programming language pick one and discard the other.

Don’t worry, most of them can be categorized in one of those big groups:

  • Role-based access control

from wikipedia

In computer systems security, role-based access control (RBAC) is an approach to restricting system access to authorized users. It is used by the majority of enterprises with more than 500 employees, and can implement mandatory access control (MAC) or discretionary access control (DAC). RBAC is sometimes referred to as role-based security.

Role-based-access-control (RBAC) is a policy neutral access control mechanism defined around roles and privileges.

  • Access Level Control

from wikipedia

An access control list (ACL), with respect to a computer file system, is a list of permissions attached to an object. An ACL specifies which users or system processes are granted access to objects, as well as what operations are allowed on given objects. Each entry in a typical ACL specifies a subject and an operation. For instance, if a file object has an ACL that contains (Alice: read,write; Bob: read), this would give Alice permission to read and write the file and Bob to only read it.

  • Identity Management

from wikipedia

In computer security, identity and access management (IAM) is the security and business discipline that “enables the right individuals to access the right resources at the right times and for the right reasons”. It addresses the need to ensure appropriate access to resources across increasingly heterogeneous technology environments and to meet increasingly rigorous compliance requirements.

In my case, I based on Ruby On Rails’ CanCan gem. Is very nice the way they implemented the “ability” class to grant users and groups the access to specific resource.
This time I’ve based on AC\Kilinka (compose package from American Council) and basically extended it to cover my needs.
Let’s breakdown a bit to make things more clear, there are two big parts, Authorizer and Guard, and two interface that defines them.
The first one, GuardInterface define four basic methods that will be responsible for get and check policies related with an specific resource, the other one, AuthorizerInterface, has two method, one for register guards and “can”, that decides if an action on a resource is permitted.
kalinka_guardinterface
kalinka_authorizerinterface

 

This package also provides some basic implementations. I’ve chosen RoleAuthorizer that better match to my needs, because users used to have a role associated. However, you can use a SimpleAuthorizer that allows you to allow/deny access by user instead of group.

The main difference is the way you config your permissions, here’s an example of what I did in a JSON format:
auth_json

Final thoughts

I have presented a brief overview about how you can identify users and manage permissions to your app resources.
Hope you enjoyed, thanks for reading, and stay tuned in this blog because we will bring you a new Erdiko packages that implements those things, soon!

Scaling your business with Technology @ SBF

We’ll be at Silicon Beach Fest Friday 8/25 for our CTO panel, “Scaling your business with technology.” If you are in LA please join us.

We’ll be at Silicon Beach Fest Friday 8/25 for our CTO panel, “Scaling your business with technology.”  If you are in LA please join us.

We have a great line up of speakers with some probing questions about how they build and scale their businesses.  Find out what kind of bumps they hit along the way and how they tackled those issues.

John Arroyo, Arroyo Labs, CEO (moderator)

Tina Denuit-Wojcik, Enplug, CTO
Paul Kasinski, Sky Zone, CTO
Erin Neff, The Black Tux, Director of Product
Andy Bauch, Wizely Finance, CTO
Cullen Zandstra, FloQast, CTO
Andres Buritica, CTO of Well Nest; Dodgers / R\GA Accelerator, Mentor

Official Description: CTOs and product experts talk about their journeys growing a business with technology. We will get insight into how certain technologies and concepts helped them handle growth and deal with the challenges of scale.

http://siliconbeachfest.com/

Electron and Angular2: simple App example

In our first post about Electron, we were covering the main topics about what is and how it works. This time we will cover how to create a dummy application using Electron and Angular2 as a front-end framework.

The application tree should be something like this picture:

tree

we can observe:

  • gulpfile and package.json: we will talk later about this 2 files, by now we can just say that are needed to build the application.
  • assets: The package.json is a file useful to give directives to Electron, with this method we can order show/hide the window borders, icon, maximized/minimized, etc.
  • frontend: here we got the content relative to the front end, more especifically all the Angular2 stuffs.
  • main: contains the index.js referenced by assets/package.json and is the start point of our electron application.
  • Tsconfig and typescript files are needed to transcode the typeScript code into javascript.

The main gulp tasks needed to build and “deploy” the application sources:

gulp_file_main_tasks

from this file, the most important tasks are frontend and electron. The first one copy all the content from the source path.

The principal Electron tasks to run the application:

main_electron_gulp_tasks

 

The  second task begins the transcoding and building of the application.

   The electron package.js, it is useful to pass directives at start time, the format of  is exactly the same as that of Node’s modules, and the script specified by the main field is the startup script of your app, which will run the main process. An example of your package.json might look like this:

package_electron

   We need to remember, if the main field is not present in, Electron will attempt to load an “index.js”.

The main index file loaded by electron at first time looks like a common js file:

main_electron

Then, the final product, the application up and running:

app_running

    we realize that is a common web application, the tick here is to work in the look & feel to “hide” that common details (relative to the chromium browser) and make an effort in order to show the appplication like a elaborated desktop app. It is possible to change icon, task bar, menus, system buttons etc. Even if you don’t like the squared and classical window you can hide the background and create a “floating” app with alpha and the shape you want.

   In the sample app we’ve created a minimal environment with an image background and a button in the middle. If you press the button, you will get as result a notification at the notification area, that position will be according to the SO where the app is running, in my case Im running ElementaryOs so the notification area is in the upper-right conner:

notification_electron

The cool part here is, that notification is executing in real native code. The Electron API does the hard work to communicate to the SO what we are trying to do, in our case, show a notification with a text and image.

That’s all for this second part of Electron, you can download the code from here thanks for reading!