Wednesday, April 9, 2014

SSO Integration guide with Play-Authenticate




1. Add dependencies


Add below dependencies and the repositories to your play project’s Build.scala file (fully tested with play 2.1)  and build the project. do play eclipse. This will add SSO module, Deadbolt and Play-Authenticate dependencies to your application.


play 2.1.1
"com.redmart.sso.integration"   %  "sso-integration" % "1.0",
"be.objectify" %% "deadbolt-java" % "2.1-RC2",
"com.feth"      %%  "play-authenticate" % "0.3.5-SNAPSHOT"


play 2.2.0
"com.redmart.sso.integration"   %  "sso-integration" % "2.2",
"be.objectify" %% "deadbolt-java" % "2.2-RC4",
"com.feth"      %%  "play-authenticate" % "0.5.0-SNAPSHOT"



Add below repos if they are not already present


resolvers += "maven-repo" at "https://github.com/Redmart/maven-repo/raw/master/",
resolvers += Resolver.url("Objectify Play Repository",     
url("http://schaloner.github.com/releases/"))(Resolver.ivyStylePatterns),
resolvers += Resolver.url("Objectify Play Snapshot Repository", url("http://schaloner.github.com/snapshots/"))(Resolver.ivyStylePatterns),
resolvers += Resolver.url("play-authenticate (release)", url("http://joscha.github.com/play-authenticate/repo/releases/"))(Resolver.ivyStylePatterns),
resolvers += Resolver.url("play-authenticate (snapshot)", url("http://joscha.github.com/play-authenticate/repo/snapshots/"))(Resolver.ivyStylePatterns),
resolvers += Resolver.url("Objectify Play Repository (release)", url("http://schaloner.github.com/releases/"))(Resolver.ivyStylePatterns),
resolvers += Resolver.url("Objectify Play Repository (snapshot)", url("http://schaloner.github.com/snapshots/"))(Resolver.ivyStylePatterns),
resolvers += Resolver.url("play-easymail (release)", url("http://joscha.github.com/play-easymail/repo/releases/"))(Resolver.ivyStylePatterns),
resolvers += Resolver.url("play-easymail (snapshot)", url("http://joscha.github.com/play-easymail/repo/snapshots/"))(Resolver.ivyStylePatterns)




2. Add required plugins with necessary configs


2.1 Add Play Authenticate and Deadbolt plugins to your project’s conf/play.plugins file


10000:be.objectify.deadbolt.java.DeadboltPlugin
9000:service.MyUserServicePlugin
10010:com.feth.play.module.pa.providers.oauth2.google.GoogleAuthProvider



2.2. Create a directory named play-authenticate in conf directory and  add xxx.conf  file with below content.


play-authenticate {
   accountMergeEnabled=false
   accountAutoLink=true


   google {
       redirectUri {
       }


#Google client keys           
clientId="1026436145178-eglfmfarkopfnj823leutk27u0s4c3u7.apps.googleusercontent.com"
     clientSecret="qwoTMbT3xoua_el2Qh3Y-1lI"
   }
}




2.3. After that you need to include that file in your main application.conf file like below.


include "play-authenticate/xxx.conf"


2.4 Add deadbolt handler in your application.conf


deadbolt.java.handler=security.AuthenticationHandler



3. Add Authorizer URL


Add authorizer URL in your application.conf like below, at the end add your application Id which should be defined inside Authorizer.





4. Configure Routes


Add below routes to your applications routes files.



GET     /logout                                      com.feth.play.module.pa.controllers.Authenticate.logout
GET     /authenticate/:provider           com.feth.play.module.pa.controllers.Authenticate.authenticate(provider: String)
GET     /authenticate/:provider/denied     controllers.Application.oAuthDenied(provider: String)
GET     /login                                         controllers.Application.login()



Add root to your home page.


GET     /                                              controllers.SlotDashboard.index()



Application class has to have below methods.



   public static Result login() {
       return ok(login.render());
   }


  public static Result oAuthDenied(final String providerKey) {
       flash(FLASH_ERROR_KEY,
               "You need to accept the OAuth connection in order to use this website!");
       return ok(login.render());
   }




5. Update Global class to use Play-Authenticate and SSO module


