openejb jpa jaas module

#1

hello , i've finished jpa jaas module.

Here it is :

package com.bayner.auth;

import com.bayner.jpa.Principals;
import com.bayner.jpa.UserInfo;
import com.bayner.jpa.UserPrincipal;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import java.io.IOException;
import java.security.Principal;
import java.util.*;

/**
* Created with IntelliJ IDEA.
* User: apple
* Date: 31.01.2013
* Time: 06:01
* To change this template use File | Settings | File Templates.
*/
public class JPALoginModule implements LoginModule {

    private Subject                 subject;
    private CallbackHandler         callbackHandler;
    private EntityManagerFactory    entityManagerFactory;
    private EntityManager           entityManager;
    protected Map<String, ?>        sharedState = new HashMap<String, Object>();
    private String                  username;
    private char[]                  password;
    private Map                     options;
    /**
     * User.
     */
    protected String                login;
    /**
     * Password.
     */
    protected String                pass;

    private boolean                 succeeded;
    private UserInfo                info;

    @Override
    public final void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
        //To change body of implemented methods use File | Settings | File Templates.
        // TODO Auto-generated method stub
        this.subject = subject;
        this.callbackHandler = callbackHandler;
        this.sharedState = sharedState;
        this.options = options;

        final Properties properties = new Properties();
        properties.put("javax.persistence.jdbc.user",options.get("user"));
        properties.put("javax.persistence.jdbc.password", options.get("password") );
        //objectdb://localhost:6136/myDbFile.odb

