Search in sources :

Example 6 with User

use of io.bastillion.manage.model.User in project KeyBox by skavanagh.

the class AuthDB method getUserByUID.

/**
 * returns user base on username
 *
 * @param con DB connection
 * @param uid username id
 * @return user object
 */
public static User getUserByUID(Connection con, String uid) throws SQLException {
    User user = null;
    PreparedStatement stmt = con.prepareStatement("select * from  users where lower(username) like lower(?)");
    stmt.setString(1, uid);
    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
        user = new User();
        user.setId(rs.getLong("id"));
        user.setFirstNm(rs.getString("first_nm"));
        user.setLastNm(rs.getString("last_nm"));
        user.setEmail(rs.getString("email"));
        user.setUsername(rs.getString("username"));
        user.setUserType(rs.getString("user_type"));
        user.setLastLoginTm(rs.getTimestamp("last_login_tm"));
        user.setExpirationTm(rs.getTimestamp("expiration_tm"));
        user.setExpired(EXPIRATION_DAYS > 0 && user.getExpirationTm() != null && user.getExpirationTm().before(new Date()));
        user.setProfileList(UserProfileDB.getProfilesByUser(con, user.getId()));
    }
    DBUtils.closeRs(rs);
    DBUtils.closeStmt(stmt);
    return user;
}
Also used : User(io.bastillion.manage.model.User) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Date(java.util.Date)

Example 7 with User

use of io.bastillion.manage.model.User in project KeyBox by skavanagh.

the class ExternalAuthUtil method login.

/**
 * external auth login method
 *
 * @return auth token if success
 * @auth authentication credentials
 */
