org.jivesoftware.openfire.user.UserManager Java Examples

The following examples show how to use org.jivesoftware.openfire.user.UserManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FlattenNestedGroupsTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private void initLdapManager(boolean posix, boolean flattenNestedGroups) {
    final Map<String, String> properties = new HashMap<>();
    properties.put("ldap.host", "localhost");
    properties.put("ldap.port", "" + LDAP_SERVER_PORT);
    properties.put("ldap.sslEnabled", "false" );
    properties.put("ldap.startTlsEnabled", "false" );
    properties.put("ldap.baseDN", "dc=mobikat,dc=net");
    properties.put("ldap.adminDN", EmbeddedLdapRuleBuilder.DEFAULT_BIND_DSN);
    properties.put("ldap.adminPassword", EmbeddedLdapRuleBuilder.DEFAULT_BIND_CREDENTIALS);
    properties.put("ldap.usernameField", "uid");
    properties.put("ldap.nameField", "cn");
    properties.put("ldap.searchFilter", "(objectClass=inetOrgPerson)");
    properties.put("ldap.groupNameField", "cn");
    properties.put("ldap.groupMemberField", posix ? "memberUid" : "uniqueMember");
    properties.put("ldap.groupSearchFilter", posix ? "(objectClass=posixGroup)" : "(objectClass=groupOfUniqueNames)");

    if (posix)
        properties.put("ldap.posixMode", "true");
    if (flattenNestedGroups)
        properties.put("ldap.flattenNestedGroups", "true");

    LdapManager.setInstance(new LdapManager(properties));
    UserManager.setProvider(new LdapUserProvider());
    UserManager.getInstance().clearCaches();
}
 
Example #2
Source File: UserProperties.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private void populateResponseFields(DataForm form, List<String> accounts) {
    FormField jidField = form.addField();
    jidField.setVariable("accountjids");

    FormField emailField = form.addField();
    emailField.setVariable("email");

    FormField nameField = form.addField();
    nameField.setVariable("name");

    UserManager manager = UserManager.getInstance();
    for(String account : accounts) {
        User user;
        try {
            JID jid = new JID(account);
            user = manager.getUser(jid.getNode());
        }
        catch (Exception ex) {
            continue;
        }

        jidField.addValue(account);
        emailField.addValue(user.getEmail());
        nameField.addValue(user.getName());
    }
}
 
Example #3
Source File: IQDiscoItemsHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<Element> getUserItems(String name, JID senderJID) {
    List<Element> answer = new ArrayList<>();
    try {
        User user = UserManager.getInstance().getUser(name);
        RosterItem item = user.getRoster().getRosterItem(senderJID);
        // If the requesting entity is subscribed to the account's presence then
        // answer the user's "available resources"
        if (item.getSubStatus() == RosterItem.SUB_FROM ||
                item.getSubStatus() == RosterItem.SUB_BOTH) {
            for (Session session : SessionManager.getInstance().getSessions(name)) {
                Element element = DocumentHelper.createElement("item");
                element.addAttribute("jid", session.getAddress().toString());
                answer.add(element);
            }
        }
        return answer.iterator();
    }
    catch (UserNotFoundException e) {
        return answer.iterator();
    }
}
 
Example #4
Source File: JDBCAuthProvider.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Checks to see if the user exists; if not, a new user is created.
 *
 * @param username the username.
 */
// @VisibleForTesting
protected void createUser(String username) {
    // See if the user exists in the database. If not, automatically create them.
    UserManager userManager = UserManager.getInstance();
    try {
        userManager.getUser(username);
    }
    catch (UserNotFoundException unfe) {
        try {
            Log.debug("JDBCAuthProvider: Automatically creating new user account for " + username);
            UserManager.getUserProvider().createUser(username, StringUtils.randomString(8),
                    null, null);
        }
        catch (UserAlreadyExistsException uaee) {
            // Ignore.
        }
    }
}
 
Example #5
Source File: MultiUserChatServiceImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if a particular JID is allowed to create rooms.
 *
 * @param jid The jid for which to check (cannot be null).
 * @return true if the JID is allowed to create a room, otherwise false.
 */
