use of gnu.inet.encoding.StringprepException in project Openfire by igniterealtime.
the class OpenfireExporter method importUsers.
/*
* (non-Javadoc)
*
* @see
* org.jivesoftware.openfire.plugin.InExporter#importUsers(org.dom4j.Document,
* java.lang.String)
*/
@SuppressWarnings("unchecked")
private List<String> importUsers(Document document, String previousDomain, boolean isUserProviderReadOnly) {
Log.debug("importUsers");
List<String> invalidUsers = new ArrayList<String>();
Element users = document.getRootElement();
Iterator<Element> usersIter = users.elementIterator("User");
while (usersIter.hasNext()) {
Element user = usersIter.next();
String userName = null;
String password = null;
String email = null;
String name = null;
List<RosterItem> rosterItems = new ArrayList<RosterItem>();
Iterator<Element> userElements = user.elementIterator();
while (userElements.hasNext()) {
Element userElement = userElements.next();
String nameElement = userElement.getName();
if ("Username".equals(nameElement)) {
userName = userElement.getText();
} else if ("Password".equals(nameElement)) {
password = userElement.getText();
} else if ("Name".equals(nameElement)) {
name = userElement.getText();
} else if ("Email".equals(nameElement)) {
email = userElement.getText();
} else if ("Roster".equals(nameElement)) {
Iterator<Element> rosterIter = userElement.elementIterator("Item");
while (rosterIter.hasNext()) {
Element rosterElement = rosterIter.next();
String jid = rosterElement.attributeValue("jid");
String askstatus = rosterElement.attributeValue("askstatus");
String recvstatus = rosterElement.attributeValue("recvstatus");
String substatus = rosterElement.attributeValue("substatus");
String nickname = rosterElement.attributeValue("name");
List<String> groups = new ArrayList<String>();
Iterator<Element> groupIter = rosterElement.elementIterator("Group");
while (groupIter.hasNext()) {
Element group = groupIter.next();
String groupName = group.getText();
if (groupName != null && groupName.trim().length() > 0) {
groups.add(groupName);
}
}
// used for migration
if (previousDomain != null) {
jid = jid.replace(previousDomain, serverName);
}
rosterItems.add(new RosterItem(new JID(jid), RosterItem.SubType.getTypeFromInt(Integer.parseInt(substatus)), RosterItem.AskType.getTypeFromInt(Integer.parseInt(askstatus)), RosterItem.RecvType.getTypeFromInt(Integer.parseInt(recvstatus)), nickname, groups));
}
}
}
if ((userName != null) && (password != null)) {
try {
userName = Stringprep.nodeprep(userName);
if (isUserProviderReadOnly) {
userManager.createUser(userName, password, name, email);
}
// Check to see user exists before adding their roster, this is for
// read-only user providers.
userManager.getUser(userName);
for (RosterItem ri : rosterItems) {
rosterItemProvider.createItem(userName, ri);
}
} catch (StringprepException se) {
Log.info("Invalid username " + userName);
invalidUsers.add(userName);
} catch (UserAlreadyExistsException e) {
Log.info("User already exists " + userName);
invalidUsers.add(userName);
} catch (UserNotFoundException e) {
Log.info("User not found " + userName);
invalidUsers.add(userName);
}
}
}
return invalidUsers;
}
use of gnu.inet.encoding.StringprepException in project Openfire by igniterealtime.
the class Xep227Exporter method importUser.
/**
* @param user
* @param previousDomain
* @param isUserProviderReadOnly
* @param invalidUsers
*/
@SuppressWarnings("unchecked")
private void importUser(Element user, String previousDomain, boolean isUserProviderReadOnly, List<String> invalidUsers) {
Log.debug("importUser");
List<RosterItem> rosterItems = new ArrayList<RosterItem>();
List<OfflineMessage> offlineMessages = new ArrayList<OfflineMessage>();
Element vCardElement = null;
String userName = user.attributeValue(NAME_NAME);
String password = user.attributeValue(PASSWORD_NAME);
Iterator<Element> userElements = user.elementIterator();
while (userElements.hasNext()) {
Element userElement = userElements.next();
String nameElement = userElement.getName();
if (OFFLINE_MESSAGES_ELEMENT_NAME.equals(nameElement)) {
importOffLineMessages(userElement, offlineMessages);
} else if (QUERY_ELEMENT_NAME.equals(nameElement) && JABBER_IQ_ROSTER_NS.equals(userElement.getNamespaceURI())) {
importUserRoster(userElement, rosterItems, previousDomain);
} else if (V_CARD_NAME.equals(nameElement) && VCARD_TEMP_NS.equals(userElement.getNamespaceURI())) {
vCardElement = userElement;
}
}
if (userName != null) {
try {
userName = Stringprep.nodeprep(userName);
if (!isUserProviderReadOnly && (password != null)) {
userManager.createUser(userName, password, userName, null);
}
if (!isUserProviderReadOnly && vCardElement != null) {
try {
vCardManager.setVCard(userName, vCardElement);
} catch (Exception e) {
Log.warn("Error updating VCard:" + userName + ":" + e.getMessage());
Log.debug("", e);
}
}
// Check to see user exists before adding their roster, this is for
// read-only user providers.
userManager.getUser(userName);
for (RosterItem ri : rosterItems) {
rosterItemProvider.createItem(userName, ri);
}
for (OfflineMessage offlineMessage : offlineMessages) {
offlineMessagesStore.addMessage(offlineMessage);
}
} catch (StringprepException se) {
Log.info("Invalid username " + userName);
invalidUsers.add(userName);
} catch (UserAlreadyExistsException e) {
Log.info("User already exists " + userName);
invalidUsers.add(userName);
} catch (UserNotFoundException e) {
Log.info("User not found " + userName);
invalidUsers.add(userName);
} catch (Exception e) {
Log.warn("Error updating User:" + userName + ":" + e.getLocalizedMessage());
invalidUsers.add(userName);
}
}
}
use of gnu.inet.encoding.StringprepException in project Openfire by igniterealtime.
the class WorkgroupUtils method createWorkgroup.
/**
* Create a new Workgroup.
*
* @param workgroupName the name of the workgroup.
* @param description the description of the workgroup.
* @param agents the agents, in a comma delimited string.
* @return a map of errors (if any)
*/
public static Map<String, String> createWorkgroup(String workgroupName, String description, String agents) {
Map<String, String> errors = new HashMap<String, String>();
// Get a workgroup manager
WorkgroupManager wgManager = WorkgroupManager.getInstance();
if (wgManager == null) {
errors.put("general_error", "The server is down");
return errors;
}
String defaultQueueName = "Default Queue";
// Validate
if (workgroupName == null) {
errors.put("wgName", "");
} else {
try {
workgroupName = workgroupName.trim().toLowerCase();
workgroupName = Stringprep.nodeprep(workgroupName);
} catch (StringprepException se) {
errors.put("wgName", "");
}
}
// do a create if there were no errors
RequestQueue queue = null;
if (errors.size() == 0) {
try {
// Create new workgroup
Workgroup workgroup = wgManager.createWorkgroup(workgroupName);
workgroup.setDescription(description);
// Create a default workgroup queue
queue = workgroup.createRequestQueue(defaultQueueName);
//workgroup.setMaxChats(maxChats);
//workgroup.setMinChats(minChats);
// Make the workgroup ready by default:
workgroup.setStatus(Workgroup.Status.READY);
// Create default messages and images for the new workgroup
ChatSettingsCreator.getInstance().createDefaultSettings(workgroup.getJID());
// Add generic web form
FormManager formManager = FormManager.getInstance();
formManager.createGenericForm(workgroup);
} catch (UserAlreadyExistsException uaee) {
errors.put("exists", "");
} catch (Exception e) {
Log.error(e.getMessage(), e);
errors.put("general", "");
}
}
if (ModelUtil.hasLength(agents)) {
addAgents(queue, agents);
}
return errors;
}
use of gnu.inet.encoding.StringprepException in project Openfire by igniterealtime.
the class IQAuthHandler method login.
private IQ login(String username, Element iq, IQ packet, String password, LocalClientSession session, String digest) throws UnauthorizedException, UserNotFoundException, ConnectionException, InternalUnauthenticatedException {
// Verify the validity of the username
if (username == null || username.trim().length() == 0) {
throw new UnauthorizedException("Invalid username (empty or null).");
}
try {
Stringprep.nodeprep(username);
} catch (StringprepException e) {
throw new UnauthorizedException("Invalid username: " + username, e);
}
// Verify that specified resource is not violating any string prep rule
String resource = iq.elementText("resource");
if (resource != null) {
try {
resource = JID.resourceprep(resource);
} catch (StringprepException e) {
throw new UnauthorizedException("Invalid resource: " + resource, e);
}
} else {
// Answer a not_acceptable error since a resource was not supplied
IQ response = IQ.createResultIQ(packet);
response.setChildElement(packet.getChildElement().createCopy());
response.setError(PacketError.Condition.not_acceptable);
return response;
}
if (!JiveGlobals.getBooleanProperty("xmpp.auth.iqauth", true)) {
throw new UnauthorizedException();
}
username = username.toLowerCase();
// Verify that supplied username and password are correct (i.e. user authentication was successful)
AuthToken token = null;
if (AuthFactory.supportsPasswordRetrieval()) {
if (password != null) {
token = AuthFactory.authenticate(username, password);
} else if (digest != null) {
token = authenticate(username, session.getStreamID().toString(), digest);
}
}
if (token == null) {
throw new UnauthorizedException();
}
// Verify if there is a resource conflict between new resource and existing one.
// Check if a session already exists with the requested full JID and verify if
// we should kick it off or refuse the new connection
ClientSession oldSession = routingTable.getClientRoute(new JID(username, serverName, resource, true));
if (oldSession != null) {
try {
int conflictLimit = sessionManager.getConflictKickLimit();
if (conflictLimit == SessionManager.NEVER_KICK) {
IQ response = IQ.createResultIQ(packet);
response.setChildElement(packet.getChildElement().createCopy());
response.setError(PacketError.Condition.forbidden);
return response;
}
int conflictCount = oldSession.incrementConflictCount();
if (conflictCount > conflictLimit) {
// Send a stream:error before closing the old connection
StreamError error = new StreamError(StreamError.Condition.conflict);
oldSession.deliverRawText(error.toXML());
oldSession.close();
} else {
IQ response = IQ.createResultIQ(packet);
response.setChildElement(packet.getChildElement().createCopy());
response.setError(PacketError.Condition.forbidden);
return response;
}
} catch (Exception e) {
Log.error("Error during login", e);
}
}
// Set that the new session has been authenticated successfully
session.setAuthToken(token, resource);
packet.setFrom(session.getAddress());
return IQ.createResultIQ(packet);
}
use of gnu.inet.encoding.StringprepException in project Openfire by igniterealtime.
the class IQRegisterHandler method handleIQ.
@Override
public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
ClientSession session = sessionManager.getSession(packet.getFrom());
IQ reply = null;
// If no session was found then answer an error (if possible)
if (session == null) {
Log.error("Error during registration. Session not found in " + sessionManager.getPreAuthenticatedKeys() + " for key " + packet.getFrom());
// This error packet will probably won't make it through
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.internal_server_error);
return reply;
}
if (IQ.Type.get.equals(packet.getType())) {
// If inband registration is not allowed, return an error.
if (!registrationEnabled) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
} else {
reply = IQ.createResultIQ(packet);
if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
try {
User user = userManager.getUser(session.getUsername());
Element currentRegistration = probeResult.createCopy();
currentRegistration.addElement("registered");
currentRegistration.element("username").setText(user.getUsername());
currentRegistration.element("password").setText("");
currentRegistration.element("email").setText(user.getEmail() == null ? "" : user.getEmail());
currentRegistration.element("name").setText(user.getName());
Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
Iterator fields = form.elementIterator("field");
Element field;
while (fields.hasNext()) {
field = (Element) fields.next();
if ("username".equals(field.attributeValue("var"))) {
field.addElement("value").addText(user.getUsername());
} else if ("name".equals(field.attributeValue("var"))) {
field.addElement("value").addText(user.getName());
} else if ("email".equals(field.attributeValue("var"))) {
field.addElement("value").addText(user.getEmail() == null ? "" : user.getEmail());
}
}
reply.setChildElement(currentRegistration);
} catch (UserNotFoundException e) {
reply.setChildElement(probeResult.createCopy());
}
} else {
// This is a workaround. Since we don't want to have an incorrect TO attribute
// value we need to clean up the TO attribute. The TO attribute will contain an
// incorrect value since we are setting a fake JID until the user actually
// authenticates with the server.
reply.setTo((JID) null);
reply.setChildElement(probeResult.createCopy());
}
}
} else if (IQ.Type.set.equals(packet.getType())) {
try {
Element iqElement = packet.getChildElement();
if (iqElement.element("remove") != null) {
// If inband registration is not allowed, return an error.
if (!registrationEnabled) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
} else {
if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
User user = userManager.getUser(session.getUsername());
// Delete the user
userManager.deleteUser(user);
// Delete the roster of the user
rosterManager.deleteRoster(session.getAddress());
// Delete the user from all the Groups
GroupManager.getInstance().deleteUser(user);
reply = IQ.createResultIQ(packet);
session.process(reply);
// Take a quick nap so that the client can process the result
Thread.sleep(10);
// Close the user's connection
final StreamError error = new StreamError(StreamError.Condition.not_authorized);
for (ClientSession sess : sessionManager.getSessions(user.getUsername())) {
sess.deliverRawText(error.toXML());
sess.close();
}
// The reply has been sent so clean up the variable
reply = null;
} else {
throw new UnauthorizedException();
}
}
} else {
String username;
String password = null;
String email = null;
String name = null;
User newUser;
DataForm registrationForm;
FormField field;
Element formElement = iqElement.element("x");
// Check if a form was used to provide the registration info
if (formElement != null) {
// Get the sent form
registrationForm = new DataForm(formElement);
// Get the username sent in the form
List<String> values = registrationForm.getField("username").getValues();
username = (!values.isEmpty() ? values.get(0) : " ");
// Get the password sent in the form
field = registrationForm.getField("password");
if (field != null) {
values = field.getValues();
password = (!values.isEmpty() ? values.get(0) : " ");
}
// Get the email sent in the form
field = registrationForm.getField("email");
if (field != null) {
values = field.getValues();
email = (!values.isEmpty() ? values.get(0) : " ");
}
// Get the name sent in the form
field = registrationForm.getField("name");
if (field != null) {
values = field.getValues();
name = (!values.isEmpty() ? values.get(0) : " ");
}
} else {
// Get the registration info from the query elements
username = iqElement.elementText("username");
password = iqElement.elementText("password");
email = iqElement.elementText("email");
name = iqElement.elementText("name");
}
if (email != null && email.matches("\\s*")) {
email = null;
}
if (name != null && name.matches("\\s*")) {
name = null;
}
// stringprep validity now.
if (username != null) {
Stringprep.nodeprep(username);
}
if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
// Flag that indicates if the user is *only* changing his password
boolean onlyPassword = false;
if (iqElement.elements().size() == 2 && iqElement.element("username") != null && iqElement.element("password") != null) {
onlyPassword = true;
}
// If users are not allowed to change their password, return an error.
if (password != null && !canChangePassword) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
return reply;
} else // If inband registration is not allowed, return an error.
if (!onlyPassword && !registrationEnabled) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
return reply;
} else {
User user = userManager.getUser(session.getUsername());
if (user.getUsername().equalsIgnoreCase(username)) {
if (password != null && password.trim().length() > 0) {
user.setPassword(password);
}
if (!onlyPassword) {
user.setEmail(email);
}
newUser = user;
} else if (password != null && password.trim().length() > 0) {
// An admin can create new accounts when logged in.
newUser = userManager.createUser(username, password, null, email);
} else {
// Deny registration of users with no password
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_acceptable);
return reply;
}
}
} else {
// If inband registration is not allowed, return an error.
if (!registrationEnabled) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
return reply;
} else // information was not provided
if (password == null || password.trim().length() == 0) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_acceptable);
return reply;
} else {
// Create the new account
newUser = userManager.createUser(username, password, name, email);
}
}
// Set and save the extra user info (e.g. full name, etc.)
if (newUser != null && name != null && !name.equals(newUser.getName())) {
newUser.setName(name);
}
reply = IQ.createResultIQ(packet);
}
} catch (UserAlreadyExistsException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.conflict);
} catch (UserNotFoundException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.bad_request);
} catch (StringprepException e) {
// The specified username is not correct according to the stringprep specs
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.jid_malformed);
} catch (IllegalArgumentException e) {
// At least one of the fields passed in is not valid
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_acceptable);
Log.warn(e.getMessage(), e);
} catch (UnsupportedOperationException e) {
// The User provider is read-only so this operation is not allowed
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_allowed);
} catch (Exception e) {
// Some unexpected error happened so return an internal_server_error
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.internal_server_error);
Log.error(e.getMessage(), e);
}
}
if (reply != null) {
// why is this done here instead of letting the iq handler do it?
session.process(reply);
}
return null;
}
Aggregations