public static String login(final Auth auth) {
    Connection con = null;
    String authToken = null;
    if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername()) && StringUtils.isNotEmpty(auth.getPassword())) {
        try {
            // create login context
            LoginContext loginContext = new LoginContext(JAAS_MODULE, new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(auth.getUsername());
                        } else if (callback instanceof ObjectCallback) {
                            ((ObjectCallback) callback).setObject(auth.getPassword().toCharArray());
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray());
                        }
                    }
                }
            });
            // will throw exception if login fail
            loginContext.login();
            con = DBUtils.getConn();
            User user = AuthDB.getUserByUID(con, auth.getUsername());
            Field field = LoginContext.class.getDeclaredField("moduleStack");
            field.setAccessible(true);
            Object[] modules = (Object[]) field.get(loginContext);
            for (Object entry : modules) {
                field = entry.getClass().getDeclaredField("module");
                field.setAccessible(true);
                Object module = field.get(entry);
                field = entry.getClass().getDeclaredField("entry");
                field.setAccessible(true);
                AppConfigurationEntry appEntry = (AppConfigurationEntry) field.get(entry);
                if (module instanceof LdapLoginModule) {
                    // get callback handler
                    field = LoginContext.class.getDeclaredField("callbackHandler");
                    field.setAccessible(true);
                    CallbackHandler callbackHandler = (CallbackHandler) field.get(loginContext);
                    // get state
                    field = LoginContext.class.getDeclaredField("state");
                    field.setAccessible(true);
                    Map state = (Map) field.get(loginContext);
                    LdapLoginModule loginModule = (LdapLoginModule) module;
                    loginModule.initialize(loginContext.getSubject(), callbackHandler, state, appEntry.getOptions());
                    UserInfo userInfo = loginModule.getUserInfo(auth.getUsername());
                    // fetch assigned roles
                    userInfo.fetchRoles();
                    // dir context context
                    field = loginModule.getClass().getDeclaredField("_rootContext");
                    field.setAccessible(true);
                    DirContext dirContext = (DirContext) field.get(loginModule);
                    // role name attribute
                    field = loginModule.getClass().getDeclaredField("_roleNameAttribute");
                    field.setAccessible(true);
                    String roleNameAttribute = (String) field.get(loginModule);
                    // base dn for role
                    field = loginModule.getClass().getDeclaredField("_roleBaseDn");
                    field.setAccessible(true);
                    String roleBaseDn = (String) field.get(loginModule);
                    // role object class
                    field = loginModule.getClass().getDeclaredField("_roleObjectClass");
                    field.setAccessible(true);
                    String roleObjectClass = (String) field.get(loginModule);
                    // all attributes for user
                    field = LdapLoginModule.LDAPUserInfo.class.getDeclaredField("attributes");
                    field.setAccessible(true);
                    Attributes userAttributes = (Attributes) field.get(userInfo);
                    List<String> allRoles = getAllRoles(dirContext, roleBaseDn, roleNameAttribute, roleObjectClass);
                    if (user == null) {
                        user = new User();
                        user.setUserType(User.ADMINISTRATOR);
                        user.setUsername(auth.getUsername());
                        // set attributes from ldap
                        String givenName = userAttributes.get("givenName") != null ? (String) userAttributes.get("givenName").get() : null;
                        String sn = userAttributes.get("sn") != null ? (String) userAttributes.get("sn").get() : null;
                        String displayName = userAttributes.get("displayName") != null ? (String) userAttributes.get("displayName").get() : null;
                        String cn = userAttributes.get("cn") != null ? (String) userAttributes.get("cn").get() : null;
                        String email = userAttributes.get("mail") != null ? (String) userAttributes.get("mail").get() : null;
                        if (StringUtils.isNotEmpty(givenName) && StringUtils.isNotEmpty(sn)) {
                            user.setFirstNm(givenName);
                            user.setLastNm(sn);
                        } else if (StringUtils.isNotEmpty(displayName) && displayName.contains(" ")) {
                            String[] name = displayName.split(" ");
                            if (name.length > 1) {
                                user.setFirstNm(name[0]);
                                user.setLastNm(name[name.length - 1]);
                            }
                        } else if (StringUtils.isNotEmpty(cn) && cn.contains(" ")) {
                            String[] name = cn.split(" ");
                            if (name.length > 1) {
                                user.setFirstNm(name[0]);
                                user.setLastNm(name[name.length - 1]);
                            }
                        }
                        // set email
                        if (StringUtils.isNotEmpty(email)) {
                            user.setEmail(email);
                        } else if (auth.getUsername().contains("@")) {
                            user.setEmail(auth.getUsername());
                        }
                        user.setId(UserDB.insertUser(con, user));
                    }
                    // assign profiles for user
                    UserProfileDB.assignProfilesToUser(con, user.getId(), allRoles, userInfo.getRoleNames());
                    dirContext.close();
                    loginModule.commit();
                } else {
                    Subject subject = loginContext.getSubject();
                    if (user == null) {
                        user = new User();
                        user.setUserType(User.ADMINISTRATOR);
                        user.setUsername(auth.getUsername());
                        // if it looks like name is returned default it
                        for (Principal p : subject.getPrincipals()) {
                            if (p.getName().contains(" ")) {
                                String[] name = p.getName().split(" ");
                                if (name.length > 1) {
                                    user.setFirstNm(name[0]);
                                    user.setLastNm(name[name.length - 1]);
                                }
                            }
                        }
                        // set email
                        if (auth.getUsername().contains("@")) {
                            user.setEmail(auth.getUsername());
                        }
                        user.setId(UserDB.insertUser(con, user));
                    }
                }
                if (StringUtils.isNotEmpty(DEFAULT_LDAP_PROFILE)) {
                    UserProfileDB.assignProfileToUser(con, user.getId(), DEFAULT_LDAP_PROFILE);
                }
                authToken = UUID.randomUUID().toString();
                user.setAuthToken(authToken);
                user.setAuthType(Auth.AUTH_EXTERNAL);
                // set auth token
                AuthDB.updateLogin(con, user);
            }
            DBUtils.closeConn(con);
        } catch (LoginException le) {
            authToken = null;
            log.debug(le.toString(), le);
        } catch (Exception ex) {
            authToken = null;
            log.error(ex.toString(), ex);
        }
    }
    return authToken;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) User(io.bastillion.manage.model.User) Attributes(javax.naming.directory.Attributes) UserInfo(org.eclipse.jetty.jaas.spi.UserInfo) DirContext(javax.naming.directory.DirContext) LdapLoginModule(org.eclipse.jetty.jaas.spi.LdapLoginModule) Field(java.lang.reflect.Field) LoginContext(javax.security.auth.login.LoginContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) Connection(java.sql.Connection) IOException(java.io.IOException) Subject(javax.security.auth.Subject) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) NamingException(javax.naming.NamingException) IOException(java.io.IOException) AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginException(javax.security.auth.login.LoginException) Map(java.util.Map) Principal(java.security.Principal)

