Search in sources :

Example 6 with PersonImpl

use of org.apereo.portal.security.provider.PersonImpl in project uPortal by Jasig.

the class SubscribedFragmentImporterExporter method getPerson.

private IPerson getPerson(final String username, boolean create) {
    final IPerson person = new PersonImpl();
    person.setUserName(username);
    int userId;
    try {
        userId = this.userIdentityStore.getPortalUID(person);
    } catch (final Throwable t) {
        if (!create || this.errorOnMissingUser) {
            throw new RuntimeException("Unrecognized user " + person.getUserName() + "; you must import users before their layouts.", t);
        }
        userId = this.userIdentityStore.getPortalUID(person, true);
    }
    person.setID(userId);
    person.setSecurityContext(new BrokenSecurityContext());
    return person;
}
Also used : IPerson(org.apereo.portal.security.IPerson) PersonImpl(org.apereo.portal.security.provider.PersonImpl) BrokenSecurityContext(org.apereo.portal.security.provider.BrokenSecurityContext)

Example 7 with PersonImpl

use of org.apereo.portal.security.provider.PersonImpl in project uPortal by Jasig.

the class ServerNameGuestChainingProfileMapperTest method createPerson.

protected static IPerson createPerson() throws Exception {
    IPerson person = new PersonImpl();
    person.setAttribute(IPerson.USERNAME, "non_guest");
    return person;
}
Also used : IPerson(org.apereo.portal.security.IPerson) PersonImpl(org.apereo.portal.security.provider.PersonImpl)

Example 8 with PersonImpl

use of org.apereo.portal.security.provider.PersonImpl in project uPortal by Jasig.

the class RDBMDistributedLayoutStore method importLayout.