private boolean isAllowedToCreate(final JID jid) {
    // If room creation is not restricted, everyone is allowed to create a room.
    if (!isRoomCreationRestricted()) {
        return true;
    }

    final JID bareJID = jid.asBareJID();

    // System administrators are always allowed to create rooms.
    if (sysadmins.includes(bareJID)) {
        return true;
    }

    // If the JID of the user has explicitly been given permission, room creation is allowed.
    if (allowedToCreate.includes(bareJID)) {
        return true;
    }

    // Verify the policy that allows all local, registered users to create rooms.
    return allRegisteredUsersAllowedToCreate && UserManager.getInstance().isRegisteredUser(bareJID);

}
 
Example #6
Source File: RosterManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * This method is similar to {@link #getAffectedUsers(Group)} except that it receives
 * some group properties. The group properties are passed as parameters since the called of this
 * method may want to obtain the related users of the group based in some properties values.
 *
 * This is useful when the group is being edited and some properties has changed and we need to
 * obtain the related users of the group based on the previous group state.
 */
private Collection<JID> getAffectedUsers(Group group, String showInRoster, String groupNames) {
    // Answer an empty collection if the group is not being shown in users' rosters
    if (!"onlyGroup".equals(showInRoster) && !"everybody".equals(showInRoster)) {
        return new ArrayList<>();
    }
    // Add the users of the group
    Collection<JID> users = new HashSet<>(group.getMembers());
    users.addAll(group.getAdmins());
    // Check if anyone can see this shared group
    if ("everybody".equals(showInRoster)) {
        // Add all users in the system
        for (String username : UserManager.getInstance().getUsernames()) {
            users.add(server.createJID(username, null, true));
        }
        // Add all logged users. We don't need to add all users in the system since only the
        // logged ones will be affected.
        //users.addAll(SessionManager.getInstance().getSessionUsers());
    }
    else {
        // Add the users that may see the group
        Collection<Group> groupList = parseGroups(groupNames);
        for (Group groupInList : groupList) {
            users.addAll(groupInList.getMembers());
            users.addAll(groupInList.getAdmins());
        }
    }
    return users;
}
 
Example #7
Source File: FlattenNestedGroupsTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnection() throws Exception {
    initLdapManager(false, false);

    LdapManager ldapManager = LdapManager.getInstance();
    assertEquals("cn=admins,ou=groups,dc=mobikat,dc=net", ldapManager.findGroupAbsoluteDN("admins").toString());

    UserManager userManager = UserManager.getInstance();

    User user = userManager.getUser("j.bond");
    assertNotNull(user);
    assertEquals("James Bond", user.getName());
}
 
Example #8
Source File: LdapGroupProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new LDAP group provider.
 */
public LdapGroupProvider() {
    manager = LdapManager.getInstance();
    userManager = UserManager.getInstance();
    standardAttributes = new String[3];
    standardAttributes[0] = manager.getGroupNameField();
    standardAttributes[1] = manager.getGroupDescriptionField();
    standardAttributes[2] = manager.getGroupMemberField();
}
 
Example #9
Source File: PEPServiceManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public PEPService create(JID owner) {
    // Return an error if the packet is from an anonymous, unregistered user
    // or remote user
    if (!XMPPServer.getInstance().isLocal(owner)
            || !UserManager.getInstance().isRegisteredUser(owner.getNode())) {
        throw new IllegalArgumentException(
                "Request must be initiated by a local, registered user, but is not: "
                        + owner);
    }

    PEPService pepService = null;
    final JID bareJID = owner.asBareJID();
    final Lock lock = pepServices.getLock(bareJID);
    lock.lock();
    try {

        if (pepServices.get(bareJID) != null) {
            pepService = pepServices.get(bareJID).get();
        }

        if (pepService == null) {
            pepService = new PEPService(XMPPServer.getInstance(), bareJID);
            pepServices.put(bareJID, CacheableOptional.of(pepService));
            pepService.initialize();

            if (Log.isDebugEnabled()) {
                Log.debug("PEPService created for : " + bareJID);
            }
        }
    } finally {
        lock.unlock();
    }

    return pepService;
}
 
Example #10
Source File: IQPrivateHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    IQ replyPacket = IQ.createResultIQ(packet);

    Element child = packet.getChildElement();
    Element dataElement = child.elementIterator().next();

    if ( !XMPPServer.getInstance().isLocal( packet.getFrom()) || !UserManager.getInstance().isRegisteredUser( packet.getFrom()) ) {
        replyPacket.setChildElement(packet.getChildElement().createCopy());
        replyPacket.setError(PacketError.Condition.service_unavailable);
        replyPacket.getError().setText( "Service available only to locally registered users." );
        return replyPacket;
    }

    if (dataElement != null) {
        if (IQ.Type.get.equals(packet.getType())) {
            Element dataStored = privateStorage.get(packet.getFrom().getNode(), dataElement);
            dataStored.setParent(null);

            child.remove(dataElement);
            child.setParent(null);
            replyPacket.setChildElement(child);
            child.add(dataStored);
        }
        else {
            if (privateStorage.isEnabled()) {
                privateStorage.add(packet.getFrom().getNode(), dataElement);
            } else {
                replyPacket.setChildElement(packet.getChildElement().createCopy());
                replyPacket.setError(PacketError.Condition.service_unavailable);
            }
        }
    }
    else {
        replyPacket.setChildElement("query", "jabber:iq:private");
    }
    return replyPacket;
}
 