Example 8 with User

use of io.bastillion.manage.model.User in project Bastillion by bastillion-io.

the class ExternalAuthUtil method login.

/**
 * external auth login method
 *
 * @return auth token if success
 * @auth authentication credentials
 */
public static String login(final Auth auth) {
    Connection con = null;
    String authToken = null;
    if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername()) && StringUtils.isNotEmpty(auth.getPassword())) {
        try {
            // create login context
            LoginContext loginContext = new LoginContext(JAAS_MODULE, new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(auth.getUsername());
                        } else if (callback instanceof ObjectCallback) {
                            ((ObjectCallback) callback).setObject(auth.getPassword().toCharArray());
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray());
                        }
                    }
                }
            });
            // will throw exception if login fail
            loginContext.login();
            con = DBUtils.getConn();
            User user = AuthDB.getUserByUID(con, auth.getUsername());
            Field field = LoginContext.class.getDeclaredField("moduleStack");
            field.setAccessible(true);
            Object[] modules = (Object[]) field.get(loginContext);
            for (Object entry : modules) {
                field = entry.getClass().getDeclaredField("module");
                field.setAccessible(true);
                Object module = field.get(entry);
                field = entry.getClass().getDeclaredField("entry");
                field.setAccessible(true);
                AppConfigurationEntry appEntry = (AppConfigurationEntry) field.get(entry);
                if (module instanceof LdapLoginModule) {
                    // get callback handler
                    field = LoginContext.class.getDeclaredField("callbackHandler");
                    field.setAccessible(true);
                    CallbackHandler callbackHandler = (CallbackHandler) field.get(loginContext);
                    // get state
                    field = LoginContext.class.getDeclaredField("state");
                    field.setAccessible(true);
                    Map state = (Map) field.get(loginContext);
                    LdapLoginModule loginModule = (LdapLoginModule) module;
                    loginModule.initialize(loginContext.getSubject(), callbackHandler, state, appEntry.getOptions());
                    UserInfo userInfo = loginModule.getUserInfo(auth.getUsername());
                    // fetch assigned roles
                    userInfo.fetchRoles();
                    // dir context context
                    field = loginModule.getClass().getDeclaredField("_rootContext");
                    field.setAccessible(true);
                    DirContext dirContext = (DirContext) field.get(loginModule);
                    // role name attribute
                    field = loginModule.getClass().getDeclaredField("_roleNameAttribute");
                    field.setAccessible(true);
                    String roleNameAttribute = (String) field.get(loginModule);
                    // base dn for role
                    field = loginModule.getClass().getDeclaredField("_roleBaseDn");
                    field.setAccessible(true);
                    String roleBaseDn = (String) field.get(loginModule);
                    // role object class
                    field = loginModule.getClass().getDeclaredField("_roleObjectClass");
                    field.setAccessible(true);
                    String roleObjectClass = (String) field.get(loginModule);
                    // all attributes for user
                    field = LdapLoginModule.LDAPUserInfo.class.getDeclaredField("attributes");
                    field.setAccessible(true);
                    Attributes userAttributes = (Attributes) field.get(userInfo);
                    List<String> allRoles = getAllRoles(dirContext, roleBaseDn, roleNameAttribute, roleObjectClass);
                    if (user == null) {
                        user = new User();
                        user.setUserType(User.ADMINISTRATOR);
                        user.setUsername(auth.getUsername());
                        // set attributes from ldap
                        String givenName = userAttributes.get("givenName") != null ? (String) userAttributes.get("givenName").get() : null;
                        String sn = userAttributes.get("sn") != null ? (String) userAttributes.get("sn").get() : null;
                        String displayName = userAttributes.get("displayName") != null ? (String) userAttributes.get("displayName").get() : null;
                        String cn = userAttributes.get("cn") != null ? (String) userAttributes.get("cn").get() : null;
                        String email = userAttributes.get("mail") != null ? (String) userAttributes.get("mail").get() : null;
                        if (StringUtils.isNotEmpty(givenName) && StringUtils.isNotEmpty(sn)) {
                            user.setFirstNm(givenName);
                            user.setLastNm(sn);
                        } else if (StringUtils.isNotEmpty(displayName) && displayName.contains(" ")) {
                            String[] name = displayName.split(" ");
                            if (name.length > 1) {
                                user.setFirstNm(name[0]);
                                user.setLastNm(name[name.length - 1]);
                            }
                        } else if (StringUtils.isNotEmpty(cn) && cn.contains(" ")) {
                            String[] name = cn.split(" ");
                            if (name.length > 1) {
                                user.setFirstNm(name[0]);
                                user.setLastNm(name[name.length - 1]);
                            }
                        }
                        // set email
                        if (StringUtils.isNotEmpty(email)) {
                            user.setEmail(email);
                        } else if (auth.getUsername().contains("@")) {
                            user.setEmail(auth.getUsername());
                        }
                        user.setId(UserDB.insertUser(con, user));
                    }
                    // assign profiles for user
                    UserProfileDB.assignProfilesToUser(con, user.getId(), allRoles, userInfo.getRoleNames());
                    dirContext.close();
                    loginModule.commit();
                } else {
                    Subject subject = loginContext.getSubject();
                    if (user == null) {
                        user = new User();
                        user.setUserType(User.ADMINISTRATOR);
                        user.setUsername(auth.getUsername());
                        // if it looks like name is returned default it
                        for (Principal p : subject.getPrincipals()) {
                            if (p.getName().contains(" ")) {
                                String[] name = p.getName().split(" ");
                                if (name.length > 1) {
                                    user.setFirstNm(name[0]);
                                    user.setLastNm(name[name.length - 1]);
                                }
                            }
                        }
                        // set email
                        if (auth.getUsername().contains("@")) {
                            user.setEmail(auth.getUsername());
                        }
                        user.setId(UserDB.insertUser(con, user));
                    }
                }
                if (StringUtils.isNotEmpty(DEFAULT_LDAP_PROFILE)) {
                    UserProfileDB.assignProfileToUser(con, user.getId(), DEFAULT_LDAP_PROFILE);
                }
                authToken = UUID.randomUUID().toString();
                user.setAuthToken(authToken);
                user.setAuthType(Auth.AUTH_EXTERNAL);
                // set auth token
                AuthDB.updateLogin(con, user);
            }
            DBUtils.closeConn(con);
        } catch (LoginException le) {
            authToken = null;
            log.debug(le.toString(), le);
        } catch (Exception ex) {
            authToken = null;
            log.error(ex.toString(), ex);
        }
    }
    return authToken;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) User(io.bastillion.manage.model.User) Attributes(javax.naming.directory.Attributes) UserInfo(org.eclipse.jetty.jaas.spi.UserInfo) DirContext(javax.naming.directory.DirContext) LdapLoginModule(org.eclipse.jetty.jaas.spi.LdapLoginModule) Field(java.lang.reflect.Field) LoginContext(javax.security.auth.login.LoginContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) Connection(java.sql.Connection) IOException(java.io.IOException) Subject(javax.security.auth.Subject) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) NamingException(javax.naming.NamingException) IOException(java.io.IOException) AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginException(javax.security.auth.login.LoginException) Map(java.util.Map) Principal(java.security.Principal)