5.1 Add below code snippet to your Global class’s onStart method and change according to your landing page.


PlayAuthenticate.setResolver(new Resolver() {


    @Override
    public Call login() {
        return routes.Application.login();
    }


    @Override
    public Call afterAuth() {
        return routes..index();
    }


    @Override
    public Call afterLogout() {
        play.mvc.Controller.response().discardCookie("access_token");
        play.mvc.Controller.session().clear();
        play.mvc.Controller.flash("message", "Logout successfully");
        return routes.Application.login();
    }


    @Override
    public Call auth(final String provider) {
                Cookie token = play.mvc.Controller.request().cookies().get("access_token");
        try {
            if (token != null && token.value() != null && !token.value().isEmpty()) {
                int status = SsoUtil.setUserRoles(token.value());
                if(status == 200){
                    return routes..index();
                }else {
                    return routes.Application.login();
                }
            } else {
        return com.feth.play.module.pa.controllers.routes.Authenticate.authenticate(provider);
                    }
        } catch (Exception e) {
    Logger.error("Exception occurred while validating the token or setting roles : " + e.toString());
        }
        return null;       
    }


    @Override
    public Call onException(final AuthException e) {
        if (e instanceof AccessDeniedException) {
        return routes.Application.oAuthDenied(((AccessDeniedException) e).getProviderKey());
        }
        return super.onException(e);
    }


    @Override
    public Call askLink() {
        return null;
    }


    @Override
        public Call askMerge() {
            return null;
        }
    });



5.2 Set datastore to be used in SSO-module as below inside Global class. I am assuming you are using Morphia for accessing mongo DB.


//Set SSO morphia object which is bundled in the sso-integration jar.


SsoMorphiaObject.morphia = new Morphia();
SsoMorphiaObject.datastore = SsoMorphiaObject.morphia.createDatastore(MorphiaObject.mongo,DB);
SsoMorphiaObject.datastore.ensureIndexes();
SsoMorphiaObject.datastore.ensureCaps();    SsoMorphiaObject.datastore.setDefaultWriteConcern(WriteConcern.UNACKNOWLEDGED);




6. Update Mongo DB


6.1 Add user to your counter collection
db.counters.insert({"collection":"user","c":100})


6.2 Create an acl collection with your local methods and views you need to control with roles.


i.e
db.acl.insert({"method":"controllers.Zones.index","roles":["developer","admin","superadmin"]})
db.acl.insert({"method":"controllers.SubZones.index","roles":["developer","admin","superadmin"]})
db.acl.insert({"method":"views.zones","roles":["developer","admin","superadmin"]})





7. How to control User accesses


7.1 Add below annotation to control your method accesses only for a logged in user. It will validate whether the user is present in the Session if not it will redirect to the login page.



@Security.Authenticated(Secured.class)
public static Result index() {
}


7.2 Add below annotation to control methods based on specific roles.


@Dynamic(value="controllers.Zones.index")
public static Result index() {
}




7.3 Add both annotations if you need both.


@Security.Authenticated(Secured.class)
@Dynamic(value="controllers.Zones.index")
public static Result index() {
}






7.4 Add below annotations inside your scala.html pages to control role based views.


