ClientFactory.cs 14 KB

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