Example #11
Source File: IQRegisterHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void setCanChangePassword(boolean allowed)
{
    if ( allowed && UserManager.getUserProvider().isReadOnly() )
    {
        Log.warn( "Allowing password changes has no effect, as the user provider for this system is read-only." );
    }
    canChangePassword = allowed;
    JiveGlobals.setProperty("register.password", canChangePassword ? "true" : "false");
}
 
Example #12
Source File: IQRegisterHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void setInbandRegEnabled(boolean allowed)
{
    if ( allowed && UserManager.getUserProvider().isReadOnly() )
    {
        Log.warn( "Enabling in-band registration has no effect, as the user provider for this system is read-only." );
    }
    registrationEnabled = allowed;
    JiveGlobals.setProperty("register.inband", registrationEnabled ? "true" : "false");
}
 
Example #13
Source File: RosterManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
Collection<JID> getSharedUsersForRoster(Group group, Roster roster) {
    String showInRoster = group.getProperties().get("sharedRoster.showInRoster");
    String groupNames = group.getProperties().get("sharedRoster.groupList");

    // Answer an empty collection if the group is not being shown in users' rosters
    if (!"onlyGroup".equals(showInRoster) && !"everybody".equals(showInRoster)) {
        return new ArrayList<>();
    }

    // Add the users of the group
    Collection<JID> users = new HashSet<>(group.getMembers());
    users.addAll(group.getAdmins());

    // If the user of the roster belongs to the shared group then we should return
    // users that need to be in the roster with subscription "from"
    if (group.isUser(roster.getUsername())) {
        // Check if anyone can see this shared group
        if ("everybody".equals(showInRoster)) {
            // Add all users in the system
            for (String username : UserManager.getInstance().getUsernames()) {
                users.add(server.createJID(username, null, true));
            }
        }
        else {
            // Add the users that may see the group
            Collection<Group> groupList = parseGroups(groupNames);
            for (Group groupInList : groupList) {
                users.addAll(groupInList.getMembers());
                users.addAll(groupInList.getAdmins());
            }
        }
    }
    return users;
}
 
Example #14
Source File: JigasiWrapper.java    From openfire-ofmeet-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Attemt to create an XMPP user that will represent the SIP contact that is pulled into a Meet.
 */