@Override
@SuppressWarnings("unchecked")
@Transactional
public void importLayout(org.dom4j.Element layout) {
    if (layout.getNamespaceForPrefix("dlm") == null) {
        layout.add(new Namespace("dlm", Constants.NS_URI));
    }
    //Remove comments from the DOM they break import
    final List<org.dom4j.Node> comments = layout.selectNodes("//comment()");
    for (final org.dom4j.Node comment : comments) {
        comment.detach();
    }
    //Get a ref to the prefs element and then remove it from the layout
    final org.dom4j.Node preferencesElement = layout.selectSingleNode("preferences");
    if (preferencesElement != null) {
        preferencesElement.getParent().remove(preferencesElement);
    }
    final String ownerUsername = layout.valueOf("@username");
    //Get a ref to the profile element and then remove it from the layout
    final org.dom4j.Node profileElement = layout.selectSingleNode("profile");
    if (profileElement != null) {
        profileElement.getParent().remove(profileElement);
        final org.dom4j.Document profileDocument = new org.dom4j.DocumentFactory().createDocument();
        profileDocument.setRootElement((org.dom4j.Element) profileElement);
        profileDocument.setName(ownerUsername + ".profile");
        final DocumentSource profileSource = new DocumentSource(profileElement);
        this.portalDataHandlerService.importData(profileSource);
    }
    final IPerson person = new PersonImpl();
    person.setUserName(ownerUsername);
    int ownerId;
    try {
        //Can't just pass true for create here, if the user actually exists the create flag also updates the user data
        ownerId = this.userIdentityStore.getPortalUID(person);
    } catch (final AuthorizationException t) {
        if (this.errorOnMissingUser) {
            throw new RuntimeException("Unrecognized user " + person.getUserName() + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.", t);
        }
        //Create the missing user
        ownerId = this.userIdentityStore.getPortalUID(person, true);
    }
    if (ownerId == -1) {
        throw new RuntimeException("Unrecognized user " + person.getUserName() + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.");
    }
    person.setID(ownerId);
    IUserProfile profile = null;
    try {
        person.setSecurityContext(new BrokenSecurityContext());
        profile = this.getUserProfileByFname(person, "default");
    } catch (final Throwable t) {
        throw new RuntimeException("Failed to load profile for " + person.getUserName() + "; This user must have a profile for import to continue.", t);
    }
    // (6) Add database Ids & (5) Add dlm:plfID ...
    int nextId = 1;
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("folder | dlm:* | channel").iterator(); it.hasNext(); ) {
        nextId = this.addIdAttributesIfNecessary(it.next(), nextId);
    }
    // Now update UP_USER...
    this.jdbcOperations.update("UPDATE up_user SET next_struct_id = ? WHERE user_id = ?", nextId, person.getID());
    // (4) Convert external DLM pathrefs to internal form (noderefs)...
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//@dlm:origin").iterator(); itr.hasNext(); ) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null, true, layout);
        if (dlmNoderef != null) {
            // Change the value only if we have a valid pathref...
            a.setValue(dlmNoderef.toString());
            // For dlm:origin only, also use the noderef as the ID attribute...
            a.getParent().addAttribute("ID", dlmNoderef.toString());
        } else {
            // At least insure the value is between 1 and 35 characters
            a.setValue(BAD_PATHREF_MESSAGE);
        }
    }
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//@dlm:target").iterator(); itr.hasNext(); ) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null, true, layout);
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//dlm:*/@name").iterator(); names.hasNext(); ) {
        final org.dom4j.Attribute a = names.next();
        final String value = a.getValue().trim();
        if (!VALID_PATHREF_PATTERN.matcher(value).matches()) {
            /* Don't send it to getDlmNoderef if we know in advance it's not
                 * going to work;  saves annoying/misleading log messages and
                 * possibly some processing.  NOTE this is _only_ a problem with
                 * the name attribute of some dlm:* elements, which seems to go
                 * unused intentionally in some circumstances
                 */
            continue;
        }
        final org.dom4j.Attribute fname = a.getParent().attribute("fname");
        Noderef dlmNoderef = null;
        if (fname != null) {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, fname.getValue(), false, layout);
            // Remove the fname attribute now that we're done w/ it...
            fname.getParent().remove(fname);
        } else {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, null, true, layout);
        }
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }
    // (3) Restore chanID attributes on <channel> elements...
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("//channel").iterator(); it.hasNext(); ) {
        final org.dom4j.Element c = it.next();
        final String fname = c.valueOf("@fname");
        final IPortletDefinition cd = this.portletDefinitionRegistry.getPortletDefinitionByFname(fname);
        if (cd == null) {
            final String msg = "No portlet with fname=" + fname + " exists referenced by node " + c.valueOf("@ID") + " from layout for " + ownerUsername;
            if (errorOnMissingPortlet) {
                throw new IllegalArgumentException(msg);
            } else {
                logger.warn(msg);
                //Remove the bad channel node
                c.getParent().remove(c);
            }
        } else {
            c.addAttribute("chanID", String.valueOf(cd.getPortletDefinitionId().getStringId()));
        }
    }
    // (2) Restore locale info...
    // (This step doesn't appear to be needed for imports)
    // (1) Process structure & theme attributes...
    Document layoutDom = null;
    try {
        final int structureStylesheetId = profile.getStructureStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, structureStylesheetId, "structure");
        final int themeStylesheetId = profile.getThemeStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, themeStylesheetId, "theme");
        // From this point forward we need the user's PLF set as DLM expects it...
        for (final Iterator<org.dom4j.Text> it = (Iterator<org.dom4j.Text>) layout.selectNodes("descendant::text()").iterator(); it.hasNext(); ) {
            // How many years have we used Java & XML, and this still isn't easy?
            final org.dom4j.Text txt = it.next();
            if (txt.getText().trim().length() == 0) {
                txt.getParent().remove(txt);
            }
        }
        final org.dom4j.Element copy = layout.createCopy();
        final org.dom4j.Document doc = this.fac.createDocument(copy);
        doc.normalize();
        layoutDom = this.writer.get().write(doc);
        person.setAttribute(Constants.PLF, layoutDom);
    } catch (final Throwable t) {
        throw new RuntimeException("Unable to set UserPreferences for user:  " + person.getUserName(), t);
    }
    // Finally store the layout...
    try {
        this.setUserLayout(person, profile, layoutDom, true, true);
    } catch (final Throwable t) {
        final String msg = "Unable to persist layout for user:  " + ownerUsername;
        throw new RuntimeException(msg, t);
    }
    if (preferencesElement != null) {
        final int ownerUserId = this.userIdentityStore.getPortalUserId(ownerUsername);
        //TODO this assumes a single layout, when multi-layout support exists portlet entities will need to be re-worked to allow for a layout id to be associated with the entity
        //track which entities from the user's pre-existing set are touched (all non-touched entities will be removed)
        final Set<IPortletEntity> oldPortletEntities = new LinkedHashSet<IPortletEntity>(this.portletEntityDao.getPortletEntitiesForUser(ownerUserId));
        final List<org.dom4j.Element> entries = preferencesElement.selectNodes("entry");
        for (final org.dom4j.Element entry : entries) {
            final String dlmPathRef = entry.attributeValue("entity");
            final String fname = entry.attributeValue("channel");
            final String prefName = entry.attributeValue("name");
            final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(person.getUserName(), dlmPathRef, fname, false, layout);
            if (dlmNoderef != null && fname != null) {
                final IPortletEntity portletEntity = this.getPortletEntity(fname, dlmNoderef.toString(), ownerUserId);
                oldPortletEntities.remove(portletEntity);
                final List<IPortletPreference> portletPreferences = portletEntity.getPortletPreferences();
                final List<org.dom4j.Element> valueElements = entry.selectNodes("value");
                final List<String> values = new ArrayList<String>(valueElements.size());
                for (final org.dom4j.Element valueElement : valueElements) {
                    values.add(valueElement.getText());
                }
                portletPreferences.add(new PortletPreferenceImpl(prefName, false, values.toArray(new String[values.size()])));
                this.portletEntityDao.updatePortletEntity(portletEntity);
            }
        }
        //Delete all portlet preferences for entities that were not imported
        for (final IPortletEntity portletEntity : oldPortletEntities) {
            portletEntity.setPortletPreferences(null);
            if (portletEntityRegistry.shouldBePersisted(portletEntity)) {
                this.portletEntityDao.updatePortletEntity(portletEntity);
            } else {
                this.portletEntityDao.deletePortletEntity(portletEntity);
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) IPortletPreference(org.apereo.portal.portlet.om.IPortletPreference) AuthorizationException(org.apereo.portal.AuthorizationException) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) IPerson(org.apereo.portal.security.IPerson) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity) Iterator(java.util.Iterator) PortletPreferenceImpl(org.apereo.portal.portlet.dao.jpa.PortletPreferenceImpl) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) Namespace(org.dom4j.Namespace) PersonImpl(org.apereo.portal.security.provider.PersonImpl) DocumentSource(org.dom4j.io.DocumentSource) IUserProfile(org.apereo.portal.IUserProfile) BrokenSecurityContext(org.apereo.portal.security.provider.BrokenSecurityContext) Transactional(org.springframework.transaction.annotation.Transactional)