@dynamic("views.zones") {
  • "active">"/zones">Zone
  • }


    This will check whether the logged in user is having required roles to access this method. When you sign in, the relevant roles will be fetched from Authorizer and set it in the user’s session. Whenever the user is trying to access methods, it checks if the required roles are present in the session to access these methods.




    8. Finally update the Login Page


    Add login.scala.html inside your app/views directory with the below content, add google image to your image directory. You can design your login page as you wish and add below code snippet to use google authentication.


    i.e


    @import com.feth.play.module.pa.views.html._



            }








    9. Sample login page.




    This will take you to Google Account chooser page



    You can sign in with whatever account. But once you are authenticated with google, the required roles will be fetched from the Authorizer before rendering the landing page. So based on the roles the application will function accordingly.



    When you logout you will not be logged out from Google, thats the intended behavior.Because signing out from your application should not signed you out from other google applications which you might have already signed in, as an example, Google docs etc. hence if you logout, you will only be logged out from your application, not from Google. Hence in the consequent re-logins, it will not take you to the account chooser, because your details are already cached, if you need to go to the account choose again, you can delete your local cookies in the browser, so that it will take you to the account chooser again.


    How to configure RabbitMQ to use more memory and disk space




    1. move default rabbitmq home directory ( /var/lib/rabbitmq ) into EBS volume, i.e /opt/dm/rabbitmq

    2. Create a symlink like /var/lib/rabbitmq pointing to /opt/dm/rabbitmq, This will instruct rabbitMQ to use EBS disk space instead of root space ( ln -s /opt/dm/rabbitmq /var/lib/rabbitmq)

    3. Add the below configs(highlighted in green) inside the  /etc/rabbitmq/rabbitmq.conf. it specifies max memory thresholds and minimum disk space 
    thresholds to trigger flow controls not to accept connections. We have set those to 100GB and 100B respectively not to trigger flow controls unless it really needs to.

    [
      {kernel, [

      ]},
      {rabbit, [
        {tcp_listen_options, [binary, {packet,raw},
                                      {reuseaddr,true},
                                      {backlog,128},
                                      {nodelay,true},
                                      {exit_on_close,false},
                                      {keepalive,false}]},
        {default_user, <<"guest">>},
        {default_pass, <<"guest">>},
        {vm_memory_high_watermark, 100},
        {disk_free_limit, 100}
      ]}
    ].


    4. Restart the rabbitmq : /etc/init.d/rabbitmq-server stop
                                        /etc/init.d/rabbitmq-server start


    5. Enable rabbitmq management plugin : /usr/lib/rabbitmq/bin/rabbitmq-plugins enable rabbitmq_management

    6. Need to make sure we can access rabbitmq management console on port 55672 for quick queue lookups.


    Sunday, December 22, 2013

    How to create your own Maven Repository in Git hub

    First you need to have a repository created in Github, I assume you already have it and I will use maven-repo as the repository name as an example.

    Clone the empty repository to your home directory or what ever location you prefer.

     git clone https://github.com/Harsha/maven-repo.git maven-repo  
    

    my local repository path is /home/harsha/maven-repo

    Inside your project which you would like to share jar files in maven-repo define maven deployment plugin as below in pom.xml.

     <distributionManagement>  
      <repository>  
       <id>internal.repo</id>  
       <name>Internal Repository</name>  
       <url>${internal.repo.path}</url>  
      </repository>  
     </distributionManagement>  
    


    Then you need to define below properties for the jar file. Important point is
     <internal.repo.path>  
    
    which should points to your local repository which you get cloned above.

     <groupId>com.harsha.company.project</groupId>  
     <artifactId>module-name</artifactId>  
     <packaging>jar</packaging>
     <version>1.0</version>
     <properties>  
               <internal.repo.path>file:/home/harsha/maven-repo/</internal.repo.path>  
     </properties>  
    

    Now you can do
     mvn deploy  
    
    inside your project. It will create all the artifacts and publish to the local maven repository which you get cloned above.

    Now you can see all the artifacts are published in your local repository - /home/harsha/maven-repo. Just commit these changes and pushed to the git-hub.

    How to download published jars from the repository.

    Use below repository to download dependencies from your repository.

     <repositories>  
               <repository>  
                    <id>maven-repo</id>  
                    <url>https://github.com/Harsha/maven-repo/raw/master</url>  
               </repository>  
     </repositories>  
    


     <dependency>  
          <groupId>com.harsha.company.project</groupId>  
          <artifactId>module-name</artifactId>  
          <version>1.0</version>  
     </dependency>  
    


    You have successfully created your own repository from which others can download dependecies etc.



    2. If it is a Play project
    ======================

    To publish your project jar files inside Maven-repo issue the below command first inside your play application. This is not the best way to do it, but it is a pretty smart hack.

    play publish-local

    This will publish your jars into the local play repository located inside your play installation.
    Go to that directory and find the jar file which you need to publish into the maven-repo.

    Install this jar file manually into your local maven repository using the below command.

    mvn install:install-file -Dfile= -DgroupId=com.redmart.sso.integration -DartifactId=sso-integration -Dversion=1.0 -Dpackaging=jar



    This will install your jar into .m2/repository. Go to that directory and copy the com directory into your local maven-repo which you get cloned from Github. If you already have many artifacts inside com directory, make sure only to copy redmart directory.

    You are done and just commit and push your changes in maven-repo

    To make that jars as a dependency inside your play project add below lines to your Build.scala



    i.e
    ” %  “” % “
    "com.redmart.sso.integration"   %  "sso-integration" % "1.0"

    Add the below repository.

    resolvers += "maven-repo" at "https://github.com/Redmart/maven-repo/raw/master/",



    You are done !


    Saturday, June 13, 2009

    How to access Axis IP Camera using Java

    What is an IP Camera?

    An IP Camera is a stand-alone device which allows you to view live, full motion video from anywhere in the world. IP Cameras can be used for surveillance of both homes and businesses. With the ability to record live video to a remote location, IP Cameras allow you to make sure your recorded video is safe by storing it at a location that only you can access.



    This was indeed a challenge for me at the first time. But with mere investigation i could find that before accessing the IP camera we need to obtain authentication as it is working as a video server. I would list out what i did to capture a video stream from IP camera

    Step1 : obtaining the IP address of the camera (it will get assigned an available ip address from the network as it is configured upon DHCP by default) . You can use the utility software provided by the camera provider in case of finding the ip.

    Step2 : You may need to configure the axis camera giving a password for the default "root" user. If you want you may add many users as you wish using their utility software.

    Step3 : Then you can go to the URL of the camera and make sure the JPG or MJPG streams are there.

    Step4 : Next challenge was to obain authentication from the video server of the camera using Java code snippet. In that case i used java.net.Authenticator. Authenticator would consist of the URL , username and password which we are providing for the server.Then setDefault(Authenticator a) Sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

    Step5 : Now you are successfully connected to the Camera. :)

    Step6 : Then you can use the video stream from the IP camera for whatever application you use.







    Tuesday, May 19, 2009

    How to configure a Star Printer (TSP 800)

    This POS printer provides a solution to a number of applications where no POS printer was able to before. From compact web printing to mobile transportation printing as well as producing wide high-quality POS receipts with professional and crisp graphics, the TSP800 is the solution!

    The TSP800 is the only printer on the market that provides printing on 3” to 4.4” wide paper at an amazing speed. It is the perfect printer for applications that need to print a large amount of information on a receipt



    1) First identify the interface of the printer, my one is having Eathernet Interface.

    2) Accordingly you may guess how you would connect your printer. e.g : If it is having an USB interface it may be directly connected to the computer. If Eathernet interface it would be connected to a Network add as a Network printer (TCP/IP).

    Below i asssume the printer as TSP800 Star Printer having Eathernet Interface.

    3) Before adding your printer as a network printer you have to find out the IP address of the printer. Most of the printers at the first time are configured upon DHCP , so it may assign an IP for itself dynamically. For proper and ease of use you have to assign a static IP for the printer.

    4) In case of finding the dynamically assigned IP address of the printer , the only way you have to follow is printing the self test page which would contain each and every information of the printer statistics. (Note: when you take a self test page just press the feed button once just as you turn on the printer, do not press consequently as it may lead to some problems. While printing it may suspend in the middle, do not think it as a problem, it is because of the time taken to identify information of the network card in built to the printer)

    5) Now you can go to the printer interface (web page) using the IP found in the test page. (http://ip of the printer) . This will led to access the system access interface of the printer in case of assigning a static IP

    6) Use defauld username and password as in your test page. otherwise (root , public). This would carry you to the system access interface. There you can assign a static IP to the printer.

    7) You are almost done : Now add the printer as a TCP/IP printer.How to add your printer as a TCP/IP printer is listed here http://www.tamu-commerce.edu/ctis/help/tcpipprinter/default.htm. Note: use the ip address you assigned in step 8. Port would be assigned automatically.

    8) Print a test page to test your printer. You are done :)

    Saturday, March 29, 2008

    Harshajith Halgaswatta

    /GSoC:2008 - Proposal

    Google Summer of Code 2008 Proposal

    Subject

    Review Application

    Author

    Harshajith Halgaswatta

    Email

    harsha.halgaswatta@gmail.com

    Project Title

    Review Application

    Abstract

    XWiki is a generic wiki platform allowing the development of collaborative applications. It includes a toolkit for the web, supporting a cost-effective solution that allows non-developers to create those required applications quickly and in an organic manner. If one application remain as it is from the orientation and no way to give feed backs regarding to those documents or comments on it, its worth and usability may degrade because it is not updating in a regular manner.

    Hence the intention of this project is to give the facility to add reviews (add comments, highlight text, delete text, insert text, with an interface like the one in Adobe Acrobat Professional). Further it gives a way to anchoring reviews without messing with previous reviews. Eventually the authors of document may do required changes according to the reviews.

    Deliverables

    1. Implementation of Review Application (Client portion and author’s portion)

    2. Tests for Review Application according to its adjectives

    3. Documentation to support continuation of the project

    Overview

    People once read it and move off if it contain some useless things or it does not include what essentially should be there. Therefore if there is a way to update documents and particular stuff in an easy way according to the reviews of web viewers it will help the authors and the proprietors to remain their web viewers in a stable level.

    Therefore this project supposes to provide a review application which leads to add reviews just by clicking on the particular spot of a page and add their reviews. It may be a cumulative or standalone mode. Further it may beneficial giving the chances to view reviews not only by the document author but also the other viewers. Eventually it support a vital pros in point of authors view that they are in a position to edit, delete , remove highlights and comments of reviewers and make changes appropriately just by clicking once.

    I hope to develop this project dividing into two modules.

    • First module is the client portion which is indeed giving the facility to add reviews (feedback or comment on the read only document) for a particular document. Also it will support a way for the reviewed data to be anchored, so that later edits won't mess all the reviews.

    • Second module is the Author’s portion .The author can view such a review (or all of them together) and:

    • easily apply "delete" and "insert" changes with one click.

    • easily remove the comments and highlights.

    • while being able to also edit the document.

    Project Plan

    I have broken down the project under 4 steps as follows.

    Step1: Initial Planning and Designing

    I would look into the current implementation of Xwiki under this step(velocity and groovy). It would be very important to plan and design how I reach towards predefined objectives. Eventually I would have the skeleton of the implementation.

    Estimated Completion: 26th May 2008

    Step2: Implementation

    The real logic for client and author portion of review application would take into accounts and starts implementation.

    Deliverable(s): Prototype and documentation for mid evaluation Estimated Completion: 2nd July 2008

    Step3: Modifications and Tests

    Modifications or improvements suggested at the mid evaluation would be completed in this step.

    Deliverable(s): Prototype including tests Estimated Completion: 6th August 2008

    Step4: Final Product and Documents

    This step would complete the Review Application. Necessary documents would also be present with the final product.

    Deliverable(s): Final product and documentation Estimated Completion: 1st September 2008.

    Biography

    I’m a level 3 undergraduate of the Department of Computer Science & Engineering of the University of Moratuwa, Sri Lanka. I have participated in some Open Source development.

    During my internship I have implemented a member section from the scratch for E-channeling private Ltd, which is the market leader of online channel booking system and first listed company in Colombo stock exchange in Sri Lanka. I implemented the whole member section which included member usage module and member administration module using java upon STRUTS2 framework with Sun Application Server and ORACLE database server. Further I used some XML stuff in case of merchant integration for the site.

    I have implemented a managements system for an Internet cafe as my level 3 programming project module at the university. It covered many areas of JAVA (Swing toolkit, Java Network programming, jdic integration, java and XML, Java mail API).I used MySql server in case of this project.

    I’m really passionate in java and some web frameworks such as Struts2 and Spring. Thus I found this project really appealing as it lies on the path of my experience. I believe that I have the necessary background knowledge to make this a success. Eventually I hope that my involvement in this project would polish my software engineering skills whilst adding a whole new experience to my career.

    Mentor Information

    Sergiu Dumitriu, Marta Girdea

    References

    http://www. xwiki/article.tss.html

    http://www. Xwiki/SecondGenerationWiki.htm

    http://xwiki/DataModel.htm1

    http://www.echannelling.com

    http://www.cse.mrt.ac.lk