private static void ensureJigasiUser()
{
    final OFMeetConfig config = new OFMeetConfig();

    final String userId = config.getJigasiXmppUserId().get();

    // Ensure that the user exists.
    final UserManager userManager = XMPPServer.getInstance().getUserManager();
    if ( !userManager.isRegisteredUser( userId ) )
    {
        Log.info( "No pre-existing jigasi user '{}' detected. Generating one.", userId );

        if ( UserManager.getUserProvider().isReadOnly() ) {
            Log.info( "The user provider on this system is read only. Cannot create a Jigasi user account." );
            return;
        }

        String password = config.getJigasiXmppPassword().get();
        if ( password == null || password.isEmpty() )
        {
            password = StringUtils.randomString( 40 );
        }

        try
        {
            userManager.createUser(
                userId,
                password,
                "Jigasi User (generated)",
                null
            );
            config.getJigasiXmppPassword().set( password );
        }
        catch ( Exception e )
        {
            Log.error( "Unable to provision a jigasi user.", e );
        }
    }
}
 
Example #15
Source File: RosterManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void userDeleting(User user, Map<String,Object> params) {
    // Shared public groups that have a presence subscription of type FROM
    // for the deleted user should no longer have a reference to the deleted user
    JID userJID = server.createJID(user.getUsername(), null);
    // Shared public groups that are public should have a presence subscription
    // of type FROM for the new user
    for (Group group : getPublicSharedGroups()) {
        // Get group members of public group
        Collection<JID> users = new HashSet<>(group.getMembers());
        users.addAll(group.getAdmins());
        // Update the roster of each group member to include a subscription of type FROM
        for (JID userToUpdate : users) {
            // Get the roster to update
            Roster roster = null;
            if (server.isLocal(userToUpdate)) {
                // Check that the user exists, if not then continue with the next user
                try {
                    UserManager.getInstance().getUser(userToUpdate.getNode());
                }
                catch (UserNotFoundException e) {
                    continue;
                }
                roster = rosterCache.get(userToUpdate.getNode());
            }
            // Only update rosters in memory
            if (roster != null) {
                roster.deleteSharedUser(group, userJID);
            }
            if (!server.isLocal(userToUpdate)) {
                // Unsusbcribe from the presence of the remote user. This is only necessary for
                // remote users and may only work with remote users that **automatically**
                // accept presence subscription requests
                sendSubscribeRequest(userJID, userToUpdate, false);
            }
        }
    }

    deleteRoster(userJID);
}
 
Example #16
Source File: CrowdVCardProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.jivesoftware.openfire.vcard.DefaultVCardProvider#updateVCard(java.lang.String, org.dom4j.Element)
 */
@Override
public Element updateVCard(String username, Element vCard) throws NotFoundException {
    // make sure some properties have not been overridden
    Element nickNameNode = vCard.element("NICKNAME");
    Element displayNameNode = vCard.element("FN");
    
    Element nameNode = vCard.element("N");
    Element lastNameNode = nameNode.element("FAMILY");
    Element firstnameNode = nameNode.element("GIVEN");
    
    Element emailNode = vCard.element("EMAIL").element("USERID");
    
    CrowdUserProvider userProvider = (CrowdUserProvider) UserManager.getUserProvider();
    try {
        User user = userProvider.getCrowdUser(username);
        
        nickNameNode.setText(username);
        displayNameNode.setText(user.displayName);
        lastNameNode.setText(user.lastName);
        firstnameNode.setText(user.firstName);
        emailNode.setText(user.email);
        
    } catch (UserNotFoundException unfe) {
        LOG.error("Unable to find user:" + String.valueOf(username) + " for updating its vcard", unfe);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("updatevcard:" + vCard.asXML());
    }

    return super.updateVCard(username, vCard);
}
 
