SimianUserAccountServiceConnector.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 const double CACHE_EXPIRATION_SECONDS = 120.0;
  51. private static readonly ILog m_log =
  52. LogManager.GetLogger(
  53. MethodBase.GetCurrentMethod().DeclaringType);
  54. private string m_serverUrl = String.Empty;
  55. private ExpiringCache<UUID, UserAccount> m_accountCache;
  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 (!String.IsNullOrEmpty(m_serverUrl)) { scene.RegisterModuleInterface<IUserAccountService>(this); } }
  64. public void RemoveRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.UnregisterModuleInterface<IUserAccountService>(this); } }
  65. #endregion ISharedRegionModule
  66. public SimianUserAccountServiceConnector(IConfigSource source)
  67. {
  68. Initialise(source);
  69. }
  70. public void Initialise(IConfigSource source)
  71. {
  72. if (Simian.IsSimianEnabled(source, "UserAccountServices", this.Name))
  73. {
  74. IConfig assetConfig = source.Configs["UserAccountService"];
  75. if (assetConfig == null)
  76. {
  77. m_log.Error("[SIMIAN ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini");
  78. throw new Exception("User account connector init error");
  79. }
  80. string serviceURI = assetConfig.GetString("UserAccountServerURI");
  81. if (String.IsNullOrEmpty(serviceURI))
  82. {
  83. m_log.Error("[SIMIAN ACCOUNT CONNECTOR]: No UserAccountServerURI in section UserAccountService, skipping SimianUserAccountServiceConnector");
  84. throw new Exception("User account connector init error");
  85. }
  86. m_accountCache = new ExpiringCache<UUID, UserAccount>();
  87. m_serverUrl = serviceURI;
  88. }
  89. }
  90. public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
  91. {
  92. NameValueCollection requestArgs = new NameValueCollection
  93. {
  94. { "RequestMethod", "GetUser" },
  95. { "Name", firstName + ' ' + lastName }
  96. };
  97. return GetUser(requestArgs);
  98. }
  99. public UserAccount GetUserAccount(UUID scopeID, string email)
  100. {
  101. NameValueCollection requestArgs = new NameValueCollection
  102. {
  103. { "RequestMethod", "GetUser" },
  104. { "Email", email }
  105. };
  106. return GetUser(requestArgs);
  107. }
  108. public UserAccount GetUserAccount(UUID scopeID, UUID userID)
  109. {
  110. // Cache check
  111. UserAccount account;
  112. if (m_accountCache.TryGetValue(userID, out account))
  113. return account;
  114. NameValueCollection requestArgs = new NameValueCollection
  115. {
  116. { "RequestMethod", "GetUser" },
  117. { "UserID", userID.ToString() }
  118. };
  119. return GetUser(requestArgs);
  120. }
  121. public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
  122. {
  123. List<UserAccount> accounts = new List<UserAccount>();
  124. m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Searching for user accounts with name query " + query);
  125. NameValueCollection requestArgs = new NameValueCollection
  126. {
  127. { "RequestMethod", "GetUsers" },
  128. { "NameQuery", query }
  129. };
  130. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  131. if (response["Success"].AsBoolean())
  132. {
  133. OSDArray array = response["Users"] as OSDArray;
  134. if (array != null && array.Count > 0)
  135. {
  136. for (int i = 0; i < array.Count; i++)
  137. {
  138. UserAccount account = ResponseToUserAccount(array[i] as OSDMap);
  139. if (account != null)
  140. accounts.Add(account);
  141. }
  142. }
  143. else
  144. {
  145. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
  146. }
  147. }
  148. else
  149. {
  150. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to search for account data by name " + query);
  151. }
  152. return accounts;
  153. }
  154. public bool StoreUserAccount(UserAccount data)
  155. {
  156. m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account for " + data.Name);
  157. NameValueCollection requestArgs = new NameValueCollection
  158. {
  159. { "RequestMethod", "AddUser" },
  160. { "UserID", data.PrincipalID.ToString() },
  161. { "Name", data.Name },
  162. { "Email", data.Email },
  163. { "AccessLevel", data.UserLevel.ToString() }
  164. };
  165. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  166. if (response["Success"].AsBoolean())
  167. {
  168. m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account data for " + data.Name);
  169. requestArgs = new NameValueCollection
  170. {
  171. { "RequestMethod", "AddUserData" },
  172. { "UserID", data.PrincipalID.ToString() },
  173. { "CreationDate", data.Created.ToString() },
  174. { "UserFlags", data.UserFlags.ToString() },
  175. { "UserTitle", data.UserTitle }
  176. };
  177. response = WebUtil.PostToService(m_serverUrl, requestArgs);
  178. bool success = response["Success"].AsBoolean();
  179. if (success)
  180. {
  181. // Cache the user account info
  182. m_accountCache.AddOrUpdate(data.PrincipalID, data, CACHE_EXPIRATION_SECONDS);
  183. }
  184. else
  185. {
  186. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account data for " + data.Name + ": " + response["Message"].AsString());
  187. }
  188. return success;
  189. }
  190. else
  191. {
  192. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account for " + data.Name + ": " + response["Message"].AsString());
  193. }
  194. return false;
  195. }
  196. /// <summary>
  197. /// Helper method for the various ways of retrieving a user account
  198. /// </summary>
  199. /// <param name="requestArgs">Service query parameters</param>
  200. /// <returns>A UserAccount object on success, null on failure</returns>
  201. private UserAccount GetUser(NameValueCollection requestArgs)
  202. {
  203. string lookupValue = (requestArgs.Count > 1) ? requestArgs[1] : "(Unknown)";
  204. m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Looking up user account with query: " + lookupValue);
  205. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  206. if (response["Success"].AsBoolean())
  207. {
  208. OSDMap user = response["User"] as OSDMap;
  209. if (user != null)
  210. return ResponseToUserAccount(user);
  211. else
  212. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format");
  213. }
  214. else
  215. {
  216. m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to lookup user account with query: " + lookupValue);
  217. }
  218. return null;
  219. }
  220. /// <summary>
  221. /// Convert a User object in LLSD format to a UserAccount
  222. /// </summary>
  223. /// <param name="response">LLSD containing user account data</param>
  224. /// <returns>A UserAccount object on success, null on failure</returns>
  225. private UserAccount ResponseToUserAccount(OSDMap response)
  226. {
  227. if (response == null)
  228. return null;
  229. UserAccount account = new UserAccount();
  230. account.PrincipalID = response["UserID"].AsUUID();
  231. account.Created = response["CreationDate"].AsInteger();
  232. account.Email = response["Email"].AsString();
  233. account.ServiceURLs = new Dictionary<string, object>(0);
  234. account.UserFlags = response["UserFlags"].AsInteger();
  235. account.UserLevel = response["AccessLevel"].AsInteger();
  236. account.UserTitle = response["UserTitle"].AsString();
  237. GetFirstLastName(response["Name"].AsString(), out account.FirstName, out account.LastName);
  238. // Cache the user account info
  239. m_accountCache.AddOrUpdate(account.PrincipalID, account, CACHE_EXPIRATION_SECONDS);
  240. return account;
  241. }
  242. /// <summary>
  243. /// Convert a name with a single space in it to a first and last name
  244. /// </summary>
  245. /// <param name="name">A full name such as "John Doe"</param>
  246. /// <param name="firstName">First name</param>
  247. /// <param name="lastName">Last name (surname)</param>
  248. private static void GetFirstLastName(string name, out string firstName, out string lastName)
  249. {
  250. if (String.IsNullOrEmpty(name))
  251. {
  252. firstName = String.Empty;
  253. lastName = String.Empty;
  254. }
  255. else
  256. {
  257. string[] names = name.Split(' ');
  258. if (names.Length == 2)
  259. {
  260. firstName = names[0];
  261. lastName = names[1];
  262. }
  263. else
  264. {
  265. firstName = String.Empty;
  266. lastName = name;
  267. }
  268. }
  269. }
  270. }
  271. }