SimianUserAccountServiceConnector.cs 13 KB

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