Example #17
Source File: ChangeUserPassword.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData data, Element command) {
    Element note = command.addElement("note");
    // Check if groups cannot be modified (backend is read-only)
    if (UserManager.getUserProvider().isReadOnly()) {
        note.addAttribute("type", "error");
        note.setText("Users are read only. Changing password is not allowed.");
        return;
    }
    JID account = new JID(data.getData().get("accountjid").get(0));
    String newPassword = data.getData().get("password").get(0);
    if (!XMPPServer.getInstance().isLocal(account)) {
        note.addAttribute("type", "error");
        note.setText("Cannot change password of remote user.");
        return;
    }
    // Get requested group
    User user;
    try {
        user = UserManager.getInstance().getUser(account.getNode());
    } catch (UserNotFoundException e) {
        // Group not found
        note.addAttribute("type", "error");
        note.setText("User does not exists.");
        return;
    }
    // Set the new passowrd of the user
    user.setPassword(newPassword);
    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example #18
Source File: UserDeleting.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData sessionData, Element command) {
    Element note = command.addElement("note");

    Map<String, List<String>> data = sessionData.getData();

    // Gets the username
    String username;
    try {
        username = get(data, "username", 0);
    }
    catch (NullPointerException npe) {
        note.addAttribute("type", "error");
        note.setText("Username required parameter.");
        return;
    }

    // Sends the event
    User user;
    try {
        // Gets current user
        user = UserManager.getInstance().getUser(username);
        
        Map<String, Object> params = Collections.emptyMap();
        UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_deleting, params);
    } catch (UserNotFoundException e) {
        // It's ok, user doesn't exist, so deleting it is nothing
    }

    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example #19
Source File: UserCreated.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData sessionData, Element command) {
    Element note = command.addElement("note");

    Map<String, List<String>> data = sessionData.getData();

    // Get the username
    String username;
    try {
        username = get(data, "username", 0);
    }
    catch (NullPointerException npe) {
        note.addAttribute("type", "error");
        note.setText("Username required parameter.");
        return;
    }

    // Sends the event
    User user;
    try {
        // Loads the new user            
        user = UserManager.getUserProvider().loadUser(username);

        // Fire event.
        Map<String, Object> params = Collections.emptyMap();
        UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_created, params);

    } catch (UserNotFoundException e) {
        note.addAttribute("type", "error");
        note.setText("User not found.");
    }

    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example #20
Source File: RosterManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * A new user has been created so members of public shared groups need to have
 * their rosters updated. Members of public shared groups need to have a roster
 * item with subscription FROM for the new user since the new user can see them.
 *
 * @param newUser the newly created user.
 * @param params event parameters.
 */
@Override
public void userCreated(User newUser, Map<String,Object> params) {
    JID newUserJID = server.createJID(newUser.getUsername(), null);
    // Shared public groups that are public should have a presence subscription
    // of type FROM for the new user
    for (Group group : getPublicSharedGroups()) {
        // Get group members of public group
        Collection<JID> users = new HashSet<>(group.getMembers());
        users.addAll(group.getAdmins());
        // Update the roster of each group member to include a subscription of type FROM
        for (JID userToUpdate : users) {
            // Get the roster to update
            Roster roster = null;
            if (server.isLocal(userToUpdate)) {
                // Check that the user exists, if not then continue with the next user
                try {
                    UserManager.getInstance().getUser(userToUpdate.getNode());
                }
                catch (UserNotFoundException e) {
                    continue;
                }
                roster = rosterCache.get(userToUpdate.getNode());
            }
            // Only update rosters in memory
            if (roster != null) {
                roster.addSharedUser(group, newUserJID);
            }
            if (!server.isLocal(userToUpdate)) {
                // Susbcribe to the presence of the remote user. This is only necessary for
                // remote users and may only work with remote users that **automatically**
                // accept presence subscription requests
                sendSubscribeRequest(newUserJID, userToUpdate, true);
            }
        }
    }
}
 
Example #21
Source File: DeleteUser.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public boolean hasPermission(JID requester) {
    return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester))
            && !UserManager.getUserProvider().isReadOnly();
}
 
