1
0

SimianUserAccountServiceConnector.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 List<UserAccount> GetUserAccountsWhere(UUID scopeID, string query)
  172. {
  173. return null;
  174. }
  175. public List<UserAccount> GetUserAccounts(UUID scopeID, List<string> IDs)
  176. {
  177. return null;
  178. }
  179. public bool StoreUserAccount(UserAccount data)
  180. {
  181. // m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account for " + data.Name);
  182. NameValueCollection requestArgs = new NameValueCollection
  183. {
  184. { "RequestMethod", "AddUser" },
  185. { "UserID", data.PrincipalID.ToString() },
  186. { "Name", data.Name },
  187. { "Email", data.Email },
  188. { "AccessLevel", data.UserLevel.ToString() }
  189. };
  190. OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
  191. if (response["Success"].AsBoolean())
  192. {
  193. m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account data for " + data.Name);
  194. requestArgs = new NameValueCollection
  195. {
  196. { "RequestMethod", "AddUserData" },
  197. { "UserID", data.PrincipalID.ToString() },
  198. { "CreationDate", data.Created.ToString() },
  199. { "UserFlags", data.UserFlags.ToString() },
  200. { "UserTitle", data.UserTitle }
  201. };
  202. response = SimianGrid.PostToService(m_serverUrl, requestArgs);
  203. bool success = response["Success"].AsBoolean();
  204. if (success)
  205. {
  206. // Cache the user account info
  207. m_accountCache.AddOrUpdate(data.PrincipalID, data, CACHE_EXPIRATION_SECONDS);
  208. }
  209. else
  210. {
  211. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account data for " + data.Name + ": " + response["Message"].AsString());
  212. }
  213. return success;
  214. }
  215. else
  216. {
  217. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account for " + data.Name + ": " + response["Message"].AsString());
  218. }
  219. return false;
  220. }
  221. /// <summary>
  222. /// Helper method for the various ways of retrieving a user account
  223. /// </summary>
  224. /// <param name="requestArgs">Service query parameters</param>
  225. /// <returns>A UserAccount object on success, null on failure</returns>
  226. private UserAccount GetUser(NameValueCollection requestArgs)
  227. {
  228. string lookupValue = (requestArgs.Count > 1) ? requestArgs[1] : "(Unknown)";
  229. // m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Looking up user account with query: " + lookupValue);
  230. OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
  231. if (response["Success"].AsBoolean())
  232. {
  233. OSDMap user = response["User"] as OSDMap;
  234. if (user != null)
  235. return ResponseToUserAccount(user);
  236. else
  237. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
  238. }
  239. else
  240. {
  241. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to lookup user account with query: " + lookupValue);
  242. }
  243. return null;
  244. }
  245. /// <summary>
  246. /// Convert a User object in LLSD format to a UserAccount
  247. /// </summary>
  248. /// <param name="response">LLSD containing user account data</param>
  249. /// <returns>A UserAccount object on success, null on failure</returns>
  250. private UserAccount ResponseToUserAccount(OSDMap response)
  251. {
  252. if (response == null)
  253. return null;
  254. UserAccount account = new UserAccount();
  255. account.PrincipalID = response["UserID"].AsUUID();
  256. account.Created = response["CreationDate"].AsInteger();
  257. account.Email = response["Email"].AsString();
  258. account.ServiceURLs = new Dictionary<string, object>(0);
  259. account.UserFlags = response["UserFlags"].AsInteger();
  260. account.UserLevel = response["AccessLevel"].AsInteger();
  261. account.UserTitle = response["UserTitle"].AsString();
  262. account.LocalToGrid = true;
  263. if (response.ContainsKey("LocalToGrid"))
  264. account.LocalToGrid = (response["LocalToGrid"].AsString() == "true" ? true : false);
  265. GetFirstLastName(response["Name"].AsString(), out account.FirstName, out account.LastName);
  266. // Cache the user account info
  267. m_accountCache.AddOrUpdate(account.PrincipalID, account, CACHE_EXPIRATION_SECONDS);
  268. return account;
  269. }
  270. /// <summary>
  271. /// Convert a name with a single space in it to a first and last name
  272. /// </summary>
  273. /// <param name="name">A full name such as "John Doe"</param>
  274. /// <param name="firstName">First name</param>
  275. /// <param name="lastName">Last name (surname)</param>
  276. private static void GetFirstLastName(string name, out string firstName, out string lastName)
  277. {
  278. if (String.IsNullOrEmpty(name))
  279. {
  280. firstName = String.Empty;
  281. lastName = String.Empty;
  282. }
  283. else
  284. {
  285. string[] names = name.Split(' ');
  286. if (names.Length == 2)
  287. {
  288. firstName = names[0];
  289. lastName = names[1];
  290. }
  291. else
  292. {
  293. firstName = String.Empty;
  294. lastName = name;
  295. }
  296. }
  297. }
  298. }
  299. }