SimianUserAccountServiceConnector.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Collections.Specialized;
  30. using System.IO;
  31. using System.Reflection;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Framework.Interfaces;
  34. using OpenSim.Region.Framework.Scenes;
  35. using OpenSim.Services.Interfaces;
  36. using log4net;
  37. using Mono.Addins;
  38. using Nini.Config;
  39. using OpenMetaverse;
  40. using OpenMetaverse.StructuredData;
  41. namespace OpenSim.Services.Connectors.SimianGrid
  42. {
  43. /// <summary>
  44. /// Connects user account data (creating new users, looking up existing
  45. /// users) to the SimianGrid backend
  46. /// </summary>
  47. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
  48. public class SimianUserAccountServiceConnector : IUserAccountService, ISharedRegionModule
  49. {
  50. private static readonly ILog m_log =
  51. LogManager.GetLogger(
  52. MethodBase.GetCurrentMethod().DeclaringType);
  53. private string m_serverUrl = String.Empty;
  54. private ExpiringCache<UUID, UserAccount> m_accountCache;
  55. #region ISharedRegionModule
  56. public Type ReplaceableInterface { get { return null; } }
  57. public void RegionLoaded(Scene scene) { }
  58. public void PostInitialise() { }
  59. public void Close() { }
  60. public SimianUserAccountServiceConnector() { }
  61. public string Name { get { return "SimianUserAccountServiceConnector"; } }
  62. public void AddRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.RegisterModuleInterface<IUserAccountService>(this); } }
  63. public void RemoveRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.UnregisterModuleInterface<IUserAccountService>(this); } }
  64. #endregion ISharedRegionModule
  65. public SimianUserAccountServiceConnector(IConfigSource source)
  66. {
  67. Initialise(source);
  68. }
  69. public void Initialise(IConfigSource source)
  70. {
  71. if (Simian.IsSimianEnabled(source, "UserAccountServices", this.Name))
  72. {
  73. IConfig assetConfig = source.Configs["UserAccountService"];
  74. if (assetConfig == null)
  75. {
  76. m_log.Error("[SIMIAN ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini");
  77. throw new Exception("User account connector init error");
  78. }
  79. string serviceURI = assetConfig.GetString("UserAccountServerURI");
  80. if (String.IsNullOrEmpty(serviceURI))
  81. {
  82. m_log.Error("[SIMIAN ACCOUNT CONNECTOR]: No UserAccountServerURI in section UserAccountService, skipping SimianUserAccountServiceConnector");
  83. throw new Exception("User account connector init error");
  84. }
  85. m_accountCache = new ExpiringCache<UUID, UserAccount>();
  86. m_serverUrl = serviceURI;
  87. }
  88. }
  89. public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
  90. {
  91. NameValueCollection requestArgs = new NameValueCollection
  92. {
  93. { "RequestMethod", "GetUser" },
  94. { "Name", firstName + ' ' + lastName }
  95. };
  96. return GetUser(requestArgs);
  97. }
  98. public UserAccount GetUserAccount(UUID scopeID, string email)
  99. {
  100. NameValueCollection requestArgs = new NameValueCollection
  101. {
  102. { "RequestMethod", "GetUser" },
  103. { "Email", email }
  104. };
  105. return GetUser(requestArgs);
  106. }
  107. public UserAccount GetUserAccount(UUID scopeID, UUID userID)
  108. {
  109. // Cache check
  110. UserAccount account;
  111. if (m_accountCache.TryGetValue(userID, out account))
  112. return account;
  113. NameValueCollection requestArgs = new NameValueCollection
  114. {
  115. { "RequestMethod", "GetUser" },
  116. { "UserID", userID.ToString() }
  117. };
  118. return GetUser(requestArgs);
  119. }
  120. public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
  121. {
  122. List<UserAccount> accounts = new List<UserAccount>();
  123. m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Searching for user accounts with name query " + query);
  124. NameValueCollection requestArgs = new NameValueCollection
  125. {
  126. { "RequestMethod", "GetUsers" },
  127. { "NameQuery", query }
  128. };
  129. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  130. if (response["Success"].AsBoolean())
  131. {
  132. OSDArray array = response["Users"] as OSDArray;
  133. if (array != null && array.Count > 0)
  134. {
  135. for (int i = 0; i < array.Count; i++)
  136. {
  137. UserAccount account = ResponseToUserAccount(array[i] as OSDMap);
  138. if (account != null)
  139. accounts.Add(account);
  140. }
  141. }
  142. else
  143. {
  144. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
  145. }
  146. }
  147. else
  148. {
  149. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to search for account data by name " + query);
  150. }
  151. return accounts;
  152. }
  153. public bool StoreUserAccount(UserAccount data)
  154. {
  155. m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account for " + data.Name);
  156. NameValueCollection requestArgs = new NameValueCollection
  157. {
  158. { "RequestMethod", "AddUser" },
  159. { "UserID", data.PrincipalID.ToString() },
  160. { "Name", data.Name },
  161. { "Email", data.Email },
  162. { "AccessLevel", data.UserLevel.ToString() }
  163. };
  164. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  165. if (response["Success"].AsBoolean())
  166. {
  167. m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account data for " + data.Name);
  168. requestArgs = new NameValueCollection
  169. {
  170. { "RequestMethod", "AddUserData" },
  171. { "UserID", data.PrincipalID.ToString() },
  172. { "CreationDate", data.Created.ToString() },
  173. { "UserFlags", data.UserFlags.ToString() },
  174. { "UserTitle", data.UserTitle }
  175. };
  176. response = WebUtil.PostToService(m_serverUrl, requestArgs);
  177. bool success = response["Success"].AsBoolean();
  178. if (success)
  179. {
  180. // Cache the user account info
  181. m_accountCache.AddOrUpdate(data.PrincipalID, data, DateTime.Now + TimeSpan.FromMinutes(2.0d));
  182. }
  183. else
  184. {
  185. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account data for " + data.Name + ": " + response["Message"].AsString());
  186. }
  187. return success;
  188. }
  189. else
  190. {
  191. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account for " + data.Name + ": " + response["Message"].AsString());
  192. }
  193. return false;
  194. }
  195. /// <summary>
  196. /// Helper method for the various ways of retrieving a user account
  197. /// </summary>
  198. /// <param name="requestArgs">Service query parameters</param>
  199. /// <returns>A UserAccount object on success, null on failure</returns>
  200. private UserAccount GetUser(NameValueCollection requestArgs)
  201. {
  202. string lookupValue = (requestArgs.Count > 1) ? requestArgs[1] : "(Unknown)";
  203. m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Looking up user account with query: " + lookupValue);
  204. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  205. if (response["Success"].AsBoolean())
  206. {
  207. OSDMap user = response["User"] as OSDMap;
  208. if (user != null)
  209. return ResponseToUserAccount(user);
  210. else
  211. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
  212. }
  213. else
  214. {
  215. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to lookup user account with query: " + lookupValue);
  216. }
  217. return null;
  218. }
  219. /// <summary>
  220. /// Convert a User object in LLSD format to a UserAccount
  221. /// </summary>
  222. /// <param name="response">LLSD containing user account data</param>
  223. /// <returns>A UserAccount object on success, null on failure</returns>
  224. private UserAccount ResponseToUserAccount(OSDMap response)
  225. {
  226. if (response == null)
  227. return null;
  228. UserAccount account = new UserAccount();
  229. account.PrincipalID = response["UserID"].AsUUID();
  230. account.Created = response["CreationDate"].AsInteger();
  231. account.Email = response["Email"].AsString();
  232. account.ServiceURLs = new Dictionary<string, object>(0);
  233. account.UserFlags = response["UserFlags"].AsInteger();
  234. account.UserLevel = response["AccessLevel"].AsInteger();
  235. account.UserTitle = response["UserTitle"].AsString();
  236. GetFirstLastName(response["Name"].AsString(), out account.FirstName, out account.LastName);
  237. // Cache the user account info
  238. m_accountCache.AddOrUpdate(account.PrincipalID, account, DateTime.Now + TimeSpan.FromMinutes(2.0d));
  239. return account;
  240. }
  241. /// <summary>
  242. /// Convert a name with a single space in it to a first and last name
  243. /// </summary>
  244. /// <param name="name">A full name such as "John Doe"</param>
  245. /// <param name="firstName">First name</param>
  246. /// <param name="lastName">Last name (surname)</param>
  247. private static void GetFirstLastName(string name, out string firstName, out string lastName)
  248. {
  249. if (String.IsNullOrEmpty(name))
  250. {
  251. firstName = String.Empty;
  252. lastName = String.Empty;
  253. }
  254. else
  255. {
  256. string[] names = name.Split(' ');
  257. if (names.Length == 2)
  258. {
  259. firstName = names[0];
  260. lastName = names[1];
  261. }
  262. else
  263. {
  264. firstName = String.Empty;
  265. lastName = name;
  266. }
  267. }
  268. }
  269. }
  270. }