Example #22
Source File: JitsiJicofoWrapper.java    From openfire-ofmeet-plugin with Apache License 2.0 4 votes vote down vote up
private static void ensureFocusUser()
{
    final OFMeetConfig config = new OFMeetConfig();

    // Ensure that the 'focus' user exists.
    final UserManager userManager = XMPPServer.getInstance().getUserManager();
    if ( !userManager.isRegisteredUser( "focus" ) )
    {
        Log.info( "No pre-existing 'focus' user detected. Generating one." );

        String password = config.getFocusPassword();
        if ( password == null || password.isEmpty() )
        {
            password = StringUtils.randomString( 40 );
        }

        try
        {
            userManager.createUser(
                "focus",
                password,
                "Focus User (generated)",
                null
            );
            config.setFocusPassword( password );
        }
        catch ( Exception e )
        {
            Log.error( "Unable to provision a 'focus' user.", e );
        }
    }

    // Ensure that the 'focus' user can grant permissions in persistent MUCs by making it a sysadmin of the conference service(s).
    final JID focusUserJid = new JID( "focus@" + XMPPServer.getInstance().getServerInfo().getXMPPDomain() );
    for ( final MultiUserChatService mucService : XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatServices() )
    {
        if ( !mucService.isSysadmin( focusUserJid ) )
        {
            Log.info( "Adding 'focus' user as a sysadmin to the '{}' MUC service.", mucService.getServiceName() );
            mucService.addSysadmin( focusUserJid );
        }
    }
}
 
Example #23
Source File: MeetingPlanner.java    From openfire-ofmeet-plugin with Apache License 2.0 4 votes vote down vote up
public static void processMeeting(JSONObject meeting, String username, String videourl)
 {
     Log.info("OfMeet Plugin - processMeeting " + username + " " + meeting);

     try {
         UserManager userManager = XMPPServer.getInstance().getUserManager();
         User user = userManager.getUser(username);
         Date start = new Date(meeting.getLong("startTime"));
         Date end = new Date(meeting.getLong("endTime"));
         String name = user.getName();
         String email = user.getEmail();
         String description = meeting.getString("description");
         String title = meeting.getString("title");
         String room = meeting.getString("room");
         String audiourl = videourl + "#config.startWithVideoMuted=true";
         String template = JiveGlobals.getProperty("ofmeet.email.template", "Dear [name],\n\nYou have an online meeting from [start] to [end]\n\n[description]\n\nTo join, please click\n[videourl]\nFor audio only with no webcan, please click\n[audiourl]\n\nAdministrator - [domain]");

         HashMap variables = new HashMap<String, String>();
         String domain = XMPPServer.getInstance().getServerInfo().getXMPPDomain();

variables.put("name", name);
variables.put("email", email);
variables.put("start", start.toString());
variables.put("end", end.toString());
variables.put("description", description);
variables.put("title", title);
variables.put("room", room);
variables.put("videourl", videourl);
variables.put("audiourl", audiourl);
variables.put("domain", domain);

         if (email != null)
         {
	sendEmail(name, email, title, replaceTokens(template, variables), null);
}

if (SessionManager.getInstance().getSessions(username).size() > 0)
{
	// send invitation to user session as chat message with url

	org.xmpp.packet.Message message = new org.xmpp.packet.Message();
	message.setFrom(domain);
	message.setSubject(title);
	message.setTo(username + "@" + domain);
	message.setBody(videourl);

	SessionManager.getInstance().userBroadcast(username, message);
}
SecurityAuditManager.getInstance().logEvent(username, "sent email - " + title, description);

     }
     catch (Exception e) {
         Log.error("processMeeting error", e);
     }
 }
 
Example #24
Source File: WebManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
public UserManager getUserManager() {
    return getXMPPServer().getUserManager();
}
 
Example #25
Source File: ChangeUserPassword.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public boolean hasPermission(JID requester) {
    return super.hasPermission(requester) && !UserManager.getUserProvider().isReadOnly();
}
 
Example #26
Source File: AddUser.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public boolean hasPermission(JID requester) {
    return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester))
            && !UserManager.getUserProvider().isReadOnly();
}
 
