SimianUserAccountServiceConnector.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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.Reflection;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.Framework.Interfaces;
  33. using OpenSim.Region.Framework.Scenes;
  34. using OpenSim.Services.Interfaces;
  35. using log4net;
  36. using Mono.Addins;
  37. using Nini.Config;
  38. using OpenMetaverse;
  39. using OpenMetaverse.StructuredData;
  40. namespace OpenSim.Services.Connectors.SimianGrid
  41. {
  42. /// <summary>
  43. /// Connects user account data (creating new users, looking up existing
  44. /// users) to the SimianGrid backend
  45. /// </summary>
  46. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianUserAccountServiceConnector")]
  47. public class SimianUserAccountServiceConnector : IUserAccountService, ISharedRegionModule
  48. {
  49. private const double CACHE_EXPIRATION_SECONDS = 120.0;
  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 = new ExpiringCache<UUID,UserAccount>();
  55. private bool m_Enabled;
  56. #region ISharedRegionModule
  57. public Type ReplaceableInterface { get { return null; } }
  58. public void RegionLoaded(Scene scene) { }
  59. public void PostInitialise() { }
  60. public void Close() { }
  61. public SimianUserAccountServiceConnector() { }
  62. public string Name { get { return "SimianUserAccountServiceConnector"; } }
  63. public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IUserAccountService>(this); } }
  64. public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IUserAccountService>(this); } }
  65. #endregion ISharedRegionModule
  66. public SimianUserAccountServiceConnector(IConfigSource source)
  67. {
  68. CommonInit(source);
  69. }
  70. public void Initialise(IConfigSource source)
  71. {
  72. IConfig moduleConfig = source.Configs["Modules"];
  73. if (moduleConfig != null)
  74. {
  75. string name = moduleConfig.GetString("UserAccountServices", "");
  76. if (name == Name)
  77. CommonInit(source);
  78. }
  79. }
  80. private void CommonInit(IConfigSource source)
  81. {
  82. IConfig gridConfig = source.Configs["UserAccountService"];
  83. if (gridConfig != null)
  84. {
  85. string serviceUrl = gridConfig.GetString("UserAccountServerURI");
  86. if (!String.IsNullOrEmpty(serviceUrl))
  87. {
  88. if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
  89. serviceUrl = serviceUrl + '/';
  90. m_serverUrl = serviceUrl;
  91. m_Enabled = true;
  92. }
  93. }
  94. if (String.IsNullOrEmpty(m_serverUrl))
  95. m_log.Info("[SIMIAN ACCOUNT CONNECTOR]: No UserAccountServerURI specified, disabling connector");
  96. }
  97. public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
  98. {
  99. NameValueCollection requestArgs = new NameValueCollection
  100. {
  101. { "RequestMethod", "GetUser" },
  102. { "Name", firstName + ' ' + lastName }
  103. };
  104. return GetUser(requestArgs);
  105. }
  106. public UserAccount GetUserAccount(UUID scopeID, string email)
  107. {
  108. NameValueCollection requestArgs = new NameValueCollection
  109. {
  110. { "RequestMethod", "GetUser" },
  111. { "Email", email }
  112. };
  113. return GetUser(requestArgs);
  114. }
  115. public UserAccount GetUserAccount(UUID scopeID, UUID userID)
  116. {
  117. // Cache check
  118. UserAccount account;
  119. if (m_accountCache.TryGetValue(userID, out account))
  120. return account;
  121. NameValueCollection requestArgs = new NameValueCollection
  122. {
  123. { "RequestMethod", "GetUser" },
  124. { "UserID", userID.ToString() }
  125. };
  126. account = GetUser(requestArgs);
  127. if (account == null)
  128. {
  129. // Store null responses too, to avoid repeated lookups for missing accounts
  130. m_accountCache.AddOrUpdate(userID, null, CACHE_EXPIRATION_SECONDS);
  131. }
  132. return account;
  133. }
  134. public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
  135. {
  136. List<UserAccount> accounts = new List<UserAccount>();
  137. // m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Searching for user accounts with name query " + query);
  138. NameValueCollection requestArgs = new NameValueCollection
  139. {
  140. { "RequestMethod", "GetUsers" },
  141. { "NameQuery", query }
  142. };
  143. OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
  144. if (response["Success"].AsBoolean())
  145. {
  146. OSDArray array = response["Users"] as OSDArray;
  147. if (array != null && array.Count > 0)
  148. {
  149. for (int i = 0; i < array.Count; i++)
  150. {
  151. UserAccount account = ResponseToUserAccount(array[i] as OSDMap);
  152. if (account != null)
  153. accounts.Add(account);
  154. }
  155. }
  156. else
  157. {
  158. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
  159. }
  160. }
  161. else
  162. {
  163. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to search for account data by name " + query);
  164. }
  165. return accounts;
  166. }
  167. public void InvalidateCache(UUID userID)
  168. {
  169. m_accountCache.Remove(userID);
  170. }
  171. public bool StoreUserAccount(UserAccount data)
  172. {
  173. // m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account for " + data.Name);
  174. NameValueCollection requestArgs = new NameValueCollection
  175. {
  176. { "RequestMethod", "AddUser" },
  177. { "UserID", data.PrincipalID.ToString() },
  178. { "Name", data.Name },
  179. { "Email", data.Email },
  180. { "AccessLevel", data.UserLevel.ToString() }
  181. };
  182. OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
  183. if (response["Success"].AsBoolean())
  184. {
  185. m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account data for " + data.Name);
  186. requestArgs = new NameValueCollection
  187. {
  188. { "RequestMethod", "AddUserData" },
  189. { "UserID", data.PrincipalID.ToString() },
  190. { "CreationDate", data.Created.ToString() },
  191. { "UserFlags", data.UserFlags.ToString() },
  192. { "UserTitle", data.UserTitle }
  193. };
  194. response = SimianGrid.PostToService(m_serverUrl, requestArgs);
  195. bool success = response["Success"].AsBoolean();
  196. if (success)
  197. {
  198. // Cache the user account info
  199. m_accountCache.AddOrUpdate(data.PrincipalID, data, CACHE_EXPIRATION_SECONDS);
  200. }
  201. else
  202. {
  203. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account data for " + data.Name + ": " + response["Message"].AsString());
  204. }
  205. return success;
  206. }
  207. else
  208. {
  209. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account for " + data.Name + ": " + response["Message"].AsString());
  210. }
  211. return false;
  212. }
  213. /// <summary>
  214. /// Helper method for the various ways of retrieving a user account
  215. /// </summary>
  216. /// <param name="requestArgs">Service query parameters</param>
  217. /// <returns>A UserAccount object on success, null on failure</returns>
  218. private UserAccount GetUser(NameValueCollection requestArgs)
  219. {
  220. string lookupValue = (requestArgs.Count > 1) ? requestArgs[1] : "(Unknown)";
  221. // m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Looking up user account with query: " + lookupValue);
  222. OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
  223. if (response["Success"].AsBoolean())
  224. {
  225. OSDMap user = response["User"] as OSDMap;
  226. if (user != null)
  227. return ResponseToUserAccount(user);
  228. else
  229. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
  230. }
  231. else
  232. {
  233. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to lookup user account with query: " + lookupValue);
  234. }
  235. return null;
  236. }
  237. /// <summary>
  238. /// Convert a User object in LLSD format to a UserAccount
  239. /// </summary>
  240. /// <param name="response">LLSD containing user account data</param>
  241. /// <returns>A UserAccount object on success, null on failure</returns>
  242. private UserAccount ResponseToUserAccount(OSDMap response)
  243. {
  244. if (response == null)
  245. return null;
  246. UserAccount account = new UserAccount();
  247. account.PrincipalID = response["UserID"].AsUUID();
  248. account.Created = response["CreationDate"].AsInteger();
  249. account.Email = response["Email"].AsString();
  250. account.ServiceURLs = new Dictionary<string, object>(0);
  251. account.UserFlags = response["UserFlags"].AsInteger();
  252. account.UserLevel = response["AccessLevel"].AsInteger();
  253. account.UserTitle = response["UserTitle"].AsString();
  254. account.LocalToGrid = true;
  255. if (response.ContainsKey("LocalToGrid"))
  256. account.LocalToGrid = (response["LocalToGrid"].AsString() == "true" ? true : false);
  257. GetFirstLastName(response["Name"].AsString(), out account.FirstName, out account.LastName);
  258. // Cache the user account info
  259. m_accountCache.AddOrUpdate(account.PrincipalID, account, CACHE_EXPIRATION_SECONDS);
  260. return account;
  261. }
  262. /// <summary>
  263. /// Convert a name with a single space in it to a first and last name
  264. /// </summary>
  265. /// <param name="name">A full name such as "John Doe"</param>
  266. /// <param name="firstName">First name</param>
  267. /// <param name="lastName">Last name (surname)</param>
  268. private static void GetFirstLastName(string name, out string firstName, out string lastName)
  269. {
  270. if (String.IsNullOrEmpty(name))
  271. {
  272. firstName = String.Empty;
  273. lastName = String.Empty;
  274. }
  275. else
  276. {
  277. string[] names = name.Split(' ');
  278. if (names.Length == 2)
  279. {
  280. firstName = names[0];
  281. lastName = names[1];
  282. }
  283. else
  284. {
  285. firstName = String.Empty;
  286. lastName = name;
  287. }
  288. }
  289. }
  290. }
  291. }