Example 9 with User

use of io.bastillion.manage.model.User in project Bastillion by bastillion-io.

the class AuthDB method getUserByAuthToken.

/**
 * returns user id based on auth token
 *
 * @param authToken auth token
 * @param con       DB connection
 * @return user
 */
public static User getUserByAuthToken(Connection con, String authToken) throws SQLException {
    User user = null;
    PreparedStatement stmt = con.prepareStatement("select * from users where auth_token like ?");
    stmt.setString(1, authToken);
    ResultSet rs = stmt.executeQuery();
    if (rs.next()) {
        Long userId = rs.getLong("id");
        user = UserDB.getUser(con, userId);
    }
    DBUtils.closeRs(rs);
    DBUtils.closeStmt(stmt);
    return user;
}
Also used : User(io.bastillion.manage.model.User) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 10 with User

use of io.bastillion.manage.model.User in project Bastillion by bastillion-io.

the class UserDB method getAdminUserSet.

/**
 * returns all admin users based on sort order defined
 *
 * @param sortedSet object that defines sort order
 * @return sorted user list
 * @profileId check if user is apart of given profile
 */
public static SortedSet getAdminUserSet(SortedSet sortedSet, Long profileId) throws SQLException, GeneralSecurityException {
    ArrayList<User> userList = new ArrayList<>();
    String orderBy = "";
    if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
        orderBy = "order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
    }
    String sql = "select u.*, m.profile_id from users u left join user_map  m on m.user_id = u.id and m.profile_id = ? where u.user_type like '" + User.ADMINISTRATOR + "'" + orderBy;
    Connection con = DBUtils.getConn();
    PreparedStatement stmt = con.prepareStatement(sql);
    stmt.setLong(1, profileId);
    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
        User user = new User();
        user.setId(rs.getLong("id"));
        user.setFirstNm(rs.getString(FIRST_NM));
        user.setLastNm(rs.getString(LAST_NM));
        user.setEmail(rs.getString(EMAIL));
        user.setUsername(rs.getString(USERNAME));
        user.setPassword(rs.getString(PASSWORD));
        user.setAuthType(rs.getString(AUTH_TYPE));
        user.setUserType(rs.getString(USER_TYPE));
        user.setLastLoginTm(rs.getTimestamp(LAST_LOGIN_TM));
        user.setExpirationTm(rs.getTimestamp(EXPIRATION_TM));
        user.setExpired(EXPIRATION_DAYS > 0 && user.getExpirationTm() != null && user.getExpirationTm().before(new Date()));
        user.setChecked(profileId.equals(rs.getLong(PROFILE_ID)));
        userList.add(user);
    }
    DBUtils.closeRs(rs);
    DBUtils.closeStmt(stmt);
    DBUtils.closeConn(con);
    sortedSet.setItemList(userList);
    return sortedSet;
}
Also used : User(io.bastillion.manage.model.User) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Date(java.util.Date)

Aggregations

User (io.bastillion.manage.model.User)20 Connection (java.sql.Connection)10 PreparedStatement (java.sql.PreparedStatement)10 ResultSet (java.sql.ResultSet)10 Date (java.util.Date)8 GeneralSecurityException (java.security.GeneralSecurityException)4 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 ServletException (javax.servlet.ServletException)4 Kontrol (loophole.mvc.annotation.Kontrol)4 IOException (java.io.IOException)2 Field (java.lang.reflect.Field)2 Principal (java.security.Principal)2 Map (java.util.Map)2 NamingException (javax.naming.NamingException)2 Attributes (javax.naming.directory.Attributes)2 DirContext (javax.naming.directory.DirContext)2 Subject (javax.security.auth.Subject)2 Callback (javax.security.auth.callback.Callback)2 CallbackHandler (javax.security.auth.callback.CallbackHandler)2