Example 9 with PersonImpl

use of org.apereo.portal.security.provider.PersonImpl in project uPortal by Jasig.

the class RDBMUserLayoutStore method getUserProfileByFname.

public UserProfile getUserProfileByFname(final IPerson person, final String profileFname) {
    Tuple<String, String> key = null;
    final Cache<Tuple<String, String>, UserProfile> profileCache = getProfileImportExportCache();
    if (profileCache != null) {
        key = new Tuple<String, String>(person.getUserName(), profileFname);
        final UserProfile profile = profileCache.getIfPresent(key);
        if (profile != null) {
            return profile;
        }
    }
    logger.debug("Getting profile {} for user {}", profileFname, person.getID());
    final int userId = person.getID();
    final UserProfile userProfile = jdbcOperations.execute(new ConnectionCallback<UserProfile>() {

        @Override
        public UserProfile doInConnection(Connection con) throws SQLException, DataAccessException {
            String query = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, " + "LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE " + "USER_ID=? AND PROFILE_FNAME=?";
            PreparedStatement pstmt = con.prepareStatement(query);
            pstmt.setInt(1, userId);
            pstmt.setString(2, profileFname);
            try {
                logger.debug("getUserProfileByFname(): {} userId: {} profileFname: {}", query, userId, profileFname);
                ResultSet rs = pstmt.executeQuery();
                try {
                    if (rs.next()) {
                        int profileId = rs.getInt(2);
                        String profileName = rs.getString(3);
                        String profileDesc = rs.getString(4);
                        int layoutId = rs.getInt(5);
                        if (rs.wasNull()) {
                            layoutId = 0;
                        }
                        int structSsId = rs.getInt(6);
                        if (rs.wasNull()) {
                            // This is probably a data issue and probably an export operation;  defer to the system user...
                            if (!person.equals(getSystemUser())) {
                                structSsId = getSystemProfileByFname(profileFname).getStructureStylesheetId();
                            } else {
                                String msg = "The system user profile has no structure stylesheet Id.";
                                throw new IllegalStateException(msg);
                            }
                        }
                        int themeSsId = rs.getInt(7);
                        if (rs.wasNull()) {
                            // This is probably a data issue and probably an export operation;  defer to the system user...
                            if (!person.equals(getSystemUser())) {
                                themeSsId = getSystemProfileByFname(profileFname).getThemeStylesheetId();
                            } else {
                                String msg = "The system user profile has no theme stylesheet Id.";
                                throw new IllegalStateException(msg);
                            }
                        }
                        UserProfile userProfile = new UserProfile(profileId, profileFname, profileName, profileDesc, layoutId, structSsId, themeSsId);
                        final Locale[] userLocales = localeStore.getUserLocales(person);
                        userProfile.setLocaleManager(new LocaleManager(person, userLocales));
                        return userProfile;
                    }
                    /* Try to copy the template profile. */
                    logger.debug("Copying template profile {} to user {}", profileFname, person.getID());
                    rs.close();
                    pstmt.close();
                    pstmt = con.prepareStatement("SELECT USER_DFLT_USR_ID FROM UP_USER WHERE USER_ID=?");
                    pstmt.setInt(1, person.getID());
                    rs = pstmt.executeQuery();
                    if (rs.next()) {
                        int defaultProfileUser = rs.getInt(1);
                        if (rs.wasNull()) {
                            throw new RuntimeException("Need to clone the '" + profileFname + "' profile from template user for " + person + " but they have no template user");
                        }
                        IPerson defaultProfilePerson = new PersonImpl();
                        defaultProfilePerson.setID(defaultProfileUser);
                        if (defaultProfilePerson.getID() != person.getID()) {
                            UserProfile templateProfile = getUserProfileByFname(defaultProfilePerson, profileFname);
                            if (templateProfile != null) {
                                UserProfile newUserProfile = new UserProfile(templateProfile);
                                final Locale[] userLocales = localeStore.getUserLocales(person);
                                newUserProfile.setLayoutId(0);
                                newUserProfile = addUserProfile(person, newUserProfile);
                                newUserProfile.setLocaleManager(new LocaleManager(person, userLocales));
                                return newUserProfile;
                            }
                        }
                    }
                    throw new RuntimeException("Unable to find User Profile for userId " + userId + " and profile " + profileFname);
                } finally {
                    rs.close();
                }
            } finally {
                pstmt.close();
            }
        }
    });
    if (profileCache != null && key != null) {
        profileCache.put(key, userProfile);
    }
    return userProfile;
}
Also used : IUserProfile(org.apereo.portal.IUserProfile) UserProfile(org.apereo.portal.UserProfile) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) IJoinQueryString(org.apereo.portal.jdbc.IJoinQueryString) IPerson(org.apereo.portal.security.IPerson) PersonImpl(org.apereo.portal.security.provider.PersonImpl) ResultSet(java.sql.ResultSet) LocaleManager(org.apereo.portal.i18n.LocaleManager) Tuple(org.apereo.portal.utils.Tuple) DataAccessException(org.springframework.dao.DataAccessException)

