ClientFactory.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using InABox.Configuration;
  6. using InABox.Core;
  7. using InABox.Mail;
  8. namespace InABox.Clients
  9. {
  10. public class BypassSession : IDisposable
  11. {
  12. public BypassSession()
  13. {
  14. ClientFactory.SetBypass();
  15. }
  16. public void Dispose()
  17. {
  18. ClientFactory.UnsetBypass();
  19. }
  20. }
  21. public static class ClientFactory
  22. {
  23. public static Dictionary<EmailType, Type> MailerTypes = new Dictionary<EmailType, Type>();
  24. public static Guid UserGuid { get; private set; }
  25. public static string UserID { get; private set; }
  26. public static Guid UserSecurityID { get; private set; }
  27. public static Guid SessionID { get; private set; }
  28. public static Guid DatabaseID { get; set; }
  29. public static Platform Platform { get; private set; }
  30. public static string? Version { get; private set; }
  31. public static Type? ClientType { get; private set; }
  32. public static object[]? Parameters { get; private set; }
  33. public static IEnumerable<string>? SupportedTypes { get; private set; }
  34. public static string? Recipient2FA { get; private set; }
  35. public static DateTime PasswordExpiration { get; private set; }
  36. public static int PINLength { get; } = 4;
  37. public static PushHandlers PushHandlers { get; private set; } = new PushHandlers();
  38. public delegate void RequestErrorHandler(RequestException e);
  39. public static event RequestErrorHandler? OnRequestError;
  40. public static void RaiseRequestError(RequestException e)
  41. {
  42. OnRequestError?.Invoke(e);
  43. }
  44. public static bool IsSupported<T>() where T : Entity, new()
  45. {
  46. return true;
  47. }
  48. public static bool IsSupported<T1, T2>() where T1 : Entity, new() where T2 : Entity, new()
  49. {
  50. return IsSupported<T1>() && IsSupported<T2>();
  51. }
  52. public static bool IsSupported<T1, T2, T3>() where T1 : Entity, new() where T2 : Entity, new() where T3 : Entity, new()
  53. {
  54. return IsSupported<T1>() && IsSupported<T2>() && IsSupported<T3>();
  55. }
  56. public static bool IsSupported<T1, T2, T3, T4>() where T1 : Entity, new()
  57. where T2 : Entity, new()
  58. where T3 : Entity, new()
  59. where T4 : Entity, new()
  60. {
  61. return IsSupported<T1>() && IsSupported<T2>() && IsSupported<T3>() && IsSupported<T4>();
  62. }
  63. public static bool IsSupported<T1, T2, T3, T4, T5>() where T1 : Entity, new()
  64. where T2 : Entity, new()
  65. where T3 : Entity, new()
  66. where T4 : Entity, new()
  67. where T5 : Entity, new()
  68. {
  69. return IsSupported<T1>() && IsSupported<T2>() && IsSupported<T3>() && IsSupported<T4>() && IsSupported<T4>();
  70. }
  71. public static bool IsSupported(params Type[] types)
  72. {
  73. return true;
  74. }
  75. public static void SetClientType(Type type, Platform platform, string? version, params object[]? parameters)
  76. {
  77. ClientType = type;
  78. Platform = platform;
  79. Version = String.IsNullOrEmpty(version) ? Version : version;
  80. Parameters = parameters == null ? Parameters : parameters;
  81. SupportedTypes = parameters == null ? SupportedTypes : null;
  82. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  83. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  84. }
  85. public static void ClearClientType()
  86. {
  87. ClientType = null;
  88. Platform = default(Platform);
  89. Version = "";
  90. Parameters = null;
  91. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  92. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  93. }
  94. // override the need to provide credentials when configuring the database
  95. public static void SetBypass()
  96. {
  97. UserGuid = CoreUtils.FullGuid;
  98. UserID = "";
  99. Request.BeforeRequest = request =>
  100. {
  101. if(request is ValidateRequest validate)
  102. {
  103. var ticks = DateTime.Now.ToUniversalTime().Ticks.ToString();
  104. validate.UserID = Encryption.Encrypt(ticks, "wCq9rryEJEuHIifYrxRjxg", true);
  105. validate.Password = Encryption.Encrypt(ticks, "7mhvLnqMwkCAzN+zNGlyyg", true);
  106. }
  107. };
  108. var ticks = DateTime.Now.ToUniversalTime().Ticks.ToString();
  109. var result = Validate(
  110. Encryption.Encrypt(ticks, "wCq9rryEJEuHIifYrxRjxg", true),
  111. Encryption.Encrypt(ticks, "7mhvLnqMwkCAzN+zNGlyyg", true));
  112. if (result != ValidationStatus.VALID)
  113. {
  114. Logger.Send(LogType.Error, "", "Bypass login failed");
  115. }
  116. //Load up the data model, including Custom Properties
  117. //var props = CreateClient<CustomProperty>().Load();
  118. //DatabaseSchema.Load(props);
  119. }
  120. public static void UnsetBypass()
  121. {
  122. Request.BeforeRequest = null;
  123. UserGuid = Guid.Empty;
  124. }
  125. public static ValidationStatus Validate(string userid, string password, Guid session = default)
  126. {
  127. InvalidateUser();
  128. var result = Client.Validate(userid, password, session);
  129. if (result.Status != ValidationStatus.INVALID)
  130. {
  131. UserGuid = result.UserGuid;
  132. UserID = result.UserID;
  133. UserSecurityID = result.SecurityID;
  134. Recipient2FA = result.Recipient2FA;
  135. SessionID = result.SessionID;
  136. PasswordExpiration = result.PasswordExpiration;
  137. if(result.Status == ValidationStatus.VALID)
  138. {
  139. OnValidLogin();
  140. }
  141. return result.Status;
  142. }
  143. return result.Status;
  144. }
  145. public static ValidationStatus Validate(string pin, Guid session = default)
  146. {
  147. InvalidateUser();
  148. var result = Client.Validate(pin, session);
  149. if (result.Status != ValidationStatus.INVALID)
  150. {
  151. UserGuid = result.UserGuid;
  152. UserID = result.UserID;
  153. UserSecurityID = result.SecurityID;
  154. Recipient2FA = result.Recipient2FA;
  155. SessionID = result.SessionID;
  156. PasswordExpiration = result.PasswordExpiration;
  157. if (result.Status == ValidationStatus.VALID)
  158. {
  159. OnValidLogin();
  160. }
  161. return result.Status;
  162. }
  163. return result.Status;
  164. }
  165. public static ValidationStatus Validate(Guid session)
  166. {
  167. var result = Client.Validate(session);
  168. if (result.Status != ValidationStatus.INVALID)
  169. {
  170. UserGuid = result.UserGuid;
  171. UserID = result.UserID;
  172. UserSecurityID = result.SecurityID;
  173. Recipient2FA = result.Recipient2FA;
  174. SessionID = result.SessionID;
  175. PasswordExpiration = result.PasswordExpiration;
  176. if (result.Status == ValidationStatus.VALID)
  177. {
  178. OnValidLogin();
  179. }
  180. return result.Status;
  181. }
  182. return result.Status;
  183. }
  184. public static bool ValidateUser(string userid, string password)
  185. {
  186. InvalidateUser();
  187. var result = Client.Validate(userid, password);
  188. if (result.Status == ValidationStatus.VALID)
  189. {
  190. UserGuid = result.UserGuid;
  191. UserID = result.UserID;
  192. UserSecurityID = result.SecurityID;
  193. Recipient2FA = result.Recipient2FA;
  194. SessionID = result.SessionID;
  195. PasswordExpiration = result.PasswordExpiration;
  196. if (result.Status == ValidationStatus.VALID)
  197. {
  198. OnValidLogin();
  199. }
  200. return true;
  201. }
  202. return false;
  203. }
  204. public static bool ValidatePIN(string pin)
  205. {
  206. InvalidateUser();
  207. var result = Client.Validate(pin);
  208. if (result.Status == ValidationStatus.VALID)
  209. {
  210. UserGuid = result.UserGuid;
  211. UserID = result.UserID;
  212. UserSecurityID = result.SecurityID;
  213. Recipient2FA = result.Recipient2FA;
  214. SessionID = result.SessionID;
  215. PasswordExpiration = result.PasswordExpiration;
  216. if (result.Status == ValidationStatus.VALID)
  217. {
  218. OnValidLogin();
  219. }
  220. return true;
  221. }
  222. return false;
  223. }
  224. public static bool Check2FA(string code, Guid? session = null)
  225. {
  226. var result = Client.Check2FA(code, session);
  227. if (result)
  228. {
  229. OnValidLogin();
  230. }
  231. return result;
  232. }
  233. public static void OnValidLogin()
  234. {
  235. //Load up the data model, including Custom Properties
  236. var props = new Client<CustomProperty>().Load();
  237. DatabaseSchema.Load(props);
  238. }
  239. public static void InvalidateUser()
  240. {
  241. //CurrentUser = null;
  242. UserGuid = Guid.Empty;
  243. UserID = "";
  244. UserSecurityID = Guid.Empty;
  245. SessionID = Guid.Empty;
  246. InABox.Core.Security.Reset();
  247. }
  248. public static event LogEvent? OnLog;
  249. public static IClient<TEntity> CreateClient<TEntity>() where TEntity : Entity, new()
  250. {
  251. var type = ClientType.MakeGenericType(typeof(TEntity));
  252. var client = (IClient<TEntity>)Activator.CreateInstance(type, Parameters);
  253. client.OnLog += OnLog;
  254. return client;
  255. }
  256. public static IClient CreateClient(Type t)
  257. {
  258. var type = ClientType.MakeGenericType(t);
  259. var client = (IClient)Activator.CreateInstance(type, Parameters);
  260. client.OnLog += OnLog;
  261. return client;
  262. }
  263. public static CoreTable[] MultiQuery(params IQueryDef[] queries)
  264. {
  265. var tasks = new Dictionary<object, Task<CoreTable>>();
  266. for (var i = 0; i < queries.Length; i++)
  267. {
  268. var def = queries[i];
  269. var task = Task.Run(() => { return CreateClient(def.Type).Query(def.Filter, def.Columns, def.SortOrder); });
  270. tasks[i] = task;
  271. }
  272. Task.WaitAll(tasks.Values.ToArray());
  273. var results = new List<CoreTable>();
  274. for (var i = 0; i < queries.Length; i++)
  275. results.Add(tasks[i].Result);
  276. return results.ToArray();
  277. }
  278. public static void MultiQuery(IQueryDef[] queries, Action<CoreTable[]> OnResults)
  279. {
  280. Task.Run(() =>
  281. {
  282. var tasks = new Dictionary<object, Task<CoreTable>>();
  283. for (var i = 0; i < queries.Length; i++)
  284. {
  285. var def = queries[i];
  286. var task = Task.Run(() => { return CreateClient(def.Type).Query(def.Filter, def.Columns, def.SortOrder); });
  287. tasks[i] = task;
  288. }
  289. Task.WaitAll(tasks.Values.ToArray());
  290. var results = new List<CoreTable>();
  291. for (var i = 0; i < queries.Length; i++)
  292. results.Add(tasks[i].Result);
  293. OnResults.Invoke(results.ToArray());
  294. });
  295. }
  296. public static void RegisterMailer(EmailType type, Type mailer)
  297. {
  298. MailerTypes[type] = mailer;
  299. }
  300. public static ICoreMailer? CreateMailer()
  301. {
  302. var row = new Client<User>().Query(
  303. new Filter<User>(x => x.ID).IsEqualTo(UserGuid),
  304. Columns.None<User>().Add(
  305. x => x.EmailType,
  306. x => x.EmailHost,
  307. x => x.EmailPort,
  308. x => x.EmailDomain,
  309. x => x.EmailUserID,
  310. x => x.EmailPassword,
  311. x => x.SMTPHost,
  312. x => x.SMPTPort,
  313. x => x.SMTPUserName,
  314. x => x.SMTPPassword)
  315. ).Rows.FirstOrDefault();
  316. if (row == null)
  317. return null;
  318. var type = row.Get<User, EmailType>(x => x.EmailType);
  319. if (type == EmailType.None)
  320. return null;
  321. var result = (Activator.CreateInstance(MailerTypes[type]) as ICoreMailer)!;
  322. result.MailboxHost = row.Get<User, string>(x => x.EmailHost);
  323. result.MailboxPort = row.Get<User, int>(x => x.EmailPort);
  324. result.MailboxDomain = row.Get<User, string>(x => x.EmailDomain);
  325. result.MailboxUserName = row.Get<User, string>(x => x.EmailUserID);
  326. result.MailboxPassword = row.Get<User, string>(x => x.EmailPassword);
  327. result.SMTPHost = row.Get<User, string>(x => x.SMTPHost);
  328. result.SMTPPort = row.Get<User, int>(x => x.SMPTPort);
  329. result.SMTPUserName = row.Get<User, string>(x => x.SMTPUserName);
  330. result.SMTPPassword = row.Get<User, string>(x => x.SMTPPassword);
  331. return result;
  332. }
  333. }
  334. }