        entityManagerFactory = Persistence.createEntityManagerFactory((String) options.get("url"));
        entityManager = entityManagerFactory.createEntityManager( );
    }

    /**
           * Attempt authentication
           *
           * <p>
           *
           * @param getPasswdFromSharedState boolean that tells this method whether
           *                to retrieve the password from the sharedState.
    */
    private final void attemptAuthentication(boolean getPasswdFromSharedState) throws LoginException {

    }

    @Override
    public final boolean login() throws LoginException {
        try {
            getUsernamePassword();
            try {

                info = entityManager.find( UserInfo.class , username );
                if(info != null) {
                    String password = info.getPassword();
                    if(password.equals(pass)) {
                        succeeded = true;
                        return true;
                    } else {
                        succeeded = false;
                        return false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            succeeded = true;
            //Principals and Credentials
        } catch (UnsupportedCallbackException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            succeeded = false;
            return false;
        }


        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public final boolean commit() throws LoginException {
        if (succeeded == false) {
            return false;
        } else {
            final Set<Principal> principals = subject.getPrincipals();
            final int id = info.getId();
            final TypedQuery<UserPrincipal> namedQuery = entityManager.createNamedQuery("UserPrincipal.findAll", UserPrincipal.class);
            List<UserPrincipal> resultList = namedQuery.getResultList();
            for (UserPrincipal userPrincipal : resultList) {
                final int principalId = userPrincipal.getPrincipalId();
                final Principals principals1 = entityManager.find(Principals.class, principalId);
                subject.getPrincipals().add(principals1);
            }
        }
        return true;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public final boolean abort() throws LoginException {
        final Set<Principal> principals = subject.getPrincipals();
        if (principals != null) {
            principals.clear();
        }
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public final boolean logout() throws LoginException {
        final Set<Principal> principals = subject.getPrincipals();
        principals.clear();
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }


    protected final void getUsernamePassword() throws LoginException, UnsupportedCallbackException {
        if (callbackHandler == null)
            throw new LoginException("Error: no CallbackHandler available to garner authentication information from the user");

        final Callback[] callbacks = new Callback[2];
        callbacks[0] = new NameCallback(null);
        callbacks[1] = new PasswordCallback(null, false);

        try {
            callbackHandler.handle(callbacks);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        login = ((NameCallback) callbacks[0]).getName();
        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        pass = new String(tmpPassword);
        ((PasswordCallback) callbacks[1]).clearPassword();
    }
}





package com.bayner.jpa;

import javax.persistence.*;
import java.io.Serializable;
import java.security.Principal;

/**
* Created with IntelliJ IDEA.
* User: apple
* Date: 02.02.2013
* Time: 23:15
* To change this template use File | Settings | File Templates.
*/
@Cacheable
@Entity
@SequenceGenerator(
        name = "gen",
        initialValue = 10000,
        allocationSize = 50
)
public class Principals implements Serializable,Principal {

    private String principalName;

    @GeneratedValue(strategy = GenerationType.SEQUENCE , generator = "gen")
    @Id
    private int    principalId;

    public String getPrincipalName() {
        return principalName;
    }

    public void setPrincipalName(String principalName) {
        this.principalName = principalName;
    }

    public int getPrincipalId() {
        return principalId;
    }

    public void setPrincipalId(int principalId) {
        this.principalId = principalId;
    }

    @Override
    public String getName() {
        return principalName;  //To change body of implemented methods use File | Settings | File Templates.
    }
}




package com.bayner.jpa;

import network.data.Settings;

import javax.jdo.annotations.Index;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

/**
* Created with IntelliJ IDEA.
* User: apple
* Date: 27.01.2013
* Time: 02:30
* To change this template use File | Settings | File Templates.
*/

@Cacheable
@Entity
@SequenceGenerator(name="seq", initialValue=10000)
@NamedQueries({
        @NamedQuery(name = "UserInfo.setClientSettings",query = "update UserInfo ui set ui.settings= :settings") ,
        @NamedQuery(name = "UserInfo.setClientSettingsForUser",query = "update UserInfo ui set ui.settings= :settings where ui.user=:user"),
        @NamedQuery(name = "UserInfo.getClientSettings" , query = "select  ui.settings from UserInfo ui where ui.user=:user" ),
        @NamedQuery(name = "UserInfo.getByClientId" , query = "select  ui from UserInfo ui where ui.id = :id"),
        @NamedQuery(name = "UserInfo.getByMailAddress" , query = "select  ui from UserInfo ui where ui.mailAddress = :mail")
})
public class UserInfo implements Serializable {
    @GeneratedValue(strategy = GenerationType.AUTO,generator = "seq")
    @Index
    private int      id;

    @Id
    private String   user;
    private String   password;

    @Index
    private String   mailAddress;


    @OneToOne
    private Settings settings;

    private String   phoneNumber;


    @OneToMany
    private List<UserPrincipal> principals;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMailAddress() {
        return mailAddress;
    }

    public void setMailAddress(String mailAddress) {
        this.mailAddress = mailAddress;
    }

    public Settings getSettings() {
        return settings;
    }

    public void setSettings(Settings settings) {
        this.settings = settings;
    }

    public List<UserPrincipal> getPrincipals() {
        return principals;
    }

    public void setPrincipals(List<UserPrincipal> principals) {
        this.principals = principals;
    }
}






package com.bayner.jpa;

import javax.jdo.annotations.Index;
import javax.persistence.*;
import java.io.Serializable;

/**
* Created with IntelliJ IDEA.
* User: apple
* Date: 02.02.2013
* Time: 23:09
* To change this template use File | Settings | File Templates.
*/
@Cacheable
@Entity
@NamedQueries(
        @NamedQuery(name = "UserPrincipal.findAll",query = "SELECT p from UserPrincipal p where p.userId=:id")
)
public class UserPrincipal implements Serializable {
    @Id
    private int userId;
    @Index
    private int principalId;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getPrincipalId() {
        return principalId;
    }

    public void setPrincipalId(int principalId) {
        this.principalId = principalId;
    }
}





package network.data;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.*;

/**
* Created with IntelliJ IDEA.
* User: apple
* Date: 24.01.2013
* Time: 03:13
* To change this template use File | Settings | File Templates.
*/
@Entity
public class Settings implements Serializable {

    private static final long       serialVersionUID = -7516039939801615889L;
    private transient static Settings         instance;

    public static Settings getInstance() {
        return instance;
    }

    public static final void init() {
        instance = new Settings();
    }

    private Settings() {
    }


    private String computerName;
    private String serverName;
    @Id
    private int    id;

    public String getComputerName() {
        return computerName;
    }

    public void setComputerName(String computerName) {
        this.computerName = computerName;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }


    public final void save() {
        try {
            final FileOutputStream fileOutputStream = new FileOutputStream( "settings.obj" );
            final ObjectOutputStream objectOutputStream = new ObjectOutputStream( fileOutputStream );
            objectOutputStream.writeObject( this );
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }


    public final void load() {
        try {
            final FileInputStream fileInputStream = new FileInputStream( "settings.obj" );
            final ObjectInputStream objectInputStream = new ObjectInputStream( fileInputStream );
            final Settings settings = (Settings) objectInputStream.readObject();
            setComputerName( settings.getComputerName() );
            setServerName( settings.getServerName() );
        } catch (Exception epx) {

        }
    }
}
#2

Thank you for sharing the module.

Any feedback from other users that try the module would be welcome.

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)

Post Reply

To post a reply and/or subscribe to update notifications - please login