Example 10 with PersonImpl

use of org.apereo.portal.security.provider.PersonImpl in project uPortal by Jasig.

the class NodeReferenceFactory method getUserLayoutTuple.

/*
     * Implementation.
     */
/**
     * Provides a {@link Tuple} containing the &quot;fragmentized&quot; version of a DLM fragment
     * owner's layout, together with the username. This version of the layout consistent with what
     * DLM uses internally for fragments, and is created by FragmentActivator.fragmentizeLayout.
     * It's important that the version returned by this method matches what DLM uses internally
     * because it will be used to establish relationships between fragment layout nodes and user
     * customizations of DLM fragments.
     *
     * @param userId
     * @return
     */
/* TODO:  make private */
Tuple<String, DistributedUserLayout> getUserLayoutTuple(String userName, int userId) {
    final PersonImpl person = new PersonImpl();
    person.setUserName(userName);
    person.setID(userId);
    person.setSecurityContext(new BrokenSecurityContext());
    final IUserProfile profile = layoutStore.getUserProfileByFname(person, UserProfile.DEFAULT_PROFILE_FNAME);
    final DistributedUserLayout userLayout = layoutStore.getUserLayout(person, (UserProfile) profile);
    return new Tuple<String, DistributedUserLayout>(userName, userLayout);
}
Also used : PersonImpl(org.apereo.portal.security.provider.PersonImpl) IUserProfile(org.apereo.portal.IUserProfile) BrokenSecurityContext(org.apereo.portal.security.provider.BrokenSecurityContext) Tuple(org.apereo.portal.utils.Tuple)

Aggregations

PersonImpl (org.apereo.portal.security.provider.PersonImpl)16 IPerson (org.apereo.portal.security.IPerson)12 IUserProfile (org.apereo.portal.IUserProfile)4 BrokenSecurityContext (org.apereo.portal.security.provider.BrokenSecurityContext)4 ArrayList (java.util.ArrayList)2 AuthorizationException (org.apereo.portal.AuthorizationException)2 Tuple (org.apereo.portal.utils.Tuple)2 Before (org.junit.Before)2 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 Iterator (java.util.Iterator)1 LinkedHashSet (java.util.LinkedHashSet)1 UserProfile (org.apereo.portal.UserProfile)1 LocaleManager (org.apereo.portal.i18n.LocaleManager)1 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)1 PortletPreferenceImpl (org.apereo.portal.portlet.dao.jpa.PortletPreferenceImpl)1 IPortletDefinition (org.apereo.portal.portlet.om.IPortletDefinition)1 IPortletEntity (org.apereo.portal.portlet.om.IPortletEntity)1