Example #27
Source File: OfflineMessageStrategy.java    From Openfire with Apache License 2.0 4 votes vote down vote up
public void storeOffline(Message message) {
    if (message != null) {
        // Do nothing if the message was sent to the server itself, an anonymous user or a non-existent user
        // Also ignore message carbons
        JID recipientJID = message.getTo();
        if (recipientJID == null || serverAddress.equals(recipientJID) ||
                recipientJID.getNode() == null ||
                message.getExtension("received", "urn:xmpp:carbons:2") != null ||
                !UserManager.getInstance().isRegisteredUser(recipientJID.getNode())) {
            return;
        }

        // Do not store messages if communication is blocked
        PrivacyList list =
                PrivacyListManager.getInstance().getDefaultPrivacyList(recipientJID.getNode());
        if (list != null && list.shouldBlockPacket(message)) {
            Message result = message.createCopy();
            result.setTo(message.getFrom());
            result.setFrom(message.getTo());
            result.setError(PacketError.Condition.service_unavailable);
            XMPPServer.getInstance().getRoutingTable().routePacket(message.getFrom(), result, true);
            return;
        }

        // 8.5.2.  localpart@domainpart
        // 8.5.2.2.  No Available or Connected Resources
        if (recipientJID.getResource() == null) {
            if (message.getType() == Message.Type.headline || message.getType() == Message.Type.error) {
                // For a message stanza of type "headline" or "error", the server MUST silently ignore the message.
                return;
            }
            // // For a message stanza of type "groupchat", the server MUST return an error to the sender, which SHOULD be <service-unavailable/>.
            else if (message.getType() == Message.Type.groupchat) {
                bounce(message);
                return;
            }
        } else {
            // 8.5.3.  localpart@domainpart/resourcepart
            // 8.5.3.2.1.  Message

            // For a message stanza of type "normal", "groupchat", or "headline", the server MUST either (a) silently ignore the stanza
            // or (b) return an error stanza to the sender, which SHOULD be <service-unavailable/>.
            if (message.getType() == Message.Type.normal || message.getType() == Message.Type.groupchat || message.getType() == Message.Type.headline) {
                // Depending on the OfflineMessageStragey, we may silently ignore or bounce
                if (type == Type.bounce) {
                    bounce(message);
                }
                // Either bounce or silently ignore, never store such messages
                return;
            }
            // For a message stanza of type "error", the server MUST silently ignore the stanza.
            else if (message.getType() == Message.Type.error) {
                return;
            }
        }

        switch (type) {
        case bounce:
            bounce(message);
            break;
        case store:
            store(message);
            break;
        case store_and_bounce:
            if (underQuota(message)) {
                store(message);
            }
            else {
                Log.debug( "Unable to store, as user is over storage quota. Bouncing message instead: " + message.toXML() );
                bounce(message);
            }
            break;
        case store_and_drop:
            if (underQuota(message)) {
                store(message);
            } else {
                Log.debug( "Unable to store, as user is over storage quota. Silently dropping message: " + message.toXML() );
            }
            break;
        case drop:
            // Drop essentially means silently ignore/do nothing
            break;
        }
    }
}
 
Example #28
Source File: AuthorizationManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Authorize the authenticated used to the requested username.  This uses the
 * selected the selected AuthenticationProviders.
 *
 * @param username The requested username.
 * @param principal The authenticated principal.
 * @return true if the user is authorized.
 */

public static boolean authorize(String username, String principal) {
    for (AuthorizationPolicy ap : authorizationPolicies) {
        if (Log.isDebugEnabled()) {
            Log.debug("AuthorizationManager: Trying "+ap.name()+".authorize("+username+" , "+principal+")");
        }

        if (ap.authorize(username, principal)) {
            // Authorized..  but do you exist?
            try {
                UserManager.getUserProvider().loadUser(username);
            }
            catch (UserNotFoundException nfe) {
                if (Log.isDebugEnabled()) {
                    Log.debug("AuthorizationManager: User " + username + " not found " + nfe.toString());
                }
                // Should we add the user?
                if(JiveGlobals.getBooleanProperty("xmpp.auth.autoadd",false)) {
                    if (UserManager.getUserProvider().isReadOnly()) {
                        return false;
                    }
                    if (UserManager.getUserProvider().isNameRequired() || UserManager.getUserProvider().isEmailRequired()) {
                        // If these are required, there's no way we can arbitrarily auto-create this account.
                        return false;
                    }
                    try {
                        UserManager.getInstance().createUser(username, StringUtils.randomString(8), null, null);
                        if (Log.isDebugEnabled()) {
                            Log.info("AuthorizationManager: User "+username+" created.");
                        }
                        return true;
                    }
                    catch (UserAlreadyExistsException uaee) {
                        // Somehow the user got created in this very short timeframe.. 
                        // To be safe, lets fail here. The user can always try again.
                        if (Log.isDebugEnabled()) {
                            Log.error("AuthorizationManager: User " + username +
                                    " already exists while attempting to add user.");
                        }
                        return false;
                    }
                }
                return false;
            }
            // User exists
            return true;
        }
    }
    // Not authorized.
    return false;
}
 
