Wednesday, April 1, 2015

Installing and testing Django

Django is a web development framework for python. It eases your development time and makes web development a real joy. In this article I'll show you how to install Django and test it, given you already have python installed in Linux. Installing Django is a simple step and it's a single command.
$ sudo pip install django
It assumes you have python-pip module installed. If not install it using the following command.
sudo apt-get install python-pip        // In Debian Linux/Ubuntu

sudo yum install python-pip         // In Red Hat and Fedora
After installing you can check whether everything is setup properly. Use the following commands.
$ python
Python 2.7.8 (default, Nov 10 2014, 08:19:18)
[GCC 4.9.2 20141101 (Red Hat 4.9.2-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print django.VERSION
(1, 7, 7, 'final', 0)
Let's start off with setting up a default project to see the Django in work.

Create a directory of your choice. Say $HOME/DjangoProjects.

Navigate to that directory and issue the following command.
$ django-admin.py startproject mysite     // Here 'mysite' is your project name
This will create a directory called mysite, inside which you'll find a file named manage.py and another directory named 'mysite' which in turn contains four files; namely, __init__.py, setting.py, urls,py and wsgi.py.

Let's not bog down into details of what these files are all about. You can find detailed information in the Django web site https://www.djangoproject.com/

Let's start the Django's test server for this default site. (This server is merely for testing and not recommended to use in production). Type the following to start the server.
$ python manage.py runserver 9876

This should start run the server on port 9876. To see the welcome page, open a browser and navigate to http://127.0.0.1:9876/.

Hope this was a good starting point for you to learn Django. Enjoy working with Django.

Tuesday, October 28, 2014

Creating Roles and Assigning Permissions in WSO2 IS

In this article I will try to explain the ways to create and assign roles in WSO2 Identity Server. I'll walk you through on creating and assigning roles in the Management console UI and then outline the ways to do the same using an API and using a Java client programmatically.

Let's start the WSO2 Identity Server (IS) first. To download and run the WSO2 IS, look here.

Once started login to management console. First let's look at how we can create a role named 'TestRole' and assign some permissions in the permission tree to it. This involves only a very few steps. Navigate to Configure -> Users and Roles -> Roles ->  Add New Role. Enter the role name as 'TestRole' and click next. The permission tree would be shown and you need to select the the relevant permission in the tree for this role. If you need to assign certain existing users to this role, click next and select those users. Otherwise click finish. That's it. You have successfully create a a new role named 'TestRole' and assigned permission for that. You can see the existing roles by navigating to Home -> Configure -> Users and Roles -> Roles. At this place you can view the permission, delete the role, assign user and also rename the role.

Next we shall see how to create roles and assign any permission in the permission tree to those roles using a programmatic way, without using the UI. You can do that by calling an admin service as an API or using a Java client. I'll outline both the methods here.

There is a web service API called RemoteUserStoreManagerService that can be used to manage users and roles. This is an Admin Service in the WSO2 carbon platform. Admin services in the WSO2 products are hidden by default. To see the wsdl of this web service you need to unhide the Admin service WSDLs. To do that, first, open up CARBON_HOME/repository/conf/carbon.xml and look for the following line.
<HideAdminServiceWSDLs>true</HideAdminServiceWSDLs>
Make it to 'false' and restart the server.

After the server is successfully started, you can access the wsdl of the RemoteUserStoreManagerService by navigating to https://localhost:9443/services/RemoteUserStoreManagerService?wsdl (Replace 'localhost' part as applicable).

Following are the two methods I mentioned

1. You can create a SOAP UI project with this wsdl. You can use the addRole method to add the role. A sample SOAP call is given below to add a role named 'ValidRole' and assign permission under '/permission/admin/login/EmailLogin' where 'EmailLogin' being a new permission I created under '/permission/admin/login/'
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.ws.um.carbon.wso2.org" xmlns:xsd="http://dao.service.ws.um.carbon.wso2.org/xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:addRole>
         <ser:roleName>ValidRole</ser:roleName>
         <ser:permissions>
            <xsd:action>ui.execute</xsd:action>
            <xsd:resourceId>/permission/admin/login/EmailLogin</xsd:resourceId>
         </ser:permissions>
      </ser:addRole>
   </soapenv:Body>
</soapenv:Envelope>
2. You can write a Java client instead and invoke the methods in the RemoteUserStoreManagerService. A sample Java program is shown below to achieve this. The very self explanatory. Note: you need to add the plugins directory of a IS product to the classpath of the program to build and run this.
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.um.ws.api.stub.PermissionDTO;
import org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub;

public class ISClient {

    private static final String CARBON_HOME = "/home/shazni/Downloads/WSO2/wso2is-5.0.0";
    private static final String SEVER_URL = "https://localhost:9443/services/";
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin";
    private static final String ROLE_NAME = "permissionRole";

    public static void main(String args[]){

        String trustStore = CARBON_HOME + "/repository/resources/security/wso2carbon.jks";
        System.setProperty("javax.net.ssl.trustStore",  trustStore );
        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");

        ConfigurationContext configContext;

        try {
            configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem( null, null);
            String serviceEndPoint = SEVER_URL + "RemoteUserStoreManagerService";

            RemoteUserStoreManagerServiceStub adminStub = new RemoteUserStoreManagerServiceStub(configContext, serviceEndPoint);
            ServiceClient client = adminStub._getServiceClient();
            Options option = client.getOptions();

            option.setProperty(HTTPConstants.COOKIE_STRING, null);

            HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
            auth.setUsername(USER_NAME);
            auth.setPassword(PASSWORD);
            auth.setPreemptiveAuthentication(true);
            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
            option.setManageSession(true);

            boolean  authenticate = false;

            try{
                authenticate = adminStub.authenticate(USER_NAME, PASSWORD);
            } catch (Exception e){
                e.printStackTrace();
            }

            if(authenticate){
                System.out.println("User is authenticated successfully");
            } else {
                System.err.println("User is authentication failed");
            }

            try{
                PermissionDTO permissionDTO = new PermissionDTO();
                permissionDTO.setAction(CarbonConstants.UI_PERMISSION_ACTION);
                permissionDTO.setResourceId("/permission/admin/login/WebLogin");

                PermissionDTO[] permissionDTOs = new PermissionDTO[1];
                permissionDTOs[0] = permissionDTO ;

                adminStub.addRole(ROLE_NAME, null, permissionDTOs);
                System.out.println("Role is created successfully");
            } catch (Exception e){
                System.err.println("Role creation is failed");
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Well that's it. Hope this article has been informative to you.

Friday, October 17, 2014

Adding new permissions to permission tree in WSO2 Identity Server programmatically

Let's start the WSO2 Identity Server (IS) first. To download and run the WSO2 IS, look here.

The permission tree in WSO2 identity Server is simply,  a few collections stored in the underlying registry. Therefore adding new permissions to the permission tree involves adding a meaningful collection underneath a needed permission (collection). All these resources are stored in the registry path; /_system/governance/permission/admin. You can view this permission tree by navigating to an existing roles permission. To do that, navigate to Configure -> Users and Roles -> Roles -> Internal/everyone (Permissions) in the WSO2 IS. In this article I'm gonna write a sample Registry Client to add collections under /_system/governance/permission/admin to add new permissions to the permission tree. There's a permission named /_system/governance/permission/admin/login. We are going to add a permission named WebLogin under this. What needs to happen is simply creating a collection under this collection and assign a property called 'name' with its value being the name that needs to get displayed in the permission tree. This can be easily done using the management console of the WSO2 IS. What if someone needs to do this programmatically? Read further down to see how to!!

Adding a resource or collection under another collection in a product like WSO2 IS involves few works. We can obtain some registry based services from a service client named WSRegistryServiceClient. Retrieving this service and performing operations like get and put on top of Registry instance is the easiest way to manipulate the resources in the registry tree. But this service feature is not shipped with some of the WSO2 products including WSO2 IS by default. Therefore it's required to add this feature to WSO2 IS. Following URL explains how to add a feature to any WSO2 product.

https://docs.wso2.com/display/Carbon420/Installing+Features+via+the+UI

Look for WS API feature under the category of Governance Registry section. Once installed you can use the Registry API's to add collections under the above collection /_system/governance/permission/admin.

Following sample client java program adds the said collection.
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;

import java.io.File;

public class RegistryClient {
    private static final String CARBON_HOME = "/home/shazni/Downloads/WSO2/wso2is-5.0.0";
    private static final String axis2Repo = CARBON_HOME + File.separator + "repository" + File.separator + "deployment" + File.separator + "client";
    private static final String axis2Conf = CARBON_HOME + "/repository/conf/axis2/axis2_client.xml";
    private static final String username = "admin";
    private static final String password = "admin";
    private static final String serverURL = "https://localhost:9443/services/";

    private static WSRegistryServiceClient initialize() throws Exception {
        System.setProperty("javax.net.ssl.trustStore", CARBON_HOME + File.separator + "repository" +
                File.separator + "resources" + File.separator + "security" + File.separator +
                "wso2carbon.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
        System.setProperty("carbon.repo.write.mode", "true");
        ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2Repo, axis2Conf);
        return new WSRegistryServiceClient(serverURL, username, password, configContext);
    }

    public static void main(String[] args) throws Exception {
        Registry registry = initialize();

        Collection newCol = registry.newCollection();
        newCol.setProperty("name", "WebLogin");

        registry.put("/_system/governance/permission/admin/login/WebLogin/", newCol);
    }
}
Change the CARBON_HOME variable path to the IS_HOME of your server. Further, to build this you need to add the plugins directory of a Governance Registry product to the class path. Then if you run this code, you get a collection called WebLogin created under /_system/governance/permission/admin

Hope this article was useful for any WSO2 product user.

Sending email from a gmail account using python

In this guide I'll walk you through the python commands that you can use to send an email to someone from your gmail account. If you don't have python set it up in your environment look here for detail. Enter the commands step by step.
[shazni@shazniInWSO2 bin]$ python
Python 2.7.5 (default, Jun 25 2014, 10:19:55)
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> fromAddress="aaaaaaaaaaaa@gmail.com"
>>> toAddress="bbbbbbbbbbbb@yahoo.com"
>>> msg="Subject: Hello\n\nHi!! How are you"
>>> import smtplib
>>> server=smtplib.SMTP("smtp.gmail.com", 587)
>>> server.starttls()
(220, '2.0.0 Ready to start TLS')
>>> password="xxxxxxxxxxxxxx"
>>> server.login(fromAddress, password)
(235, '2.7.0 Accepted')
>>> server.sendmail(fromAddress, toAddress, msg)
{}
Replace 'aaaaaaaaaaaa', 'bbbbbbbbbbbb' and 'xxxxxxxxxxxxxx' accordingly.

You can easily put this into a python script and invoke it and send a quick email to someone from the command line without ever opening your email account in a browser. Following is a sample script which does the same as above.
#!/usr/bin/python

import smtplib
import getpass

fromAddress = raw_input("Enter your gmail address: ")
toAddress = raw_input("Enter the recipients email address: ")
subject = raw_input('Enter the subject of email: ')
bodyText = raw_input('Enter the body text: ')

msg = "Subject: " + subject + "\n\n" + bodyText

#msg="Subject: Hello\n\nHi!! How are you"

server=smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()

password = getpass.getpass('Gmail Password: ')
server.login(fromAddress, password)
server.sendmail(fromAddress, toAddress, msg)
A sample run of the script is shown below.
[shazni@shazniInWSO2 Python]$ python sendEmail.py
Enter your gmail address: mshazninazeer@gmail.com
Enter the recipients email address: mshazninazeer@yahoo.com   
Enter the subject of email: Hello
Enter the body text: This is a sample text sent to you by python!!!
Gmail Password:
[shazni@shazniInWSO2 Python]$
Enjoy using python script to send emails

Friday, October 10, 2014

Downloading and running WSO2 Identity Server

WSO2 Identity Server (IS) provide means for security and identity management for your web applications, services and API's. In it's latest version (5.0.0) it acts like an Enterprise Identity Bus (an idea of centrally managing the identity regardless of the standards being used). It's a versatile product to manage you application users security, entitle management and many more. See more information about the WSO2 identity server at http://wso2.com/products/identity-server/

How to run WSO2 IS
  1. Download WSO2 IS from above URL itself.
  2. Extract the zip archive into a directory. Say the extracted dircetory is IS_HOME
  3. Navigate to the IS_HOME/bin in the console (terminal)
  4. Enter the following command
$ ./wso2server.sh                       in Linux
or
$ ./wso2server.bat                 in Windows
Once started you can access the management console by navigating the following URL

http://localhost:9443/carbon

You may login with default username (admin) and password (admin). When logged in you would see the management console as shown below.


Tuesday, September 16, 2014

StoreKeeper 1.0.0 Released

In the current world, lot of things are being sold and bought. The items sold are of various types; be it a consumer good, a service rendered to a client, the providers (sellers) need to keep track of details of their accounting. They, most often also need to provide a bill to the customer. Traditionally, this was a manual process. The provider writes a manual bill and write down the total price with all the items sold with details of quantity, unit price, name etc. In the end of the day he'll calculate his revenue. And also he keeps an eye on the available items to get more items to sell when the items run out of the stock.

What if there is a multipurpose point of sale software, which could do all of the above things in a snap of a time? In the modern world, time is valuable and efficiency in trading to serve more customers is vital for a successful business. Point of sale software are just created for that.

StoreKeeper is a software tool which you can use at the point of sale to add things to transactions and in the end print a bill on a printer (usually using a dot matrix printer). StoreKeeper just makes this process extremely streamlined and is very easy to use. It's a light weight, portable software, which needs a bare minimum of system requirements.

Currently following features are supported.

  • Add an item
  • Update an item
  • Query an item or all items to view
  • Add users
  • Update a user
  • Query users
  • Add items to transaction
  • Delete item from transaction
  • Cancel the transaction
  • End a transaction
  • Print a bill (with a configured printer) together with a pdf copy in the computer
  • Get the total sales on a day

Features to be added in the future

  • Query current days transactions
  • Query current days transaction on a given item/service
  • View the history of an item sale
  • View the history of total sales
  • Notification of different events via email
  • Graphs to view the stats
  • Different access to different users with different credentials

Following is a screenshot of the StoreKeeper taken from a Linux desktop. It's currently tested to be working in both Windows and Linux.



To give you a small technical idea of StoreKeeper, it's a classic client server application. The server serves request from a Graphical front end GUI client. This means, the StoreKeeper would support multiple clients to use the Software at the same time (This scenario is not yet completely tested).

Following is a sample bill (Sorry for hiding few information) printed using a dot matrix printer.



Like our facebook page for StoreKeeper https://www.facebook.com/StoreKeeperService.

Please feel free to contact us if you wish to purchase this product or if you need to provide your feedback to us via our facebook page https://www.facebook.com/StoreKeeperService.