Example #29
Source File: CrowdVCardProvider.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * @see org.jivesoftware.openfire.vcard.DefaultVCardProvider#loadVCard(java.lang.String)
 */
@Override
public Element loadVCard(String username) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("loadvcard:" + username);
    }
    
    if (MUTEX.containsKey(username)) {
        // preventing looping
        return null;
    }

    try {
        MUTEX.put(username, username);
        
        Element vcard = super.loadVCard(username);
        
        if (vcard == null) {
            CrowdUserProvider userProvider = (CrowdUserProvider) UserManager.getUserProvider();
            try {
                User user = userProvider.getCrowdUser(username);
                String str = VCARD_TEMPLATE.replace("@displayname@", user.displayName)
                        .replace("@lastname@", user.lastName)
                        .replace("@firstname@", user.firstName)
                        .replace("@email@", user.email)
                        .replace("@nickname@", username);
                
                SAXReader xmlReader = new SAXReader();
                xmlReader.setEncoding("UTF-8");
                
                vcard = xmlReader.read(new StringReader(str)).getRootElement();
                
            } catch (UserNotFoundException unfe) {
                LOG.error("Unable to find user:" + String.valueOf(username) + " for loading its vcard", unfe);
                return null;
            } catch (DocumentException de) {
                LOG.error("vcard parsing error", de);
                return null;
            }

            
            if (LOG.isDebugEnabled()) {
                LOG.debug(vcard != null ? vcard.asXML() : "vcard is null");
            }
            
            
            // store this new vcard
            if (vcard != null) {
                try {
                    createVCard(username, vcard);
                } catch (AlreadyExistsException aee) {
                    LOG.error("Unable to create and store a new vcard for user:" + username + "; one already exists", aee);
                }
            }
        }
        
        return vcard;

    } catch (RuntimeException re) {
        LOG.error("Failure occured when loading a vcard for user:" + username, re);
        throw re;
    } finally {
        MUTEX.remove(username);
    }
}
 
Example #30
Source File: NativeAuthProvider.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(String username, String password) throws UnauthorizedException {
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {
            // Unknown domain. Return authentication failed.
            throw new UnauthorizedException();
        }
    }
    try {
        // Some native authentication mechanisms appear to not handle high load
        // very well. Therefore, synchronize access to Shaj to throttle auth checks.
        synchronized (this) {
            if (!Shaj.checkPassword(domain, username, password)) {
                throw new UnauthorizedException();
            }
        }
    }
    catch (UnauthorizedException ue) {
        throw ue;
    }
    catch (Exception e) {
        throw new UnauthorizedException(e);
    }

    // See if the user exists in the database. If not, automatically create them.
    UserManager userManager = UserManager.getInstance();
    try {
        userManager.getUser(username);
    }
    catch (UserNotFoundException unfe) {
        try {
            Log.debug("Automatically creating new user account for " + username);
            // Create user; use a random password for better safety in the future.
            // Note that we have to go to the user provider directly -- because the
            // provider is read-only, UserManager will usually deny access to createUser.
            UserProvider provider = UserManager.getUserProvider();
            if (!(provider instanceof NativeUserProvider)) {
                Log.error("Error: not using NativeUserProvider so authentication with " +
                        "NativeAuthProvider will likely fail. Using: " +
                        provider.getClass().getName());
            }
            UserManager.getUserProvider().createUser(username, StringUtils.randomString(8),
                    null, null);
        }
        catch (UserAlreadyExistsException uaee) {
            // Ignore.
        }
    }
}